Skip to content

Fix TSan data race in uniqExact two-level parallel merge - #109389

Merged
Algunenano merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-uniqexact-two-level-merge-race
Jul 7, 2026
Merged

Algunenano merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-uniqexact-two-level-merge-race

Conversation

@groeneai

@groeneai groeneai commented Jul 4, 2026 •

Copy link
Copy Markdown
Collaborator

Linked issues

Related: #108912

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

Fix a data race (and resulting rare crash) in the parallel merge of uniqExact aggregate states with two-level sets, which could occur with GROUPING SETS, ROLLUP and CUBE.

Description

TSan finding STID 1464-31ed on Stress test (arm_tsan) / Stress test (amd_tsan), still firing after the previous fix in #108928.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109285&sha=aa124d023377a63a7e25cde902e4a2594150f256&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29

Stack (write of size 8 by one thread):

HashTableCell::HashTableCell           src/Common/HashTable/HashTable.h:165
HashTable::emplaceNonZeroImpl          src/Common/HashTable/HashTable.h:1054
TwoLevelHashSetTable::merge            src/Common/HashTable/HashSet.h:90
UniqExactSet::merge                    src/AggregateFunctions/UniqExactSet.h:233
AggregateFunctionUniq::mergeImpl       src/AggregateFunctions/AggregateFunctionUniq.h:496
Aggregator::mergeBucketImpl / ConvertingAggregatedToChunksWithMergingSource::generate

racing a concurrent read of the same two-level pointee.

Root cause. A UniqExactSet's two-level pointee is shared across several UniqExactSet objects: the merge fast path (two_level_set = other.getTwoLevelSet()) aliases one pointee into an empty destination, and parallelizeMergeMulti pre-fetches raw TwoLevelSet* to every state and reads those buckets across threads. So the parallel merge of GROUPING SETS/ROLLUP/CUBE states reads one pointee on one thread while another thread merges into a state that owns the same pointee.

doDeepCopyIfNeeded() forked (copied the pointee before mutating) only when shared_ptr::use_count() > 1. use_count() is not a synchronization primitive: a sibling holder being destroyed drops the count 2 -> 1 with no happens-before against the pointee's memory, so one state can observe use_count == 1 and write the pointee's buckets in place while another thread is still reading the same pointee. #108928 moved the copy-on-write from getTwoLevelSet() to the destination path but kept the racy use_count() guard, so the race persisted (this PR's branch — and the failing CI runs — already contain #108928).

Fix. Attach a monotonic is_shared atomic flag to the pointee (a small SharedTwoLevelSet wrapper). getTwoLevelSet() sets it (release) before the pointee escapes; doDeepCopyIfNeeded() forks when it is set (acquire) instead of consulting use_count(). A pointee that another thread can reach is therefore never mutated in place. A freshly forked copy is solely owned and unshared, so the common single-consumer case keeps mutating in place, preserving #108928's copy elision.

Testing. Added a unit test (gtest_uniq_exact_concurrent_alias_merge) that merges into and reads one shared two-level pointee from two threads. It reproduces the race on the pointee buckets before the fix (WRITE emplaceNonZeroImpl HashTable.h:1054 <- UniqExactSet::merge; READ HashTable::size HashTable.h:1460; same TwoLevelHashSetTable heap block) and is TSan-clean after. The existing UniqExactParallelMerge unit tests and 04489_uniq_exact_grouping_sets_concurrent_merge stay green, and parallel vs single-thread GROUPING SETS results are identical.

Closes #109495
Closes #109544

Version info

  • Merged into: 26.7.1.584 (included in 26.7 and later)
  • Backported to: 26.6.2.41, 26.5.6.22, 26.4.5.110, 26.3.17.29, 25.8.29.5

@groeneai

