Skip to content

Fix TSan data race in GetPriorityForLoadBalancing::getPriorityFunc - #104072

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-tsan-race-getpriority-loadbalancing
May 19, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-tsan-race-getpriority-loadbalancing

Conversation

@groeneai

@groeneai groeneai commented May 5, 2026 •

Copy link
Copy Markdown
Collaborator

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).

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, 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_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 because:

  • ZooKeeperArgs holds GetPriorityForLoadBalancing by value and is
    passed by value to ZooKeeper::init / ZooKeeper::create, and
    reassigns the member from a temporary in
    ZooKeeperArgs::initFromKeeperServerSection /
    initFromKeeperSection.
  • ReadFromRemote::priority_func_factory is a
    std::optional<GetPriorityForLoadBalancing> reassigned in-place.

A new gtest GetPriorityForLoadBalancing.RoundRobinIsThreadSafe
deterministically catches the bug independently of TSan: 8 threads
each call getPriorityFunc 10000 times on the same instance; after
the parallel block, the next call's observed rotation head must equal
total_parallel_calls % pool_size. With the fix it passes 20/20
iterations; 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):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed a data race in GetPriorityForLoadBalancing::getPriorityFunc that could shift the round-robin counter when distributed queries (e.g. parallel replicas or distributed inserts) dispatch concurrently against the same ConnectionPoolWithFailover. 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

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.5.1.795

`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
@groeneai

groeneai commented May 5, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR Validation Gate (self-review)

Session: cron:clickhouse-ci-task-worker:20260505-041500

a) Deterministic repro? Yes. The new gtest GetPriorityForLoadBalancing.RoundRobinIsThreadSafe deterministically reproduces the bug on a Debug build within a few iterations of --gtest_repeat. After 8 threads × 10000 concurrent calls, the post-block rotation head is asserted equal to total_parallel_calls % pool_size; lost increments shift the head and the assertion fails.

b) Root cause explained? Yes. getPriorityFunc is const but does ++last_used on a mutable size_t. The class is held by value as ConnectionPoolWithFailover::get_priority_load_balancing — one instance per pool, shared across all distributed-query worker threads. Concurrent distributed dispatches (parallel replicas, distributed inserts, BuzzHouse fuzz workloads) all hit ++last_used at the same time without synchronization. TSan reports the race as STID 4676-580d / 4676-58a7; correctness-wise, lost increments break the round-robin invariant.

c) Fix matches root cause? Yes. last_used becomes std::atomic<size_t> and ++last_used becomes fetch_add(1, std::memory_order_relaxed). Relaxed ordering is sufficient — the counter is only used to derive a rotation index, no happens-before relation is needed with other memory. This targets the missing synchronization, not the symptom.

d) Test intent preserved? / New tests added? Yes. New gtest file gtest_get_priority_for_load_balancing.cpp with three tests: (1) the threading regression test above, (2) RoundRobinRotates verifying single-threaded rotation semantics are unchanged, (3) CopyAndMovePropagateCounter exercising the new copy/move ctors and assignment operators.

e) Demonstrated in both directions? Yes. With last_used reverted to plain size_t + ++last_used, the test fails reliably within a few --gtest_repeat iterations (observed head 5 vs expected 4 in one run). With the fix, 20/20 --gtest_repeat iterations pass. All 18 existing ConnectionPoolTest gtests still pass. The main clickhouse binary builds cleanly.

f) Fix is general, not a narrow patch? Yes. The atomic protects ALL invocations of getPriorityFunc regardless of the call path (DistributedSink, RemoteQueryExecutor, parallel replicas, ZooKeeper round-robin). I checked: last_used is the only mutable counter racing in this class. The new copy/move semantics propagate the counter with relaxed ordering, preserving prior copy behavior and keeping the class compatible with ZooKeeperArgs (passed by value to ZooKeeper::init/create) and ReadFromRemote::priority_func_factory (std::optional<GetPriorityForLoadBalancing>).

@groeneai

groeneai commented May 5, 2026

Copy link
Copy Markdown
Collaborator Author

cc @azat @devcrafter — could you review this? It fixes the TSan data race on mutable size_t last_used in GetPriorityForLoadBalancing::getPriorityFunc (const method mutating shared state across concurrent distributed dispatches), as analysed by @PedroTadim in #102021. Atomic + relaxed fetch_add, with explicit copy/move ctors required because the class is held by value in ConnectionPoolWithFailover and ZooKeeperArgs. Includes a deterministic gtest.

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label May 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bd1b7f1]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) FAIL
02180_group_by_lowcardinality FAIL cidb

AI Review

Summary

This PR fixes a real data race in GetPriorityForLoadBalancing::getPriorityFunc by making last_used atomic and switching round-robin increments to fetch_add with relaxed ordering. The added copy/move operations correctly preserve the counter value after introducing std::atomic, and the new gtests cover the concurrent regression plus copy/move behavior. I did not find unresolved correctness, concurrency, or compatibility issues in the current diff.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 5, 2026
`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
@groeneai

groeneai commented May 5, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed c7fd892f2f94 to fix the Build (arm_tidy) failure.

clang-tidy-21 raised performance-unnecessary-copy-initialization on the new test:

src/Common/tests/gtest_get_priority_for_load_balancing.cpp:120:33: error: local copy 'copy' of the variable 'src' is never modified

The check is right that copy is never written through any non-const member — but the whole point of the test is to verify that the copy constructor propagates the rotation counter. The only use of copy after construction is copy.getPriorityFunc(...), which is a const method that mutates the new mutable std::atomic<size_t> counter; clang-tidy cannot see that side effect. Replacing the copy with a const & would defeat the test.

Fix: single-site // NOLINT(performance-unnecessary-copy-initialization) mirroring the existing pattern in src/Coordination/tests/gtest_compact_children_set.cpp:202 (which suppresses the same check on the same kind of copy-ctor smoke test).

Diff:

-    GetPriorityForLoadBalancing copy(src);
+    GetPriorityForLoadBalancing copy(src); // NOLINT(performance-unnecessary-copy-initialization) - intentionally testing copy constructor

Awaiting Build (arm_tidy) re-run.

cc @azat @devcrafter — heads-up only, no action required.

Session: cron:clickhouse-ci-task-worker:20260505-201500

@groeneai

groeneai commented May 18, 2026 •

Copy link
Copy Markdown
Collaborator Author

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 4676-52d8 is chronic master since 2026-05-06 (pull_request_number = 0, 5 distinct check configs), all pointing at GetPriorityForLoadBalancing.cpp:39 — exactly what this PR addresses.

cc @alexey-milovidov @azat @devcrafter — could one of you take a look so we can land it?

The fix is minimal:

  • mutable std::atomic<size_t> last_used + fetch_add(memory_order_relaxed)
  • Rule-of-five ctors because GetPriorityForLoadBalancing is held by value in ZooKeeperArgs and ReadFromRemote
  • New gtest_get_priority_for_load_balancing.cpp provides a deterministic regression test (fails without the fix, 20/20 passes with it)

Session: cron:clickhouse-ci-task-worker:20260518-013000

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The fix is perfect, thank you!

@clickhouse-gh

clickhouse-gh Bot commented May 18, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.20% 84.20% +0.00%
Functions 91.40% 91.40% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 98.88% (88/89) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov merged commit 46ed63b into ClickHouse:master May 19, 2026
163 of 167 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label May 19, 2026
alexey-milovidov added a commit to vvo/ClickHouse that referenced this pull request May 19, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ThreadSanitizer: data race (STID: 4676-580d)

5 participants