Skip to content

fix(opts): validate --run-count (Refs #426 phase 2a) - #429

Merged
fcostaoliveira merged 1 commit into
redis:masterfrom
filipecosta90:fix/issue-426-phase2a-run-count-validation
Jun 1, 2026
Merged

fcostaoliveira merged 1 commit into
redis:masterfrom
filipecosta90:fix/issue-426-phase2a-run-count-validation

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented Jun 1, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • --run-count=-1 and --run-count=2147483647 previously triggered SIGABRT (std::bad_alloc): the parser cast straight to unsigned int (so -1 wrapped to ~4.3B) and had no 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, rejects empty/non-numeric input, rejects zero/negative, and caps at MAX_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).
  • Each rejection prints a readable error to stderr and bubbles through the existing -1 -> usage() -> exit(2) path, matching the style of every other option-parsing error in memtier_benchmark.cpp.

Items closed from #426

  • Item 4: --run-count -1 -> SIGABRT, std::bad_alloc
  • Item 5: --run-count 2147483647 (INT_MAX) -> SIGABRT, std::bad_alloc

The tests/cli_fuzz.py strategy exclusion for --run-count is 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, mirrors tests/test_monitor_input.py and tests/test_mget_validation.py):

  • --run-count=-1 -> non-zero exit, stderr contains run count must be greater than zero
  • --run-count=0 -> non-zero exit, stderr contains run count must be greater than zero
  • --run-count=2147483647 -> non-zero exit, stderr contains run count must be <=
  • --run-count=2 -> end-to-end run, mb.json contains BEST RUN RESULTS and WORST RUN RESULTS sections

Run:

TEST=test_cli_validation_run_count.py OSS_STANDALONE=1 ./tests/run_tests.sh
# Total Tests Run: 4, Total Tests Failed: 0, Total Tests Passed: 4

