Skip to content

Stop silently re-running worker threads after connection errors - #546

Merged
fcostaoliveira merged 7 commits into
redis:masterfrom
Daniel-Issen:fix/no-silent-thread-restart
Oct 1, 2026
Merged

fcostaoliveira merged 7 commits into
redis:masterfrom
Daniel-Issen:fix/no-silent-thread-restart

Conversation

@Daniel-Issen

@Daniel-Issen Daniel-Issen commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Base: redis/memtier_benchmark master at abdbb3564a79439c74d18411130b3d0835d2ecd2 ("Fix ownership of URI credentials and hostnames (#544)").

Problem

When a worker thread's event loop returns and its client_group has recorded any connection error, cg_thread_start() sets m_restart_requested. The next pass of the monitor loop in run_benchmark() then joins the thread, deletes its client_group and calls cg_thread::restart(). That builds a new client_group with new clients, new run_stats and a new --test-time (or --requests) budget, and starts a new thread. This can happen up to 5 times per thread. Nothing in the final report says it happened.

What that does to a run:

  1. A --test-time run takes longer than requested, and the report hides it. Each restart adds the time the thread had already run. The report still prints 10 Seconds and the process exits 0. memtier's own CPU summary (Wall time: 12.999s) contradicts the header.
  2. With --reconnect-on-error, a window that recovered fully is thrown away and run again. The reconnect works and the window runs to --test-time. But the recovered errors still count as connection errors, so the thread is restarted anyway. The completed window, including the outage the user wanted to measure, is discarded, and a second, clean window is reported in its place. Wall time doubles.
  3. Results are dropped, and threads' windows stop lining up. Ops recorded before a restart are destroyed with the old client_group. When only some threads restart, their windows no longer overlap the other threads'. The merged result still adds per-thread rates as if they ran concurrently, although the restarted thread finishes alone against a server nobody else is loading.
  4. Against a dead server it retries without bound. restart() returns before m_restart_count++ when prepare() fails, so the 5-restart cap never takes effect. tests/differential_redis_benchmark.py records this as a known divergence ("keeps retrying connections indefinitely", follow-up for Add differential tests memtier vs hiredis/redis-cli/redis-benchmark #414).

The trigger is independent of protocol and server. Any server that drops a connection mid-run can cause it, for example a restart, CLIENT KILL, an idle timeout, a proxy failover or overload. In our own use, a server that reset connections under saturation made memtier report about 2x its real throughput for that server. The other server in the same comparison did not reset connections, so its numbers were not inflated.

Reproduction (stock memtier + stock memcached, loopback)

memcached -p 21911 -U 0 -m 64 -t 2 &
./memtier_benchmark -P memcache_text -s 127.0.0.1 -p 21911 --threads=2 --clients=4 \
    --ratio=1:4 --key-maximum=100000 --data-size=128 --hide-histogram --test-time=10 &
sleep 3; kill -9 %1; memcached -p 21911 -U 0 -m 64 -t 2 &   # restart the server at once
wait %2; echo "exit=$?"

On master this takes 13 s and exits 0. stderr shows Thread N finished due to connection failures, requesting restart and Restarting thread N, and the progress counter drops back to 0%. The report says 10 Seconds. Add --reconnect-on-error and it takes 20 s.

Fix

Remove the worker restart. A completed client stamps its end time when it reaches its stop condition. If the event loop returns with connected clients still unfinished, the requested workload did not complete. Recovered connection errors alone do not invalidate a completed window.

  • Count unfinished active clients, excluding clients a staircase ramp never activated. Intentional Ctrl+C and connection-stage supervisor shutdown retain their existing handling.
  • Report client(s) stopped before reaching their stop condition, fail the worker, and finalize its retained clients. The diagnostic does not assume the cause was a connection error: an event loop that runs out of work can also leave clients unfinished.
  • Use the same finalization path for caught standard and unknown exceptions, preserving actual end timestamps and the last partial statistics bucket. If finalization itself throws, terminate immediately with exit 1 without merging unfinalized statistics or running process-wide cleanup while sibling workers are active.
  • After joining, report that the run's results are invalid and return 1. Failure stays latched across --run-count. Supervisor and parse failures retain exit 2.

--reconnect-on-error remains the explicit recovery mechanism. It keeps the same clients, statistics and deadlines. A recovered run completes its original window and exits 0; it is no longer discarded and repeated. Failed-run output is retained for diagnosis, with stderr and exit status indicating invalid results; this PR does not change the output schema. Returning exit 0 after incomplete work is itself the bug, so the failure status is not gated behind another flag. With --run-count, best/worst/average output retains failed-run samples too; discard the invocation's benchmark aggregates whenever its exit status is nonzero.

Cluster MGET completion prerequisite

The new completion check exposed an existing replica-MGET defect: master could finish only 6 of 100 requested operations with no connection errors and still return success. A primary sent MGET to a replica, then parked with no local response to wake it. Replica responses did not resume that producer.

Routed MGET now records its waiting producer and schedules it when a destination response frees capacity. Successful sends also wake destination I/O, including the final request. Wakeups are deferred and coalesced through the existing mechanism, preserve pipeline and destination rate-token limits, and clear routing associations on disconnect/topology rebuild. Waiter vectors retain capacity across responses. When destination rate tokens run out, production waits for that destination's existing refill timer before retrying. This fixes the incomplete workload without weakening the new failure check or adding a polling loop.

Behaviour changes users will notice

  • Without --reconnect-on-error, a connection lost mid-run now ends that thread and the run exits 1 (previously the run was silently re-run, and exited 0). tests/test_reconnections.py::test_reconnect_disabled_by_default already described this as the intended behaviour; it could not assert it before.
  • A run against an unreachable server now fails fast with exit 1. Previously it restarted until --connection-stage-timeout (exit 2) or --test-time ran out (exit 0).
  • The Maximum reconnection attempts (%u) exceeded ... messages now say ending this thread instead of triggering thread restart. The Maximum reconnection attempts (N) exceeded prefix that test_reconnect_unlimited_no_spurious_thread_restart matches is unchanged.

Tests in this PR

  • Mid-run connection kills verify active clients and a positive kill count. Without recovery, assert exact exit 1, retained JSON output, and bounded termination. With recovery, assert exit 0, the full original duration, no restart, and JSON operation counts matching Redis's GET/SET counters within in-flight response tolerance. Child processes are reaped even on fixture errors.
  • Test-only exception injection exercises both worker catch blocks and asserts positive actual duration, consistent command/total counts, and retained per-second buckets. Both regressions fail on the original PR head and pass with the fix. An additional allocation-failure regression verifies that fatal finalization does not run process-wide cleanup; its injector forwards to the real allocator, including sanitizer allocators. Linux dynamic builds run these tests; unsupported interposition environments skip them.
  • Replica-MGET and RESP3 tests assert complete operation totals, full timed windows and zero connection errors, rather than accepting a single batch as success. A routed-MGET rate regression bounds the JSON operation count by destination capacity; it fails before the rate fix (196,248 operations above a 681-operation bound) and passes after it (596 operations).
  • CLI supervisor tests now configure TLS correctly and distinguish live setup stalls (exit 2 plus supervisor diagnostics) from an oversized-bulk disconnect (exit 1 plus worker diagnostics).
  • Soak and Prometheus churn tests explicitly request recovery; Prometheus retains positive-error and monotonicity assertions and checks clean exit. The differential server-kill test requires exact exit 1.

Validation of the current changes

  • Optimized build, formatting checks, and all three unit tests pass.
  • Reconnection, JSON-integrity and CPU suites: 19 executed passes, one cluster-only skip, no failures.
  • Twenty focused test-function executions pass across authenticated TCP/TLS fixtures: the two new reconnection cases, seven CLI cases and Prometheus churn per transport.
  • Twenty-seven cluster probes pass across pipelines 1/4/32, RESP2/RESP3, request/time windows, pure and mixed MGET, read preferences and completion controls.
  • All four affected cluster test bodies pass on optimized and ASAN/UBSan builds. Exception and reconnection regressions also pass over TLS under ASAN/LSAN/UBSan; no sanitizer findings.
  • The differential server-kill test passes with an authenticated local fixture.
  • The original two reconnection regressions were executed against exact master and the original PR head: they fail master and pass the PR. Both new exception regressions fail the original PR head and pass the follow-up.

Follow-up validation also passes all five cluster test bodies on optimized and ASAN/LSAN/UBSan builds, three exception/fatal tests natively and over TLS with ASAN/UBSan, and three standalone rate-limit regressions. The new fatal test passed under local TSan; two ordinary tests could not start reliably because the host reported unexpected memory mapping, the complete GitHub TSan matrix has since passed on the final head.

The oversized-bulk CLI regression now uses 100 requests at pipeline 1 with SET-only traffic, so slow serialization cannot satisfy a one-second stop condition before the disconnect. Its exact exit-1 and invalid-results assertions remain unchanged. A controlled two-second serialization delay makes the former test fail (exit 0) and the updated test pass (exit 1); native TLS, ASAN plaintext and delayed ASAN TLS controls also pass.

Routed MGET producers also wake after a destination disconnects, once its disconnected state and teardown are complete. This lets a producer use a live alternate during reconnect backoff. The new regression confirms replica traffic, kills those connections, requires primary progress within three seconds while reconnect backoff is thirty seconds, then checks the full six-second JSON window and exit 0. It fails before the fix and passes afterward. All six cluster test bodies pass optimized and with ASAN/LSAN/UBSan; unit and formatting checks pass.

Final validation at 7a48de84a08a86c84c5ea4aaacde4fd1476096f8: 113 successful checks, six intentional skips, no failed or pending checks, including successful ASAN/LSAN, UBSan, TSan and Bugbot checks. Four iterations of nine adversarial reviewers converged with no remaining blocker. Human maintainer approval is still required. The existing RLTest replica-discovery/helper limitation can skip replica-dependent CI cases; the new disconnect regression was separately executed on owned authenticated clusters, including three TLS ASAN/LSAN/UBSan repetitions of its actual body.

A matched-build, CPU-pinned non-MGET cluster spot check completed 40 valid runs against a constant Redis configuration. Initial median deltas ranged from -1.52% to +2.84% amid larger run variation; longer GET/pipeline-64 confirmation measured -0.0056% versus master, with mixed pair directions. No reproducible slowdown beyond noise was established; strict parity and smaller costs remain unproven. Review history and CI snapshot preserve the evidence and limits; performance report and samples include provenance, spreads and completion checks.

Measurements

Linux 7.0 VM (arm64, 15 vCPU), memcached 1.6.38, loopback, --threads=2 --clients=4 unless noted. The host was shared with other work, so ops/sec depends on outside load and is not compared between builds. Every claim below is about wall time, exit status and restart counts. Raw output is in measurements.txt.

scenario (--test-time=10) build wall (s) exit restarts report header
memcached killed + restarted at 3 s master 13.0-13.1 (5/5) 0 2 10 Seconds
same patched 3.0-4.0 (5/5) 1 0 10 Seconds + error line
same, --reconnect-on-error master 20.0-20.1 (5/5) 0 2 10 Seconds
same, --reconnect-on-error patched 10.0-10.1 (5/5) 0 0 10 Seconds
1 of 4 connections reset at 5 s (--threads=4 --clients=1) master 15.0-15.1 (3/3) 0 1 -
same patched 10.0-10.1 (3/3) 1 0 error line
edge case master patched
closed port, --test-time=5 exit 0 after 6.1 s, 10 restarts exit 1 after 1.0 s
SIGINT 3 s into --test-time=10 exit 0, 3.0 s exit 0, 3.0 s, no error line
clean --requests=20000 exit 0, 1.0 s exit 0, 1.0 s
clean --test-time=5 exit 0, 5.0 s exit 0, 5.0 s
clean staircase (--clients-start=1 --clients-step=1 --step-duration=2, --test-time=5) exit 0, 6.0 s exit 0, 6.0 s

The staircase run overshoots by 1 s on both builds; this PR does not change it (see "Not addressed").

Not addressed (pre-existing, separate)

  • In staircase mode, --test-time=5 --step-duration=2 runs for 6 s on both builds. The deadline is only checked when the EV_PERSIST staircase timer fires. Clients stop at their deadline; the event loop does not exit until the next timer tick.

Note

High Risk
Changes core benchmark lifecycle (exit codes, thread teardown) and cluster MGET scheduling/backpressure; incorrect incomplete-work detection or wakeup logic could fail valid runs or hang replica routing.

Overview
Removes the automatic worker-thread restart after connection errors. When a worker’s event loop exits with active clients that never reached their stop condition (count_unended_clients / end_time_set), the run is marked failed, partial stats are finalized, stderr reports invalid results, and main exits 1—unless Ctrl+C or the connection-stage supervisor already handled shutdown. --reconnect-on-error remains the supported way to survive mid-run disconnects without discarding the measurement window.

Cluster routed MGET gains producer wakeups when replica responses, rate-limit refills, or disconnects free destination capacity; deferrals also respect the destination’s pipeline cap and rate tokens (has_request_rate_budget), fixing workloads that previously stopped after one batch while still passing success.

Docs and tests are updated accordingly (no silent restart, exit 1 on server kill, soak/Prometheus churn with explicit reconnect, new MGET completion and worker-exception regressions).

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

cg_thread_start() requested a restart whenever a worker's client_group
ended with any connection error, and the monitor loop then deleted that
client_group and ran a new one: fresh clients, fresh stats and a fresh
--test-time (or --requests) budget, up to five times. Nothing in the
report says so. The consequences:

- A --test-time run takes longer than requested -- by the time spent
  before the failure, once per restart -- while the report still shows
  the requested duration and the process exits 0. Killing and
  immediately restarting memcached 3 s into a --test-time=10 run: 13 s
  wall, "10 Seconds" in the report, exit 0 (5/5 runs).

- With --reconnect-on-error the reconnect succeeds, the window runs to
  --test-time, and the worker is then re-run anyway because its
  recovered errors are still counted: the first, completed window is
  discarded and a second one is reported in its place. Same scenario:
  20 s wall for --test-time=10 (5/5 runs).

- Everything the worker recorded before the restart is destroyed with
  its client_group, and a restarted worker's window no longer overlaps
  the others', so the merged result adds up per-thread rates measured
  at different times. Resetting one of four connections 5 s into a
  --test-time=10 run: 15 s wall, exit 0, and in the final seconds one
  thread running alone against a server the others no longer load.

- Against a server that is down, restart() fails before counting the
  attempt, so the loop retries every second without bound; a closed
  port with --test-time=5 took 6 s and 10 restarts, then exited 0.

Remove the restart. A worker has one legitimate end: each connected
client reaches its stop condition and stamps its end time. A client
still without an end time when the event loop returns was cut off by a
connection it could not recover (no --reconnect-on-error, or its
attempts exhausted). In that case the worker stamps the end time --
as interrupt() does -- so the recorded duration is the time actually
spent, and marks itself failed; after the join, run_benchmark() prints
an error saying the run did not cover what was requested, and main()
exits 1. Connection errors that --reconnect-on-error recovered no
longer matter, so such a run ends at --test-time and exits 0.
Ctrl+C and the connection-stage supervisor (exit 2) are unchanged.

After the change, same scenarios: server kill without the flag ends at
3 s with exit 1; with --reconnect-on-error, 10 s and exit 0; one of
four connections reset, 10 s and exit 1; closed port, 1 s and exit 1.
Clean --test-time, --requests, staircase and Ctrl+C runs are
unchanged (exit 0, same wall time).

Tests:
- test_reconnections.py: two regression tests that kill every client
  mid-run with and without --reconnect-on-error and check the exit
  code, the absence of a restart and the wall time.
- soak/test_connection_churn.py kept its kills survivable only through
  the restart; it now passes --reconnect-on-error, the option that
  exists for that.
- differential_redis_benchmark.py: memtier now exits non-zero when the
  server is killed mid-run (the divergence noted there for redis#414), so
  assert it.
- Comment/docstring updates in two CLI validation tests.
@github-actions

github-actions Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

🤖 Automated first-pass review. A human maintainer still needs to review this before merge.

Thanks for this. The problem write-up and the wall-time/exit-code tables make a convincing case that the silent restart was hiding real measurement errors, and the reconnection regressions that fail on master and pass here are what I'd want to see. I went through most of it and have a few comments below.

  1. Scope. The cluster MGET producer wakeup (waiter vectors, handle_rate_limit_refill, handle_connection_disconnect, the destination rate-budget check) is a real change to cluster routing in its own right. The description calls it a prerequisite, but I think that argues for landing it first, not in the same PR. Would it be feasible to split it out so each half can be reviewed and bisected on its own? It's probably also worth a second look from whoever owns cluster routing.

  2. Exit code 0 → 1. I agree that exiting 0 after incomplete work is the bug. It's still a user-visible change, though, and CI wrappers that run memtier against flaky or failing-over servers will start failing. Given how this project has handled compat tradeoffs before (the output-format discussion in support ASK in cluster mode #60, strtod vs strtoull in Fix issue #211. Allow key_stddev and key_median options to be set values #212), did you consider anything that reduces the blast radius? A related question: a failed run still writes a normal-looking mb.json with no failure marker, so pipelines that only read the JSON can't tell it was invalid. Would an additive field (appended, not changing existing keys) be worth it, or is stderr plus the exit code enough?

  3. False positives in count_unended_clients(). Now that a missing end time flips the exit code, I think every legitimate completion path has to reach set_end_time(). I can see it in handle_response (via finished()), in fill_pipeline and in the rate-limit timer. Are there other ways a client can finish without it: arbitrary commands, --requests=allkeys, or clients a staircase ramp activated late? Also, the loop assumes the first active_client_count() entries of m_clients are exactly the prepared ones. Is that ordering guaranteed?

  4. Hot path. handle_response now calls wake_mget_producers() on every response in every cluster run, and each routed MGET send does a std::find plus an extra schedule_fill(). The early-return size check is cheap, but I wonder whether you measured non-MGET cluster throughput before and after.

  5. Teardown. shard_connection::disconnect() now calls back into the manager, so disconnect_all() at the end of a run can schedule_fill() sibling connections that are about to be torn down. schedule_fill checks conn_connected, so this is probably fine. Just checking that no deferred fill callback can fire after the client is freed.

  6. Injector test. Compiling a .so at test time with $CXX and pkg-config, then interposing operator new and event_base_dispatch via LD_PRELOAD, is a fair amount of machinery. The two exception cases seem worth keeping. For the third one (failed finalization → _Exit), I'm not sure the maintenance cost is worth it for a path that only triggers on allocation failure. What do you think?

The core change looks right to me. I'd mainly want the split question and the compat/JSON-visibility question answered before this merges.

(I'd file this as a comment, not a formal block.)

@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 using high effort and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 8516579. Configure here.

Comment thread cluster_client.cpp Resolved
@fcostaoliveira
fcostaoliveira self-requested a review October 1, 2026 06:24
@fcostaoliveira
fcostaoliveira merged commit 7a6394e into redis:master Oct 1, 2026
119 checks passed
fcostaoliveira added a commit that referenced this pull request Oct 12, 2026
…onnect

When a connection drops, disconnect() deletes its in-flight requests, but
they stay counted in the client's m_reqs_generated. Nothing processes them,
so generated stays ahead of processed for good:

- With --reconnect-interval, hold_pipeline() holds once
  (processed % interval) + (generated - processed) reaches the interval,
  so after a reconnect the client stops sending.
- In cluster mode, the in-flight budget (pipeline * connections) fills up
  with requests that will never complete.
- With --requests, generated reaches the target while processed never
  does, so the client stops short.

In each case the worker's event loop runs out of events. Since #546 the
run then fails with "client(s) stopped before reaching their stop
condition"; before #546 the worker was silently re-run, which hid this.
It is what has failed the nightly soak S4 (test_connection_churn) on
master every night since 2026-10-02.

Uncount the dropped workload requests: those discarded without
--retry-on-error, and those --retry-on-error cannot replay because they
have no captured bytes. Requests later dropped from the replay queue are
not uncounted here; they may already have been counted as processed when
their error reply was queued for retry.

dec_reqs_generated() never takes generated below processed, which
hold_pipeline() subtracts unguarded. A new is_workload_request() helper
classifies request types for both the drain and push_req()'s routed-ops
tally.

Add a regression test: one client, --reconnect-interval=10
--reconnect-on-error, four CLIENT KILL waves. It fails on master and
passes with the fix. It is standalone only: cluster mode rejects
--reconnect-interval, and a separate, pre-existing end-of-run hang with
reconnects in flight would make a cluster variant flaky.

Co-Authored-By: Claude Opus 5.5 <[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.

2 participants