Repository navigation
Stop silently re-running worker threads after connection errors - #546
Conversation
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.
|
🤖 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.
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.) |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
Reviewed by Cursor Bugbot for commit 8516579. Configure here.
…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]>

Base:
redis/memtier_benchmarkmaster atabdbb3564a79439c74d18411130b3d0835d2ecd2("Fix ownership of URI credentials and hostnames (#544)").Problem
When a worker thread's event loop returns and its
client_grouphas recorded any connection error,cg_thread_start()setsm_restart_requested. The next pass of the monitor loop inrun_benchmark()then joins the thread, deletes itsclient_groupand callscg_thread::restart(). That builds a newclient_groupwith new clients, newrun_statsand 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:
--test-timerun takes longer than requested, and the report hides it. Each restart adds the time the thread had already run. The report still prints10 Secondsand the process exits 0. memtier's own CPU summary (Wall time: 12.999s) contradicts the header.--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.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.restart()returns beforem_restart_count++whenprepare()fails, so the 5-restart cap never takes effect.tests/differential_redis_benchmark.pyrecords 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)
On master this takes 13 s and exits 0. stderr shows
Thread N finished due to connection failures, requesting restartandRestarting thread N, and the progress counter drops back to0%. The report says10 Seconds. Add--reconnect-on-errorand 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.
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.--run-count. Supervisor and parse failures retain exit 2.--reconnect-on-errorremains 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
--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_defaultalready described this as the intended behaviour; it could not assert it before.--connection-stage-timeout(exit 2) or--test-timeran out (exit 0).Maximum reconnection attempts (%u) exceeded ...messages now sayending this threadinstead oftriggering thread restart. TheMaximum reconnection attempts (N) exceededprefix thattest_reconnect_unlimited_no_spurious_thread_restartmatches is unchanged.Tests in this PR
Validation of the current changes
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=4unless 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 inmeasurements.txt.--test-time=10)10 Seconds10 Seconds+ error line--reconnect-on-error10 Seconds--reconnect-on-error10 Seconds--threads=4 --clients=1)--test-time=5--test-time=10--requests=20000--test-time=5--clients-start=1 --clients-step=1 --step-duration=2,--test-time=5)The staircase run overshoots by 1 s on both builds; this PR does not change it (see "Not addressed").
Not addressed (pre-existing, separate)
--test-time=5 --step-duration=2runs for 6 s on both builds. The deadline is only checked when theEV_PERSISTstaircase 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, andmainexits 1—unless Ctrl+C or the connection-stage supervisor already handled shutdown.--reconnect-on-errorremains 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.