Also verified:

  • make -j clean build on the changed file.
  • make format-check clean on the changed file (clang-format --dry-run --Werror memtier_benchmark.cpp exits 0).
  • Pre-commit hook (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-count is validated at CLI parse time so invalid values no longer crash the process with std::bad_alloc before benchmarking starts (issue #426).

Parsing now uses signed strtol instead of strtoul, so negative values (e.g. -1) are rejected instead of wrapping to a huge unsigned and forcing massive per-run vector reservations in main(). Zero, non-numeric input, and overflow get clear stderr errors. A new MAX_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.py cover rejections for -1, 0, and 2147483647, plus an end-to-end run with --run-count=2 that checks BEST/WORST JSON sections.

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

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]>
@fcostaoliveira fcostaoliveira added this to the 2.4 milestone Jun 1, 2026
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Review: docs & commit message (haiku 4.5)

Verdict: Commits clean; DEVELOPMENT.md needs run-count validation bounds.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

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.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Review: design & API (sonnet 4.6)

Verdict: Correct fix, cleanly scoped; the MAX_RUN_COUNT constant placement and the divergence with the rest of the option-parsing patterns are the main concerns.

  • MAX_RUN_COUNT defined at file scope in .cpp (load-bearing for the series): The constant is defined with #define MAX_RUN_COUNT 1024 near the top of memtier_benchmark.cpp, below the log-level global. It is therefore invisible to external tools, test harnesses, and future protocol layers. MAX_RUN_COUNT, MEMTIER_PIPELINE_MAX (PR fix(opts): validate --pipeline / --data-size / --data-size-list size (Refs #426 phase 2b) #428), and MEMTIER_DATA_SIZE_MAX (PR fix(opts): validate --pipeline / --data-size / --data-size-list size (Refs #426 phase 2b) #428) are three related caps introduced across the series — they should be co-located in a header (e.g. as constexpr values in memtier_benchmark.h) so an operator reading the header can see all enforced limits at once.

  • strtol + errno pattern diverges from the rest of the series: This PR correctly uses signed strtol and sets errno = 0 before the call. PR fix(opts): validate --pipeline / --data-size / --data-size-list size (Refs #426 phase 2b) #428 uses strtoul + a pre-check helper. The two patterns are not interchangeable: strtol silently saturates to LONG_MAX on overflow and sets errno = ERANGE, while strtoul wraps. A unified parse_bounded_uint helper (as suggested in the fix(opts): validate --command / --command-ratio at parse time (Refs #426 phase 2c) #427 review) would eliminate this divergence across the series.

  • errno == ERANGE check placed after the sign of parsed_run_count: The current ordering is: parse, check ERANGE, check <= 0, check > MAX_RUN_COUNT. If optarg = "9999999999" (overflows long), strtol returns LONG_MAX and sets errno = ERANGE. The ERANGE branch correctly catches this. However, if optarg = "-9999999999" (underflows to LONG_MIN), strtol also sets ERANGE and returns LONG_MIN which is < 0 — the ERANGE check catches it first, so the message "must be a positive integer" is shown rather than "must be greater than zero". Either message is correct, but the distinction between "not an integer" and "negative" is lost for the underflow case.

  • cli_fuzz.py exclusion left in place: The PR description notes the fuzz exclusion for --run-count is intentionally retained pending a follow-up. This is fine, but the follow-up should be tracked as a concrete issue/PR reference in the comment, not just in the PR body. A // TODO(#NNN): re-enable --run-count fuzz after fix landed comment at the exclusion site would make it easier to find and close.

  • Happy-path test uses env.skipOnCluster() without explanation: test_run_count_valid_runs_normally skips on cluster mode. The reason (presumably BEST/WORST JSON structure differs in cluster mode) is not stated. Adding a brief comment or a reason= argument to the skip call — matching the style of other skips in the test suite — would make the constraint self-documenting.

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

  • LOAD-BEARING: this is the cleanest of the phase-2 PRs from a validation correctness lens. errno = 0; + signed strtol + explicit ERANGE check + parsed_run_count <= 0 reject + MAX_RUN_COUNT cap correctly closes both reported repros: -1 no longer wraps to ~4.3B, and INT_MAX is rejected by the upper bound before allocator OOM. No signed-to-unsigned cast sneaks through because the bounds (0 < parsed <= 1024) are checked on the long before the narrow to unsigned int at the end.
  • MAX_RUN_COUNT = 1024 is a sane cap and the rationale (pre-run per-run vectors growing linearly) is correct — main() allocates run_stats[run_count] and HDR per-run state up front, so this is the right place to bound it.
  • endptr check: optarg[0] == '\0' || !endptr || *endptr != '\0' correctly rejects empty and trailing-junk inputs. Note: strtol never sets endptr to NULL on standards-conformant glibc, so !endptr is defensive but unreachable — fine.
  • errno == ERANGE is checked but errno == EINVAL isn't — glibc's strtol doesn't set EINVAL on no-conversion, the empty-string case is caught by the explicit optarg[0] == '\0' check, so no gap.
  • No format-string risk in fprintf(stderr, "error: run count must be <= %d (got %ld).\n", ...). The %ld matches long parsed_run_count. Clean.
  • Test coverage exercises -1, 0, INT_MAX, and a happy path of 2 confirming BEST/WORST RUN RESULTS are 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 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)

  • memtier_benchmark.cpp:1058-1067 clean: signed strtol, errno=0 pre-set, ERANGE-checked, endptr validated, both lower and upper bounds enforced. No off-by-one in the upper-bound message either (uses <= MAX_RUN_COUNT).
  • memtier_benchmark.cpp:1058 optarg[0] == '\0' correctly catches the empty-string case. Whitespace-only inputs are caught by *endptr != '\0' because strtol skips leading whitespace and endptr stops at the first non-converted character.
  • memtier_benchmark.cpp:1062 parsed_run_count <= 0 covers both 0 and negatives in one branch. Good.
  • memtier_benchmark.cpp:1067 (unsigned int) parsed_run_count — parsed_run_count is long (potentially 64-bit) cast to unsigned int. Cap of 1024 keeps this trivially in range; defensive but fine.
  • One minor inconsistency with phase 2b (#428) and 2c (#427): no optarg == NULL guard. getopt won't hand NULL for 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_COUNT is a #define (int literal). Adjacent caps in PR #428 are also #defines (unsigned). Cross-PR, consider a single namespace memtier::limits or at least matching widths/styles to keep the merge tidy.

Verdict: Approve (no functional concerns)

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

Verdict: LGTM; cleanest of the phase-2 batch.

  • Invocation paths: only the long-option case 'x' exists; parse_uri() does not touch run_count, no config-file feature. All paths covered.
  • Cap boundary: parsed_run_count > MAX_RUN_COUNT correctly 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 tests 2. A regression to >= would slip past CI; one cap-value-accepted assertion would close that.
  • errno = 0 before strtol and errno == ERANGE check 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 <= 0 correctly catches 0 and any negative value strtol produces. --run-count=-9223372036854775808 (LONG_MIN) → ERANGE on some libcs, otherwise returns LONG_MIN, both rejected. Good.
  • (unsigned int) parsed_run_count cast 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 with 1 (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 uses optarg[0] after the strtol call which already deref'd optarg — order is fine because strtol(NULL) is UB and optarg is guaranteed non-NULL by getopt for required-arg options.

@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: 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 — because strtol("-1") succeeds and the parse branch reaches the <= 0 check. 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_count zero-check unchanged) is the load-bearing insight; make it explicit.

  • MAX_RUN_COUNT #define at global scope is consistent with project convention — well-placed near line 90 with the other globals. Good.

  • Python test: test_run_count_valid_runs_normally uses env.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.

@fcostaoliveira
fcostaoliveira merged commit 7680708 into redis:master Jun 1, 2026
85 of 86 checks passed
fcostaoliveira added a commit that referenced this pull request Jun 2, 2026
…/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]>
fcostaoliveira added a commit that referenced this pull request Jun 2, 2026
…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]>
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.

1 participant