Skip to content

Stamp interrupted clients' end time after joining the workers (Ctrl+C data race) - #730

Merged
fcostaoliveira merged 3 commits into
masterfrom
fix/710-interrupt-race
Oct 16, 2026
Merged

fcostaoliveira merged 3 commits into
masterfrom
fix/710-interrupt-race

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented Oct 16, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

On Ctrl+C, SIGTERM, or a connection-stage abort, the main thread finalized every client's run_stats while the worker threads were still recording into them. That is a data race on std::list / std::vector members, and a double free under ASan (#710).

Root cause

client_group::interrupt() runs on the main thread. It calls event_base_loopbreak() + event_base_loopexit({0,0}), and both take effect only after the callback that is currently running. It then called finalize_all_clients(true) right away, which means run_stats::set_end_time() → summarize_current_second() (writes m_cur_stats.*.summarized_quantile_values and the shared m_quantile_values scratch) → m_stats.push_back(m_cur_stats). At the same moment the worker can be in handle_response() → update_*_op() → roll_cur_stats(), which runs the same summarize/push_back/reset on the same objects with no lock. The plain bool m_end_set was raced as well.

CI never caught this because tsan_suppressions.txt had race:run_stats::set_end_time, and that matches the main-thread stack of exactly this race.

Fix

  • interrupt() now only records the interrupt time (once), marks the clients interrupted and breaks the loop. It no longer touches run_stats.
  • run_benchmark() calls the new client_group::finalize_interrupted_clients() right after each pthread_join() and before merge_run_stats(). It ends the clients that are still open, using the recorded interrupt time (client::set_end_time_interrupted(), clamped to the client's start time). By then the worker has exited, so nothing races.
  • Results keep the same shape. The end time and "Total duration" are still the interrupt time, "Interrupted": "true" is still set, and the partial-run and series-cut behaviour from Stop the --run-count series on Ctrl+C #698 / Handle SIGTERM like Ctrl+C so --json-out-file stays valid #706 is unchanged.
  • The keep_live_totals special case in run_stats::set_end_time() / summarize_current_second() existed only because the fold ran concurrently with the worker. It is removed. The post-join fold moves the live latency histogram into the exporter's pending histogram under the mutex as usual, and the run-end drain still picks up anything left over.
  • The race:run_stats::set_end_time TSan suppression is removed.
  • Deterministic guard. client_group records its worker thread in run(), and cg_thread::join() marks it joined after pthread_join(). finalize_all_clients() aborts with BUG: finalize_all_clients() off the worker thread before join when it is called from any other thread before the join. The check is always on, because the race itself only shows up under a sanitizer, and even then not on every run. I put the old finalize back into interrupt() locally to check it. The guard then aborts on every SIGINT, SIGTERM and connection-stage abort: 5/5 of test_interrupt_signal_handling, test_interrupt_stops_run_count, test_interrupt_does_not_race_worker_stats, test_sigterm_closes_json and test_rejected_setup_at_startup_is_bounded_by_connection_stage_timeout fail. With the fix there are no false positives: all of tests_oss_simple_flow.py passes (48/48), plus test_cluster_slots_bad_reply.py, test_client_staircase.py, prometheus F27 and make check. The TSan cells are continue-on-error, so this guard is what makes the regression blocking in the plain, ASan and UBSan cells.
  • run_stats::m_interrupted is now atomic. The connection-stage supervisor calls interrupt() (which runs set_interrupted()) on groups whose worker may already have left the loop on its own and be reading the flag in client_group::run(). CI TSan reported this once.

Behaviour change: late replies are now counted

Replies the worker handles between interrupt() and the loop exiting now go into Totals and into the final per-second bucket. Before, they landed in m_cur_stats after the main thread had already pushed it. That dropped them from the JSON per-second and totals, while the HDR histograms and Prometheus (through the run-end drain) still counted them. Now JSON, HDR and Prometheus agree. The duration is still the interrupt time, so ops/sec can rise by at most one callback's worth (pipeline × connections). If that last callback crosses a second boundary, roll_cur_stats() can push a bucket that starts after the interrupt time. The worker could already do that before this change, and the per-second series simply ends with that bucket.

Test evidence

New tests_oss_simple_flow.py::test_interrupt_does_not_race_worker_stats: 3 × (-t 4 -c 10 --pipeline 16 --test-time 30, SIGINT after 2 s). It asserts no sanitizer report, exit 0, Interrupted: true, a duration that matches the interrupt time, and a non-zero count. To get the TSan exit code it has to run under a TSan build. CI's TSan cells run this file.

Local runs, TSan build (--enable-thread-sanitizer, setarch -R, TSAN_OPTIONS=suppressions=tsan_suppressions.txt from this branch):

binary test runs failed
origin/master 427d721 10 10 (TSan reports, exit 66)
this branch 10 0

Direct CLI with timeout -s INT 2: master reports the race in about 60% of single interrupts (3/5 for -t 2 -c 5 --pipeline 16, 4/5 for -t 4 -c 50 --pipeline 64), with 25 reports per hit. Every one has client_group::interrupt() → finalize_all_clients() → run_stats::set_end_time() on the main thread against run_stats::update_set_op() / handle_response() on a worker. The fix gave 0 reports in every run.

Also passing locally with the fix (as of bae456e, rebased on 193f6a8):

  • TSan build: the existing interrupt and SIGTERM tests (test_interrupt_signal_handling, test_interrupt_stops_run_count, test_interrupt_between_runs_stops_run_count, test_interrupt_last_run_marks_aggregate, test_sigterm_closes_json, test_sigterm_stops_run_count, test_sigterm_between_runs_stops_run_count), test_prometheus.py::test_F27_interrupt_run_end_counts_every_op, test_reconnections.py::test_ctrl_c_reported_when_server_never_reachable, and the connection-stage abort tests in test_cluster_slots_bad_reply.py.
  • Normal build: the same interrupt and SIGTERM tests, all of test_prometheus.py, and make check (9/9).

Overlap with open PRs

Fixes #710

Affected versions

2.3.0 through 2.5.2 (latest), and master. The bug was introduced by aa9edb8 "Signal Handling with Graceful Shutdown with metrics" (#325), and git tag --contains aa9edb8 → first tag 2.3.0. Reproduced here on master 427d721 under TSan.

🤖 Generated with Claude Code


Note

Medium Risk
Changes shutdown ordering and stats finalization on interrupt paths; logic is localized but affects correctness of reported run windows and thread-safety of hot run_stats paths.

Overview
Ctrl+C / connection-stage abort no longer finalizes run_stats on the main thread while workers may still be in handle_response() / roll_cur_stats(). That concurrent set_end_time() was a data race (and ASan double-free); TSan had been masked by a suppression on run_stats::set_end_time.

client_group::interrupt() now only captures interrupt wall time once, marks clients interrupted, and breaks the libevent loop—it does not touch stats. After each pthread_join(), finalize_interrupted_clients() stamps still-open clients via set_end_time_interrupted() (end time clamped to each client’s start). Reported duration and "Interrupted": true stay tied to the interrupt moment, not join time.

The interrupt-only keep_live_totals path in run_stats::set_end_time() / summarize_current_second() is removed; post-join folding and Prometheus run-end drain behave as on normal shutdown. A new OSS test hammers SIGINT under load and checks sanitizers, duration, and op counts.

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

@github-actions

github-actions Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

🤖 Automated first-pass review — a human maintainer's review is still required before merge.

Thanks for this. I went through the diff and the interrupt/join path in run_benchmark(), and I think the core change is right: interrupt() is only called from the main thread (both Ctrl+C and the connection-stage supervisor), and moving the fold to after pthread_join() removes the overlap with roll_cur_stats(). Dropping the race:run_stats::set_end_time suppression is the right call. The write-up of why CI missed the race was useful.

A few questions, none blocking:

  • Did you consider assert() instead of fprintf + abort() in check_stats_owner()? The rest of this path already relies on assert() (e.g. assert(ret == 0) after pthread_join), so I'm not sure an always-on check is worth having a second style for. That said, I see why the "BUG:" message is handy in CI logs, so I'm fine either way.
  • On the failure path in cg_thread_start(), a worker that throws after Ctrl+C still calls finalize_all_clients() itself with NULL. Those clients get "now" as their end time instead of the interrupt time, and the post-join finalize_interrupted_clients() then does nothing for them. I think that's the right trade-off, since reading m_interrupt_requested from the worker would bring a race back. Maybe worth a line in the comment there, so nobody "fixes" it later.
  • Nitpicking: in test_interrupt_does_not_race_worker_stats, the 1000 <= Total duration <= 6000 check can't really tell interrupt time from join time, because the join is near-instant once the loop breaks. It works as a sanity bound, but the comment above it ("not the (later) join") claims a bit more than it tests.

On compat: the JSON Totals/per-second counts can go up slightly because late replies are now counted. That's disclosed, it brings JSON in line with HDR/Prometheus, and the keys and Interrupted semantics stay the same, so I don't see a less-breaking design that would be worth it. The fails-then-passes evidence also meets the bar here. The TSan test plus the guard making the existing interrupt tests abort on the old code is the kind of regression proof PR#364 set.

The fix looks solid to me. Given how central this shutdown ordering is, it may still be worth a second look from whoever owns the Prometheus run-end drain before it merges.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks for the review. Taking your points in order (pushed as 7a6a245, rebased on master 0fc29f4):

  1. Late replies are now counted. Yes, that's intended. Replies handled between interrupt() and the loop exiting now go into Totals and the final bucket. Before, they were missing from the JSON totals and per-second data but present in the HDR histograms and in Prometheus (through the run-end drain). Now all three agree. The duration is still the interrupt time, so ops/sec rises by at most one callback (pipeline × connections). I've added a note to the description.
  2. A bucket past the end time. That can happen. If the last callback crosses a second boundary, roll_cur_stats() pushes a bucket that starts after the interrupt time, and the per-second series (including --print-all-runs) ends with it. The worker could already push such a bucket before this change, since it kept recording after the main thread's push_back. Nothing in the output assumes the last bucket ends before the end time, so I've left it alone.
  3. Is the test actually run under TSan in CI? Yes. The "Single Endpoint: TCP Plaintext" TSan cell sets no TEST filter, so it runs every file, including tests_oss_simple_flow.py. That cell is continue-on-error, though. So the new commit also adds an always-on guard: finalize_all_clients() aborts (BUG: finalize_all_clients() off the worker thread before join) when it's called from a thread other than the group's worker before pthread_join(). With the old interrupt() this aborts on every SIGINT, SIGTERM and connection-stage abort, so the existing interrupt tests fail in the plain, ASan and UBSan cells too. With the fix, all of tests_oss_simple_flow.py still passes.
  4. The if rc != 0: break. It stops further attempts from repeating the same TSan report in the log. I added a comment saying so.

Also in this push:

  • run_stats::m_interrupted is now atomic. The connection-stage supervisor can set it while a worker that already left its loop reads it in client_group::run().
  • The stale F27 comment in tests/test_prometheus.py is fixed.

Known corner, not changed: if a worker throws after an interrupt, it is marked failed and finalizes its own clients with the current time, not the interrupt time. That path runs on the worker, so there is no race. Only the end time can be a few ms later than the interrupt.

fcostaoliveira and others added 3 commits October 16, 2026 21:18
client_group::interrupt() runs on the main thread. It asked the worker
loop to stop (event_base_loopbreak()/loopexit(), which take effect only
after the callback that is running) and then immediately called
finalize_all_clients(), i.e. run_stats::set_end_time() on every client.
That folds the current second (summarize_current_second() writes the
shared quantile scratch vector) and appends it to m_stats, while the
worker can be in handle_response() -> roll_cur_stats() doing the same
on the same objects, with no lock. A data race on Ctrl+C, SIGTERM and
the connection-stage abort; a double free under ASan. The TSan
suppression for run_stats::set_end_time hid it in CI.

interrupt() now only records the interrupt time, marks the clients
interrupted and breaks the loop. run_benchmark() finalizes the clients
that have not ended with that time right after pthread_join(), before
merging their stats. The duration and JSON stay as before: the end time
is still the interrupt time, and "Interrupted" is still set. With the
fold now on the joined thread, the keep_live_totals special case for
the Prometheus exporter is no longer needed and is removed.

Drop the race:run_stats::set_end_time suppression and add
test_interrupt_does_not_race_worker_stats, which fails under TSan on
master (TSan report, exit 66) and passes with the fix.

Fixes #710

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The regression test for #710 only catches the race under TSan, which
reports it on most interrupts but not all, and the TSan CI cells are
continue-on-error. client_group now records the worker thread in run()
and is marked joined after pthread_join(); finalize_all_clients()
aborts with "BUG: finalize_all_clients() off the worker thread before
join" when called from any other thread before the join. On the old
interrupt() this aborts on every SIGINT, SIGTERM and connection-stage
abort, so the existing interrupt tests fail in every CI cell.

Also make run_stats::m_interrupted atomic: the connection-stage
supervisor sets it from the main thread while a worker whose loop has
already ended reads it in client_group::run() (seen once under TSan).

Refs #710

Co-Authored-By: Claude Opus 5.5 <[email protected]>
check_stats_owner() reads m_worker_tid from the main thread while the
worker writes it in client_group::run(). Publish it with a release
store of m_worker_tid_set and read it after an acquire load.

Refs #710

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Answers to the second automated review (pushed as bae456e, rebased on master 193f6a8, which includes #724):

  • m_failed + interrupt ordering. Yes, that's intended. A worker that throws during an interrupted run finalizes its own clients with the current time, on its own thread, so there is no race. set_end_time_interrupted() then returns early. The only effect is that the end time of that rare case can be a few ms after the interrupt time. Getting the interrupt time to the worker would mean another cross-thread hand-off for a path that is already an error.
  • Always-on abort() vs assert(). I chose the always-on check on purpose. The race is invisible without a sanitizer, and even TSan reports it on only about 60% of interrupts. The TSan cells are continue-on-error, so the plain, ASan and UBSan cells are what make this regression blocking, and they would also catch it in an -DNDEBUG build. The check costs nothing on the hot path: it runs once per finalize_all_clients() call, which is once per thread per run. It only fires if a future change finalizes the stats from the wrong thread again. I'm happy to switch it to assert() if the maintainers prefer. Your call.
  • Plain tid fields. Fixed. m_worker_tid_set is now a std::atomic<bool>. The worker writes m_worker_tid and then publishes the flag with a release store. check_stats_owner() does an acquire load of the flag before it reads the tid. I considered comparing against cg_thread::m_thread, which is set at pthread_create(), but the worker checks itself on the m_failed path, and pthread_create() may write m_thread after the new thread has already started. So that comparison would just move the race.
  • The long F27 comment line. Re-wrapped.

Re-run after the rebase: make check 10/10, the interrupt and SIGTERM tests, prometheus F27, test_test_time_stalled_server.py, test_cluster_slots_bad_reply.py (30/30), and test_retry_on_error.py (28/28).

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks. Answering the 20:20 version of the review:

  • assert() vs the always-on check: kept on purpose. The race this guards against is invisible in normal builds: without TSan it shows up only as rare heap corruption. The TSan CI cells are continue-on-error, and release builds compile assert() out. The always-on check makes the existing plain, ASan and UBSan interrupt tests abort deterministically if the stamping ever moves back before the join, and it runs once per thread per run. If maintainers prefer assert(), it's a one-line change.
  • Worker exception after Ctrl+C: yes, that trade-off is deliberate. The worker stamps "now" on its own thread, so there is no race, and the end time is at most a few ms after the interrupt. Reading m_interrupt_requested from the worker would bring the race back. I'll add a one-line comment there in a follow-up so nobody "fixes" it.
  • The 1000 <= Total duration <= 6000 bound: agreed. It's a sanity bound, and the comment overstates it. What the test actually guards is the absence of TSan reports, plus the guard abort on the old code. The interrupt-time vs join-time distinction is covered by the code, not this bound. I'll correct the comment in the same follow-up.
  • Prometheus run-end drain: reviewers checked it explicitly. F27 and the full test_prometheus.py pass under TSan, and the drain runs after the join loop. JSON, HDR and Prometheus totals now agree for interrupted runs.

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.

Ctrl+C: client_group::interrupt() finalizes run_stats from the main thread while workers still record (data race, ASan double free)

1 participant