Repository navigation
Fix TSan data race in GetPriorityForLoadBalancing::getPriorityFunc - #104072
alexey-milovidov merged 3 commits into
Conversation
`getPriorityFunc` is a `const` member function but mutates the internal `last_used` counter for round-robin load balancing. The class is held by value as `ConnectionPoolWithFailover::get_priority_load_balancing` (one instance per pool, shared across all distributed-query worker threads), so concurrent distributed dispatches (parallel replicas, distributed inserts) all race on `++last_used`. ThreadSanitizer reports the race as STID 4676-580d / 4676-58a7. Beyond the TSan finding, lost increments break the round-robin invariant that each caller gets a distinct rotation index. Make `last_used` `std::atomic<size_t>` and replace `++last_used` with `fetch_add(1, std::memory_order_relaxed)`. Relaxed ordering is correct: the counter is only used to derive a rotation index and there is no happens-before relation that needs to propagate to other memory. Because `std::atomic` is neither copyable nor movable, add explicit copy/move constructors and assignment operators that load and store the counter with relaxed ordering. They are required for `ZooKeeperArgs` (which holds `GetPriorityForLoadBalancing` by value and is passed by value to `ZooKeeper::init` / `ZooKeeper::create`) and for `ReadFromRemote::priority_func_factory` (`std::optional<GetPriorityForLoadBalancing>`). Add a gtest that: * Provokes the race by calling `getPriorityFunc` from N threads and checks the post-block rotation head equals `total_parallel_calls % pool_size` — without the fix this fails deterministically within a few iterations because lost increments shift the head. * Verifies single-threaded rotation semantics are unchanged. * Exercises the new copy/move ctors and assignment operators. Closes ClickHouse#102021. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=660cf75fc659d9a8aac811c30e3679ffb243b635&name_0=MasterCI
|
Pre-PR Validation Gate (self-review) Session: cron:clickhouse-ci-task-worker:20260505-041500 a) Deterministic repro? Yes. The new gtest b) Root cause explained? Yes. c) Fix matches root cause? Yes. d) Test intent preserved? / New tests added? Yes. New gtest file e) Demonstrated in both directions? Yes. With f) Fix is general, not a narrow patch? Yes. The atomic protects ALL invocations of |
|
cc @azat @devcrafter — could you review this? It fixes the TSan data race on |
|
Workflow [PR], commit [bd1b7f1] Summary: ❌
AI ReviewSummaryThis PR fixes a real data race in Final VerdictStatus: ✅ Approve |
`gtest_get_priority_for_load_balancing.cpp:120` intentionally exercises the copy constructor of `GetPriorityForLoadBalancing` to verify the counter is propagated to the copy. The copy's only subsequent use is through the const method `getPriorityFunc`, which mutates the internal mutable atomic counter — a side effect clang-tidy cannot see, so the copy looks unnecessary to the `performance-unnecessary-copy-initialization` check. Suppress the lint at this single site, mirroring the existing pattern in `src/Coordination/tests/gtest_compact_children_set.cpp:202`. CI: https://github.com/ClickHouse/ClickHouse/actions/runs/25357942908/job/74447018314 PR: ClickHouse#104072
|
Pushed clang-tidy-21 raised The check is right that Fix: single-site Diff: - GetPriorityForLoadBalancing copy(src);
+ GetPriorityForLoadBalancing copy(src); // NOLINT(performance-unnecessary-copy-initialization) - intentionally testing copy constructorAwaiting cc @azat @devcrafter — heads-up only, no action required. Session: cron:clickhouse-ci-task-worker:20260505-201500 |
|
Bumping for review attention. This PR has been open and CI-clean since 2026-05-05; in the meantime the race it fixes has fired 10 more times on master plus on PR #100938's BuzzHouse run, prompting @alexey-milovidov to ask for a fix (#100938 (comment) — replied with a pointer back here). CIDB confirms STID cc @alexey-milovidov @azat @devcrafter — could one of you take a look so we can land it? The fix is minimal:
Session: cron:clickhouse-ci-task-worker:20260518-013000 |
alexey-milovidov
left a comment
There was a problem hiding this comment.
The fix is perfect, thank you!
LLVM Coverage Report
Changed lines: 98.88% (88/89) · Uncovered code |
…lickHouse#104072) * Fix TSan data race in GetPriorityForLoadBalancing::getPriorityFunc `getPriorityFunc` is a `const` member function but mutates the internal `last_used` counter for round-robin load balancing. The class is held by value as `ConnectionPoolWithFailover::get_priority_load_balancing` (one instance per pool, shared across all distributed-query worker threads), so concurrent distributed dispatches (parallel replicas, distributed inserts) all race on `++last_used`. ThreadSanitizer reports the race as STID 4676-580d / 4676-58a7. Beyond the TSan finding, lost increments break the round-robin invariant that each caller gets a distinct rotation index. Make `last_used` `std::atomic<size_t>` and replace `++last_used` with `fetch_add(1, std::memory_order_relaxed)`. Relaxed ordering is correct: the counter is only used to derive a rotation index and there is no happens-before relation that needs to propagate to other memory. Because `std::atomic` is neither copyable nor movable, add explicit copy/move constructors and assignment operators that load and store the counter with relaxed ordering. They are required for `ZooKeeperArgs` (which holds `GetPriorityForLoadBalancing` by value and is passed by value to `ZooKeeper::init` / `ZooKeeper::create`) and for `ReadFromRemote::priority_func_factory` (`std::optional<GetPriorityForLoadBalancing>`). Add a gtest that: * Provokes the race by calling `getPriorityFunc` from N threads and checks the post-block rotation head equals `total_parallel_calls % pool_size` — without the fix this fails deterministically within a few iterations because lost increments shift the head. * Verifies single-threaded rotation semantics are unchanged. * Exercises the new copy/move ctors and assignment operators. Closes ClickHouse#102021. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=660cf75fc659d9a8aac811c30e3679ffb243b635&name_0=MasterCI * Fix clang-tidy performance-unnecessary-copy-initialization on arm_tidy `gtest_get_priority_for_load_balancing.cpp:120` intentionally exercises the copy constructor of `GetPriorityForLoadBalancing` to verify the counter is propagated to the copy. The copy's only subsequent use is through the const method `getPriorityFunc`, which mutates the internal mutable atomic counter — a side effect clang-tidy cannot see, so the copy looks unnecessary to the `performance-unnecessary-copy-initialization` check. Suppress the lint at this single site, mirroring the existing pattern in `src/Coordination/tests/gtest_compact_children_set.cpp:202`. CI: https://github.com/ClickHouse/ClickHouse/actions/runs/25357942908/job/74447018314 PR: ClickHouse#104072 --------- Co-authored-by: Groene AI <[email protected]> Co-authored-by: Alexey Milovidov <[email protected]>
Fix a real data race in
GetPriorityForLoadBalancing::getPriorityFunc,reported by ThreadSanitizer as STID 4676-580d / 4676-58a7
(see #102021 — closed in error as duplicate of #101649).
getPriorityFuncis aconstmember function but mutates the internallast_usedcounter for round-robin load balancing. The class is heldby value as
ConnectionPoolWithFailover::get_priority_load_balancing(one instance per pool, shared across all distributed-query worker
threads), so concurrent distributed dispatches (parallel replicas,
distributed inserts, BuzzHouse fuzz workloads) all race on
++last_used.Beyond the TSan finding itself, lost increments break the round-robin
invariant that two concurrent callers receive distinct rotation
indices.
Make
last_usedstd::atomic<size_t>and replace++last_usedwithfetch_add(1, std::memory_order_relaxed). Relaxed ordering iscorrect: the counter is only used to derive a rotation index and
there is no happens-before relation that needs to propagate to other
memory.
Because
std::atomicis neither copyable nor movable, add explicitcopy/move constructors and assignment operators that load and store
the counter with relaxed ordering. They are required because:
ZooKeeperArgsholdsGetPriorityForLoadBalancingby value and ispassed by value to
ZooKeeper::init/ZooKeeper::create, andreassigns the member from a temporary in
ZooKeeperArgs::initFromKeeperServerSection/initFromKeeperSection.ReadFromRemote::priority_func_factoryis astd::optional<GetPriorityForLoadBalancing>reassigned in-place.A new gtest
GetPriorityForLoadBalancing.RoundRobinIsThreadSafedeterministically catches the bug independently of TSan: 8 threads
each call
getPriorityFunc10000 times on the same instance; afterthe parallel block, the next call's observed rotation head must equal
total_parallel_calls % pool_size. With the fix it passes 20/20iterations; without the fix it fails reliably within a few iterations
because lost increments shift the head.
Two additional gtests verify the single-threaded rotation semantics
are unchanged and exercise the new copy/move constructors and
assignment operators.
CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=660cf75fc659d9a8aac811c30e3679ffb243b635&name_0=MasterCI
Closes #102021
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a data race in
GetPriorityForLoadBalancing::getPriorityFuncthat could shift the round-robin counter when distributed queries (e.g. parallel replicas or distributed inserts) dispatch concurrently against the sameConnectionPoolWithFailover. ThreadSanitizer reported the race; without the fix, increments could be lost, breaking the invariant that two concurrent callers see distinct rotation indices.Documentation entry for user-facing changes
Version info
26.5.1.795