groeneai commented Jul 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Unit test UniqExactConcurrentAliasMerge.ConcurrentMergeOfSharedPointee under TSan (TSAN_OPTIONS="halt_on_error=1 symbolize=0" taskset -c 0-7 ./unit_tests_dbms --gtest_filter=...). The sole-owner variant races on the pointee buckets on every run before the fix; symbolized WRITE emplaceNonZeroImpl HashTable.h:1054 <- UniqExactSet::merge, READ HashTable::size HashTable.h:1460, same TwoLevelHashSetTable heap block.
b Root cause explained? Yes. The two-level pointee is aliased across UniqExactSet objects (merge fast path + parallelizeMergeMulti raw-pointer prefetch). doDeepCopyIfNeeded forked only on shared_ptr::use_count() > 1; use_count() is not a cross-thread sync primitive, so a sibling holder's destruction (count 2 -> 1) lets one state observe use_count == 1 and write the pointee in place while another thread reads it.
c Fix matches root cause? Yes. Replaces the racy use_count() guard with a monotonic per-pointee is_shared atomic flag, set (release) when the pointee is handed out and checked (acquire) before any in-place mutation. A reachable pointee is never mutated in place.
d Test intent preserved / new tests added? Yes. Added gtest_uniq_exact_concurrent_alias_merge. Existing UniqExactParallelMerge gtests and 04489_uniq_exact_grouping_sets_concurrent_merge remain unchanged and green.
e Both directions demonstrated? Yes. Races on the pointee before the fix; TSan-clean after (guard test x3 + 04489 GROUPING SETS/CUBE/ROLLUP rounds, 0 races). Parallel vs single-thread GROUPING SETS results are identical (EXCEPT count = 0).
f Fix is general across code paths? Yes. The fix is at the single shared-mutation boundary (doDeepCopyIfNeeded + getTwoLevelSet); all in-place mutators reach the pointee through asTwoLevelChecked(), and the shared_ptr member itself is thread-local (each group's state is owned by the one thread merging its bucket; parallelizeMergeMulti prefetches asTwoLevelChecked() single-threaded).
g Fix generalizes across inputs? Yes. is_shared is independent of key type / cardinality; it guards every two-level pointee regardless of the data.
h Backward compatible? Yes. No setting, format, or on-disk/wire change. Pure in-memory synchronization fix.
i Invariants and contracts preserved? Yes. Upholds the copy-on-write contract (a shared pointee is read-only; a solely-owned one is mutated in place, preserving #108928's copy elision) and the single-XOR-two-level invariant. Also fixes a latent bug the rework exposed: convertToTwoLevel() now early-returns when already two-level (rebuilding from the cleared single-level set would have discarded data) — matches the previous self-assign no-op.

Session id: cron:clickhouse-worker-slot-2:20260704-010200

@groeneai

groeneai commented Jul 4, 2026

Copy link
Copy Markdown
Collaborator Author

cc @Algunenano @nihalzp — could you review? This continues #108928: the uniqExact two-level parallel-merge TSan race (STID 1464-31ed) still fired on branches that already contain #108928, because doDeepCopyIfNeeded kept the use_count() guard. This replaces it with a monotonic per-pointee is_shared flag so a pointee that another thread can reach is never mutated in place.

@clickhouse-gh

clickhouse-gh Bot commented Jul 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [aa39521]

Summary: ✅


AI Review

Summary

This PR replaces the racy shared_ptr::use_count() check in UniqExactSet with a per-pointee is_shared flag and swaps the earlier concurrent gtest for a deterministic regression that exercises the 2 -> 1 lifetime transition directly. On the current head, the fix matches the reviewed race mechanism, the obsolete inline concern about the old concurrent test no longer applies, and I did not find a new correctness or compatibility issue in the touched paths.

Missing context / blind spots
  • ⚠️ I did not rerun the uniqExact unit tests locally because this checkout has no build directory, so validation here is based on the current diff, the surrounding aggregation code paths, and the existing PR discussion.
Final Verdict

✅ No new inline findings on the current head.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 4, 2026
@groeneai
groeneai force-pushed the groeneai/fix-uniqexact-two-level-merge-race branch from 9855bc4 to 43567f8 Compare July 4, 2026 04:31
STID 1464-31ed. The two-level pointee of a UniqExactSet is shared across
several UniqExactSet objects: the merge fast path (two_level_set =
other.getTwoLevelSet()) aliases one pointee into an empty destination, and
parallelizeMergeMulti pre-fetches raw TwoLevelSet* to every state and reads
those buckets across threads. The parallel merge of ROLLUP/CUBE/GROUPING SETS
states thus reads one pointee on one thread while another thread merges into a
state that owns the same pointee.

doDeepCopyIfNeeded forked (copied the pointee before mutating) only when
shared_ptr::use_count() > 1. use_count() is not a synchronization primitive: a
sibling holder being destroyed drops the count 2 -> 1 with no happens-before
against the pointee's memory, so one state can observe use_count == 1 and write
the pointee's buckets in place while another thread is still reading the same
pointee. That is a data race (TSan reports it; issue ClickHouse#108912 was a segfault
from the same in-place write). PR ClickHouse#108928 moved the copy-on-write from the
read-intent getTwoLevelSet() to the destination path but kept the racy
use_count() guard, so the race persisted.

Attach a monotonic is_shared atomic flag to the pointee (SharedTwoLevelSet
wrapper). getTwoLevelSet() sets it (release) before the pointee escapes;
doDeepCopyIfNeeded() forks when it is set (acquire) instead of consulting
use_count(). A pointee that another thread can reach is therefore never mutated
in place; a freshly forked copy is solely owned and unshared, so the common
single-consumer case keeps mutating in place (preserving ClickHouse#108928's copy
elision).

Regression test (gtest UniqExactSharedPointeeCoW): a direct, deterministic test
of the exact lifetime transition of STID 1464-31ed. A pointee P escapes to a
second UniqExactSet via the merge fast path (use_count 2), the sibling holder is
dropped (use_count 2 -> 1), then a merge mutates the surviving state. The test
asserts the pointee address changes, i.e. the mutation forks P instead of
writing the escaped instance in place. It fails before this change (in-place
mutation, same address) and passes after it (fork, new address). A concurrent
reader cannot form a valid fails-before/passes-after gate: any holder that keeps
P alive for the reader also bumps use_count so the buggy guard forks too, while
dropping it to force use_count == 1 makes the fix free P under the reader. So
the fork-vs-in-place decision, the necessary and sufficient cause of the race,
is asserted directly. Existing UniqExactParallelMerge gtests and
04489_uniq_exact_grouping_sets_concurrent_merge stay green, and parallel vs
single-thread GROUPING SETS results are identical.

Related: ClickHouse#108912
@groeneai
groeneai force-pushed the groeneai/fix-uniqexact-two-level-merge-race branch from 43567f8 to 34b38b9 Compare July 4, 2026 07:33

@Algunenano Algunenano 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.

Isn’t this already fixed by #108928 ?

@Algunenano Algunenano self-assigned this Jul 4, 2026
Comment thread src/AggregateFunctions/UniqExactSet.h Resolved
@groeneai

groeneai commented Jul 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 34b38b9

CI fully finished on this head (Finish Workflow + Config Workflow green, no checks queued/in_progress). Every failure below has an owner.

Check / test Reason Owner / fixing PR
Stress test (amd_tsan) / Join is supported only for pipelines with one output port, got 1 and 8 (STID 4488-4e11) trunk logical error (full_sorting_merge JOIN + query_plan_join_shard_by_pk_ranges=1 stream divergence); unrelated to this PR's UniqExactSet/HashTable TSan-race fix; 6 distinct sources in 45d (master x2 + PRs #108014, #105945, #104431, #109374), 0 caused here #109393 (ours, open)
CH Inc sync private upstream sync CH Inc sync (private, not actionable by us)

Note: the earlier Build (arm_tidy) failure was on the previous head 9855bc4db4fa (the clang-tidy lint the current head 34b38b9686f9 already fixed); it is not present on this head.

Session id: cron:our-pr-ci-monitor:20260704-110000

@Algunenano Algunenano added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Jul 6, 2026
Condense the verbose comment blocks around SharedTwoLevelSet, getTwoLevelSet
and doDeepCopyIfNeeded. No code change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.60% 85.60% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 77.80% 77.80% +0.00%

Changed lines: Changed C/C++ lines covered: 55/55 (100.00%) · Uncovered code

Full report · Diff report

@Algunenano
Algunenano added this pull request to the merge queue Jul 7, 2026
Merged via the queue into ClickHouse:master with commit 6984449 Jul 7, 2026
344 of 345 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jul 7, 2026
clickhouse-gh Bot added a commit that referenced this pull request Jul 7, 2026
Backport #109389 to 26.6: Fix TSan data race in uniqExact two-level parallel merge
Algunenano added a commit that referenced this pull request Jul 7, 2026
Backport #109389 to 25.8: Fix TSan data race in uniqExact two-level parallel merge
Algunenano added a commit that referenced this pull request Jul 7, 2026
Backport #109389 to 26.3: Fix TSan data race in uniqExact two-level parallel merge
Algunenano added a commit that referenced this pull request Jul 7, 2026
Backport #109389 to 26.4: Fix TSan data race in uniqExact two-level parallel merge
Algunenano added a commit that referenced this pull request Jul 7, 2026
Backport #109389 to 26.5: Fix TSan data race in uniqExact two-level parallel merge
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 8, 2026
@watson-ch watson-ch Bot added v26.2-must-backport v26.4-must-backport and removed pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR labels Jul 31, 2026
@watson-ch

watson-ch Bot commented Jul 31, 2026

Copy link
Copy Markdown

Backport labels have been automatically added based on https://github.com/clickhouse/clickhouse-core-incidents/issues/1933

Labels added:

  • v26.2-must-backport
  • v26.4-must-backport

These labels ensure backport PRs are properly created for each affected release version. The release automation will create backport PRs as needed based on these labels.

@robot-ch-test-poll robot-ch-test-poll added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jul 31, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jul 31, 2026
joelynch pushed a commit to aiven/ClickHouse that referenced this pull request Aug 17, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…xact-two-level-merge-race

Fix TSan data race in uniqExact two-level parallel merge
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.2-must-backport v26.4-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ThreadSanitizer: data race (STID: 1464-2f74) ThreadSanitizer: data race (STID: 1464-31ed)

7 participants