Skip to content

fix(connection-stage): bound retry loop with --connection-stage-timeout (Refs #426 phase 1) - #431

Merged
fcostaoliveira merged 3 commits into
redis:masterfrom
filipecosta90:fix/issue-426-phase1-connection-stage-timeout
Jun 1, 2026
Merged

fcostaoliveira merged 3 commits into
redis:masterfrom
filipecosta90:fix/issue-426-phase1-connection-stage-timeout

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented Jun 1, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Phase 1 of #426: add a main-thread supervisor that bounds the connection-setup retry / parse loop with a new --connection-stage-timeout=<seconds> flag (default 30s; 0 disables).

Worker threads report failures (AUTH / HELLO / SELECT / CLUSTER SLOTS / -ERR / parse-error during initial probe) and the first successful steady-state response into the supervisor. The main thread polls once per second from run_benchmark() and aborts with rc=2 + a clear diagnostic if either:

  • a failure streak has been live for >= --connection-stage-timeout, or
  • the run has been alive that long without any thread reaching steady state (covers the "WAIT never satisfied" / "first request never returns" hangs).

--test-time still bounds the steady-state run; this new bound applies only to startup.

Two small ancillary fixes the supervisor depends on:

  • evthread_use_pthreads() is now called in main() and libevent_pthreads is linked, so cross-thread event_base_loopbreak() / event_base_loopexit() actually wake an idle worker. (This also fixed a pre-existing Ctrl+C hang in the same "stuck setup" connections.)
  • client_group::interrupt() pairs loopbreak() with loopexit({0,0}) so the worker's poll wakes immediately.
  • cg_thread_start() no longer requests a thread restart after a connection-stage abort, otherwise the restart would silently re-enter the same doomed handshake and mask the abort.

Items closed in this PR

From #426: 1, 2, 3, 8, 11, 17 (all 6 items that share the "connection-stage retry loop ignores --test-time" root cause).

# Repro Before After
1 --authenticate '' against no-auth Redis hang rc=2, AUTH error in diagnostic
2 --cluster-mode against standalone Redis hang rc=2, CLUSTER SLOTS error
3 --protocol memcache_{text,binary} against Redis hang rc=2, "protocol mismatch?"
8 --data-size-range 1-9999999999 hang rc=2, server -ERR in diagnostic
11 --select-db 100 against default 16-DB Redis hang rc=2, SELECT error
17 --wait-ratio 0:1 --num-slaves 1-10 against standalone hang rc=2, "no response from server during setup"

Refs #426

Test plan

  • make -j builds clean
  • make format-check-staged clean
  • tests/test_cli_fuzz_phase1.py (7 new tests, one per item above): all pass; each asserts non-zero exit, the new diagnostic in stderr, and a --connection-stage-timeout + 5s wall budget
  • tests/test_reconnections.py: 4/4 pass (validates the cross-thread loop-wakeup change didn't regress the normal reconnect-on-error path)
  • tests/test_retry_on_error.py: 5/5 pass
  • tests/test_sigpipe_immunity.py: pass
  • Spot-check: a normal memtier_benchmark --test-time=2 still exits 0
  • --connection-stage-timeout=0 opt-out: confirmed the original hang still occurs (supervisor disabled)

Out of scope

Phases 2 (argument-range validation) and 3 (sampler safety) of #426 are separate PRs. The tests/cli_fuzz.py exclusion list is intentionally left untouched here — narrowing it after the fixes land is a planned follow-up so the fuzzer regression net expands together with the bug landings.

🤖 Generated with Claude Code


Note

Medium Risk
Changes startup/shutdown and thread-interrupt behavior across all runs; mis-tuned timeouts or steady-state detection could abort valid slow startups or mask rare edge cases, though defaults and 0 opt-out limit exposure.

Overview
Adds --connection-stage-timeout (default 30s, 0 disables) so startup cannot spin forever when AUTH/HELLO/SELECT/CLUSTER SLOTS, protocol mismatch, or the first workload response never succeeds. Workers report setup failures and the first non-error steady-state response; the main thread polls once per second and aborts with exit code 2 and a stderr diagnostic.

Shutdown reliability: links libevent_pthreads, calls evthread_use_pthreads() before creating event bases, and pairs event_base_loopbreak() with event_base_loopexit({0,0}) in client_group::interrupt() so cross-thread stop (supervisor abort, Ctrl+C) wakes idle workers instead of hanging pthread_join(). After a stage abort, thread restart on connection errors is suppressed so the process does not re-enter the same failed handshake.

Instrumentation: shard_connection forwards setup and early -ERR/parse failures to the supervisor; tests/test_cli_fuzz_phase1.py covers the #426 hang scenarios.

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

…ut (Refs redis#426 phase 1)

Phase 1 of redis#426: add a main-thread supervisor that bounds the connection-
setup retry / parse loop, with a new --connection-stage-timeout=<seconds>
flag (default 30s; 0 disables).

Worker threads report two events into the supervisor:
  - report_connection_stage_failure() on AUTH-fail / HELLO-fail /
    SELECT-fail / CLUSTER-SLOTS-fail, on a parser failure during the
    initial probe (covers memcache_text/binary against Redis), and on
    every -ERR server response received before steady state.
  - report_connection_stage_success() on the first *successful*
    (non-error) regular response — i.e. when the worker actually exits
    the conn-setup phase.

The main thread polls once per second from run_benchmark() and aborts
with rc=2 + a clear diagnostic if either (a) a failure streak has been
live for >= --connection-stage-timeout, or (b) the run has been alive
that long without ANY thread reaching steady state. (b) covers the
"WAIT never satisfied / first request never returns" hang
(--wait-ratio 0:1 --num-slaves N against a standalone).

Closes (turns "hang until SIGKILLed" into "clean exit rc=2 within
--connection-stage-timeout + 5s") items 1, 2, 3, 8, 11, 17 of redis#426:
  1.  --authenticate '' against no-auth Redis
  2.  --cluster-mode against standalone Redis
  3.  --protocol memcache_{text,binary} against Redis
  8.  --data-size-range 1-9999999999 (-ERR invalid bulk length loop)
  11. --select-db 100 against default 16-DB Redis
  17. --wait-ratio 0:1 --num-slaves 1-10 against standalone

Two ancillary fixes the supervisor depends on:
  - evthread_use_pthreads() is now called in main() and libevent_pthreads
    is linked. Without this, event_base_loopbreak() / event_base_loopexit()
    called from the main thread don't wake a worker that's idle in
    epoll_wait(), so pthread_join() hangs after a cross-thread shutdown
    request (this also fixed a pre-existing Ctrl+C hang in the same
    "stuck setup" connections).
  - client_group::interrupt() now pairs loopbreak() with loopexit({0,0})
    so the worker's poll wakes immediately.

Reconnection / restart suppression:
  - cg_thread_start() no longer requests a thread restart when
    g_connection_stage_aborted is set; otherwise the restart would
    silently re-enter the same doomed handshake and mask the abort.

Regression tests added in tests/test_cli_fuzz_phase1.py — one per redis#426
item above, asserting non-zero exit, the new diagnostic in stderr, and a
wall-budget of --connection-stage-timeout + 5s.

Refs redis#426

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@fcostaoliveira fcostaoliveira added this to the 2.4 milestone Jun 1, 2026

@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 2 potential issues.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 80866fd. Configure here.

Comment thread memtier_benchmark.cpp Resolved
Comment thread memtier_benchmark.cpp Resolved
fcostaoliveira and others added 2 commits June 1, 2026 15:16
…tive

TSAN on the OSS-TLS cells added ~3 s of overhead per fuzz case, tipping
case redis#8 (--data-size-range with -ERR reconnect loop) past the 8-s outer
budget. Detect sanitizer instrumentation via the CI-set env hooks
(ASAN_OPTIONS / TSAN_OPTIONS / UBSAN_OPTIONS) and bump:
  SUPERVISOR_TIMEOUT_SECS: 3 -> 6
  WALL_BUDGET_SECS:        8 -> 16
under sanitizers. Non-sanitizer cells keep the tighter 3+5 budget so the
suite stays fast.

Refs redis#426 phase 1.
… counter

Address two Cursor Bugbot findings on PR redis#431:

(1) Medium: g_connection_stage_aborted was never reset between runs.
    With --run-count > 1, a run-1 abort would leave the latch set,
    suppressing legitimate thread restarts in cg_thread_start() and
    forcing main() to exit code 2 even if subsequent runs succeeded.
    Reset it in connection_stage_supervisor_reset() alongside the other
    supervisor state.

(2) Low: g_conn_stage_failure_count was incremented by every worker on
    every connection-stage failure but never read. Drop the atomic
    entirely to eliminate the unnecessary contention on the hot
    error-report path. The placeholder comment about "useful in JSON
    output" had no consumer; if we add one later, it should be reasoned
    about as a new feature.

Refs redis#426 phase 1.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@fcostaoliveira
fcostaoliveira merged commit 2e8869e into redis:master Jun 1, 2026
153 of 159 checks passed
fcostaoliveira added a commit to filipecosta90/memtier_benchmark that referenced this pull request Jun 1, 2026
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.
fcostaoliveira added a commit that referenced this pull request Jun 1, 2026
…--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]>
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]>
fcostaoliveira added a commit that referenced this pull request Jun 3, 2026
)

The CLI fuzz nightly (#445) re-broadened FLAG_SPECS to include
--authenticate and similar flags whose runaway behavior the
connection-stage supervisor (#431) is supposed to bound. But the
harness left --connection-stage-timeout at its 30 s default while
the fuzz subprocess timeout is 10 s, so cases like
`--authenticate ''` against a no-auth server hit the harness
timeout before the supervisor could fire -- producing spurious
'hung (>10s)' failures.

Pass --connection-stage-timeout=3 in the canonical args so the
supervisor reliably terminates within the 10 s harness window.
extra_args is appended after, so any fuzzed value of the same flag
still wins (last-flag-wins).

Refs: master nightly cli-fuzz failure on 03ef76e.
fcostaoliveira added a commit that referenced this pull request Jun 3, 2026
…ive (#451)

* ci(cli-fuzz): set ASAN detect_leaks=0 to avoid abort-path false positive

The nightly CLI fuzz hit a sanitizer-only abort with argv shapes like
'--authenticate "" --cluster-mode' against a no-auth server: the
connection-stage supervisor (#431) fires while cluster_client is
mid-initialisation, the abort path tears down partial cluster_client
state, and LSAN flags the unreleased allocations at __cxa_finalize,
which the harness's abort_on_error=1 converts to SIGABRT.

Release builds exit cleanly; the issue is sanitizer-only and is on
the supervisor-abort path, not the CLI input. Tracked separately in
#450.

This fuzzer's primary purpose is finding crashes/hangs from CLI
shapes; steady-state leak coverage already comes from asan.yml. Turn
off detect_leaks here while keeping abort_on_error=1 so any real
ASAN catch (UAF, OOB, double-free) still fails loudly.

Refs: nightly cli-fuzz failures on 03ef76e + 1142696.

* test(cli-fuzz): narrow LSAN bypass to the known abort-path combo

R3 review feedback on the prior approach (blanket detect_leaks=0):
turning LSAN off in the only nightly that exercises diverse argv
shapes silently dropped leak coverage on the exact cluster_client
region #450 is about.

Switched approach:
- Re-enable detect_leaks=1 in cli-fuzz-nightly.yml
- Add a Hypothesis assume(False) guard in test_cli_fuzz_does_not_crash
  for the known --authenticate '' + --cluster-mode combo so the
  example is discarded and Hypothesis keeps searching.

Net: LSAN now catches leaks on every other argv shape (including
single-flag --cluster-mode runs, --authenticate against an
auth-enabled server, etc.) -- only the one combo tracked in #450 is
skipped, with a comment linking to that issue.
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