Skip to content

Fix the ineffective TSAN suppression in NonblockingBoundedQueue - #112695

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-keeper-nonblocking-queue-tsan-suppression
Jul 31, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-keeper-nonblocking-queue-tsan-suppression

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

Related: #107083

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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

...

Description

Integration tests (amd_tsan, N/6) fails in teardown with Sanitizer assert found for instance zoo<N>, from a TSAN data race between the slot.value write in NonblockingBoundedQueue::tryPush and the read in tryPop. #107083 added NO_SANITIZE_THREAD to both methods to silence it. That fix is merged and an ancestor of the failing branch, and the race still fires: 29 CIDB rows over 45 days across 27 pull requests, 4 of them after the merge.

The correctness analysis in #107083 is right: the release/acquire handoff on slot.pos orders every payload access, so the report is a false positive. Only the chosen mechanism is ineffective. NO_SANITIZE_THREAD covers just the annotated function's own body, and neither element type declares an operator=, so the racing access happens in the implicitly generated move assignment, a separate function that keeps sanitize_thread. The attribute also causes the frame split that defeats it, since an un-attributed callee cannot inline into an attributed caller.

This registers a __tsan_default_suppressions hook with two anchored patterns for the two Keeper instantiations, and removes the two attributes. Suppression applies to the report rather than to a function body, so one entry covers the whole nested move chain. Removing the attributes also restores plain-access instrumentation in the queue for all four element types, including the logging and keeper-bench queues that were being silenced for no reason, while atomics stay instrumented so the happens-before edges remain visible.

I have not identified the TSAN-internal path that produces the bogus shadow, so the suppression is scoped narrowly enough to drop if upstream fixes it. Only tryPush is listed, because dequeue_pos gives one consumer sole ownership of a slot before the move-out, so a concurrent pop cannot race on a payload. Each race: entry also hides heap-use-after-free through the named frame, which is why the set is kept at two.

Validation

A scratch harness drives the real queue header with the slot.pos handoff weakened to relaxed, linked against the real shipped hook, so a genuine race exists through the queue frames. It reproduces the CI signature exactly (__tsan_memcpy -> element operator= -> tryPop, read of size 8). The control arm omits the hook; every case below is confirmed non-vacuous there.

case control races shipped races matches expected
req_pushpop (witnessed signature) 8 0 4 suppressed
req_pushpush 14 0 4 suppressed
resp_pushpop 10 0 5 suppressed
resp_pushpush 20 0 5 suppressed
req_poppop 0 0 0 no race possible
log_pushpop, log_poppop (logging queue) 6 6 0 reported
bench_pushpop (keeper-bench) 6 6 0 reported
size, byref, unrelated 2 2 0 reported

Suppressed runs print matched suppression naming the shipped pattern, so the demangled-name match is empirical.

Why the attribute cannot work, measured on the real header. With it, tryPush and tryPop carry 0 plain-access hooks but each still calls the element move out of line, and that move body carries 11 hooks including __tsan_memcpy. Without it they carry 18 and 19 hooks and the move inlines; atomics are 8/8 in both arms.

On the real TSAN binary both patterns match exactly one live symbol each, so neither is a dead entry, and mangling only the suppression type makes the runtime fail to parse and die at startup, proving the list is consumed rather than merely present.

No test is added or changed, and no integration job applies setting randomization.

Witnessed failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107074&sha=e42b9c4c1c5cda0dc694c4150a195295639e4ca3&name_0=PR&name_1=Integration%20tests%20%28amd_tsan%2C%204%2F6%29

groeneai and others added 2 commits July 31, 2026 00:56
`Integration tests (amd_tsan, N/6)` fails in teardown with `Sanitizer assert
found for instance zoo<N>`, from a TSAN data race between the `slot.value`
write in `NonblockingBoundedQueue::tryPush` and the read in `tryPop`.

PR ClickHouse#107083 added `NO_SANITIZE_THREAD` to both methods to silence it. That fix
is merged and an ancestor of the failing branch, and the race still fires: 29
CIDB rows over 45 days across 27 distinct pull requests, 3 of them on master,
and 4 after the merge timestamp.

The correctness analysis in ClickHouse#107083 is right. The release/acquire handoff on
`slot.pos` orders every access to a slot payload, and there is no non-protocol
payload access anywhere in the class, so the report is a false positive. Only
the chosen mechanism is ineffective:

  * `NO_SANITIZE_THREAD` suppresses instrumentation of plain accesses in the
    annotated function's own body only. Neither `KeeperRequestForSession` nor
    `KeeperResponseForSession` declares an `operator=`, so the racing access
    happens in the implicitly generated move assignment, a separate function
    that keeps `sanitize_thread`.
  * The attribute also causes the frame split that defeats it, because an
    un-attributed callee can never be inlined into an attributed caller.

Measured at IR level on the real header: with the attribute, `tryPush` and
`tryPop` carry 0 plain-access hooks but each still calls the element move out
of line, and that move body carries 10 hooks including the `__tsan_memcpy`
that the CI report names.

Register a `__tsan_default_suppressions` hook instead, with two anchored
patterns for the two Keeper instantiations, and remove the two attributes.
Suppressions are consulted for every frame of a report, so one entry covers
the whole nested move chain, which is what no compile-time mechanism achieves.
Removing the attributes additionally restores plain-access instrumentation in
the queue for all four element types, including the logging and keeper-bench
queues that were being silenced for no reason, while atomics stay instrumented
so the happens-before edges remain visible to TSAN.

Only `tryPush` is listed. A concurrent pop cannot race on a payload, because
`dequeue_pos` gives exactly one consumer ownership of a slot before the
move-out; this was measured, not assumed. Each `race:` entry also hides
heap-use-after-free reports through the frame it names, so the set is kept at
the proven minimum of two.

The TSAN-internal path that produces the bogus shadow is not identified.
Shadow-cell eviction is refuted, since it is reached only after the scan finds
no race and can therefore only cause false negatives. The signature is worth
reporting upstream, and the suppression is scoped narrowly enough to drop if
that lands.

Non-sanitizer builds are unaffected: the hook is inside `#ifdef
THREAD_SANITIZER`, and removing the attributes is codegen-neutral without a
sanitizer (same translation unit compiled with and without the attribute
yields byte-identical objects when built without `-g`, and byte-identical
`.text` with `-g`).
Review round 1, comment only. The executable change is unmodified: the two
anchored `tryPush` suppression entries and the removal of the two
`NO_SANITIZE_THREAD` attributes are byte-identical to the previous commit.

The comment justified listing only `tryPush` by saying each Keeper queue has a
single consumer, and then warned that giving one a second consumer would make a
pop/pop report possible and require a `tryPop` entry. That warning is wrong, and
the justification is weaker than what the code guarantees.

A pop/pop payload race is impossible for any number of consumers. In `tryPop`
the `dequeue_pos` compare-exchange admits exactly one consumer per position and
only the winner reaches the move-out of `slot.value`. Two consumers can target
one slot index only when their positions differ by the capacity, and the later
one cannot pass the emptiness check until the earlier one publishes the slot,
which happens after its move-out. Independently, ThreadSanitizer requires two
distinct thread ids to report a race, so a single consumer cannot race itself.

The comment now states that reason and drops the refuted warning. Adding a
`tryPop` entry would be a dead entry that also hides heap-use-after-free
reports through that frame.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, 11 findings adjudicated, 0 open blockers)

Before opening this I ran an independent cold review plus a separate second-model gate pass over
each revision, and adjudicated every finding. Two rounds: the first bounced the branch for a fix,
the second came back clean (gate findings=0). Recorded here so a reviewer can see what was
challenged and on what evidence, rather than taking a clean result on trust.

Verdict totals. Round 1: 3 AGREE (2 fixed by me in the PR text, 1 bounced as a code change),
3 DISAGREE with evidence. Round 2: 4 AGREE (all fixed), 3 DISAGREE with evidence. Nothing
deferred. No finding was overridden without a refutation of a step it actually needs.

❌ Blocker raised and refuted: "the standalone Keeper binary never registers the suppressions"

The gate observed that BUILD_STANDALONE_KEEPER builds programs/keeper/keeper_main.cpp as the
entry point and that this file does not include base/sanitizer_options.h. Both true, and the
conclusion still does not follow, for two independent reasons.

The hook cannot be missing from any standalone build, because no standalone build has a sanitizer.
Cross-tabulating every BuildTypes entry in ci/defs/, BUILD_STANDALONE_KEEPER=1 appears only
for AMD_RELEASE and ARM_RELEASE, both with -DSANITIZE= empty; SANITIZE=thread appears only
in AMD_TSAN/ARM_TSAN, which set it to 0. So #ifdef SANITIZER compiles the whole hook away
wherever that binary exists.

And the failing job cannot be running that binary anyway. With BUILD_STANDALONE_KEEPER=0,
programs/clickhouse-keeper is a symlink (programs/CMakeLists.txt:208), and
tests/integration/helpers/cluster.py:1384-1393 takes the standalone branch only when the path
exists and not os.path.islink(...). It therefore falls through to clickhouse keeper, the
multi-call binary, whose entry point programs/main.cpp:4 does include the header. Confirmed in
the TSAN tree used for this work (build-tsan/programs/clickhouse-keeper -> clickhouse) and in the
shipped binary, which has exactly one strong T __tsan_default_suppressions.

⚠️ Recording the remedy hazard, because it looks harmless: adding that include to
keeper_main.cpp would be a bug. That file is compiled into clickhouse-keeper-lib in every
build, and that library is linked into the clickhouse executable
(programs/CMakeLists.txt:146) alongside main.cpp (:135), with an unguarded main(). Since
base/base/sanitizer_options.h:5-7 requires each hook to be defined exactly once per binary, the
include would produce two definitions of the same extern "C" symbol in one link.

⚠️ Separately, and out of this PR's scope: on the merge base keeper_main.cpp registers no
sanitizer hooks at all, not just the tsan one. That is a latent gap in a configuration CI never
builds with a sanitizer, so it changes nothing here, but it is worth someone's attention.

❌ Bounced for a code change: the comment justified the entry set with a claim my own measurement refutes

Round 1's substantive finding was in the in-diff comment, not the mechanism. It justified listing
only tryPush by the fact that each Keeper queue has a single consumer, and then warned that
"giving either of them a second consumer makes a pop/pop report possible and requires a matching
entry there". That warning is wrong, and the justification is weaker than what the code guarantees.

A pop/pop payload race is impossible for any consumer count.
dequeue_pos.compare_exchange_weak admits exactly one consumer per position, and only the CAS
winner reaches out_value = std::move(slot.value). Two consumers can target the same slot index
only if their positions differ by the capacity, and the later one cannot pass the emptiness guard
until the earlier one has published its release store, which happens after its move-out. TSAN also
short-circuits when both accesses carry the same sid, so a single consumer cannot race with itself.
The verification harness measured exactly this: the req_poppop case is silent even on the control
arm with no suppressions linked.

Since the comment lives in source and I do not edit source in this role, it went back as a fix
round. The revision now grounds the conclusion in the CAS ownership argument and drops the refuted
warning; I re-derived that replacement from the queue protocol before accepting it. The same
contradiction was also present in the pre-PR validation notes and was corrected there in the same
round.

❌ Off-by-one in a published measurement, found by re-deriving it

Round 2 caught a wrong number in this PR's own description. It said the out-of-line element-move
body "carries 10 hooks including __tsan_memcpy". Parsing the recorded IR gives 17 __tsan_*
calls in that body: 2 atomics, 2 entry/exit, 2 vptr, and 11 plain-access hooks. The figure is
11, not 10.

The counting convention is not in doubt, because the three sibling figures in the same sentence are
exact under it: 0 plain-access hooks in tryPush/tryPop with the attribute, 18 and 19 without.
Only the move-body number was wrong, and only one published copy of it existed. Corrected before
opening, and the corrected text was re-gated rather than published on the strength of the earlier
pass.

💡 Reported by the implementation rather than silently changed, and left as is

base/base/sanitizer_options.h still grounds the same conclusion in the single-consumer argument
while the queue header now uses the stronger CAS argument. I checked it rather than assuming, and
left it deliberately.

The premise is true: the only tryPop consumers are the single dispatch_thread and the single
response_thread, both ThreadFromGlobalPool members started once each behind a
chassert(!joinable()), and the third drain site runs inside shutdown() after both joins, so it
is temporally exclusive. KeeperRequestDispatcherOld's responses_queue is a different class and
not a carrier. The logic is also valid: of the three report shapes, push/pop and push/push both
contain a tryPush frame and pop/pop is excluded. Crucially, unlike the sentence the fix round
removed, it makes no claim that a second consumer would need a tryPop entry, so nothing in the
tree contradicts itself. Rewriting it would move base/ outside the byte range two gate rounds
have covered, for a prose refinement, so it stays.

💡 What I verified independently, in case it saves a reviewer the same work

The delta of the second round is comment-only, so I re-derived the mechanism from the vendored
runtime and the shipped binary rather than reusing the first round's conclusions.

race: genuinely covers heap-use-after-free (conv() maps ReportTypeUseAfterFree and
ReportTypeVptrUseAfterFree to kSuppressionRace), which is why keeping the set at two entries is
a real cost argument. Matching either side of a pair suffices: OutputReport loops over every
rep->mops stack and IsSuppressed walks every frame. A suppressed report returns before
PrintReport and before Die(), so no ================== banner is written, which is exactly
the string the Keeper stderr.log scanner greps, so this genuinely clears the observed failure.
The matched-suppression summary cannot re-trip that scanner either, because TSAN forces
print_suppressions=false. The hook is the live channel: no suppressions= is set anywhere in
ci/, tests/integration/helpers/ or docker/, and tests/tsan_ignorelist.txt is the separate
compile-time -fsanitize-ignorelist mechanism. ^ anchoring behaves as claimed (TemplateMatch
treats only ^, *, $ as special), so the patterns cannot match this header's file name, the
logging queue, the keeper-bench queues, or either tryPop.

The one that matters most: objdump of the shipped tryPush for the request type shows zero
out-of-line calls to the element move, __tsan_memcpy twice inside tryPush itself, atomics
intact, and no separate symbol for the element move assignment. The frame the CI report named is
now tryPush, which is what the entries anchor on. Both patterns match exactly one live symbol
each, so neither entry is dead.

Session id: cron:clickhouse-review-slot-9:20260731-020500

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The CI failure itself is rare (29 CIDB rows / 45d), so the mechanism is made deterministic instead: a harness drives the real NonblockingBoundedQueue header with the slot.pos handoff weakened to relaxed, linked against the real shipped __tsan_default_suppressions TU. It reproduces the CI stack exactly on demand: __tsan_memcpy -> DB::KeeperRequestForSession::operator=(...&&) -> NonblockingBoundedQueue<DB::KeeperRequestForSession>::tryPop, read of size 8. Not a "~1%".
b Root cause explained? Yes. The release/acquire handoff on slot.pos orders every payload access, so the report is a false positive; there is no non-protocol payload access. NO_SANITIZE_THREAD cannot suppress it because neither element type declares an operator=, so the racing access lives in the implicitly generated move assignment, a separate function that keeps sanitize_thread; the attribute also blocks that callee from inlining into the annotated caller. The TSAN-internal path that produces the bogus shadow is deliberately left unidentified and the PR body says so (shadow-cell eviction refuted; DoReset plausible but unproven).
c Fix matches root cause? Yes. Suppression must apply to the report, not to a function body, so the runtime __tsan_default_suppressions hook is the correct layer; the ineffective attributes are removed rather than left as a self-contradiction. Not a widened bound, not a disabled or weakened test, not a defensive check masking an upstream bug. Compile-time ignorelists, an attribute on the element operator=, a queue-side move helper, __tsan_acquire/__tsan_release and DISABLE_SANITIZER_INSTRUMENTATION were each measured or reasoned out and rejected.
d Test intent preserved / new tests added? No test is added, changed or relaxed, and this is argued rather than skipped: the trigger is a rare TSAN-runtime artifact, so the acceptance criterion is mechanism-level. The change increases what TSAN checks - removing the attributes restores 18 and 19 plain-access hooks in tryPush/tryPop for all four element types, including the two that are not suppressed.
e Both directions demonstrated? Yes, on Build-ID-verified binaries. Control arm (hook TU omitted, runtime weak default): 8 / 14 / 10 / 20 genuine races for the four Keeper shapes. Shipped arm: 0 races, with 4-5 matched suppression lines naming the exact shipped pattern. Every case is confirmed non-vacuous on the control arm.
f Fix is general across code paths? Yes. Carrier audit run tree-wide (git grep -l NonblockingBoundedQueue origin/master): 7 files, 4 element types, each with an explicit disposition. Both Keeper queues covered by one entry each; the logging queue (src/Loggers/OwnSplitChannel.h) and the three programs/keeper-bench/ queues deliberately left reportable and measured to be so. Single-consumer claim verified in source, including the one nearby false lead (KeeperTCPHandler's responses is a ConcurrentBoundedQueue, a different class; src/Server/ has 0 references to this queue).
g Fix generalizes across inputs (params/datatypes/wrappers)? Not applicable in the type-wrapper sense (no user data types). The analogous axis is report shape, and all reachable shapes are covered: push/pop and push/push suppressed for both Keeper element types, pop/pop measured impossible (dequeue_pos gives one consumer sole ownership of a slot before the move-out), and 6 negative shapes measured REPORTED.
h Backward compatible? (maintainer-approved exception only) Yes, trivially. No settings, no serialization, no protocol, so no SettingsChangesHistory.cpp entry. Sanitizer-only header hook plus a comment; non-sanitizer executable code is byte-identical (.text md5 equal, full IR comparison 11/11 functions and 0 differing bodies).
i Invariants and contracts preserved? Yes. Queue logic untouched (two attributes and a comment); both static_asserts still hold; atomics stay instrumented 8/8 in both arms so the happens-before edges TSAN needs remain visible; error and early-return paths touch no payload. The one narrowed contract is that the two entries are exact anchored strings, so renaming tryPush or either element type makes them dead; the nm -C check in the validation notes is what guards that.

Session id: cron:clickhouse-impl-slot-40:20260731-014200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @al13n321 @antonio2368, could you review this? Your correctness analysis in #107083 holds, but NO_SANITIZE_THREAD covers only the annotated function's own body, and neither Keeper element type declares an operator=, so the racing access lives in the implicitly generated move assignment, a separate function that stays instrumented and that the attribute itself keeps out of line. This moves the suppression to a __tsan_default_suppressions hook with two anchored patterns and removes the two attributes, which also restores plain-access instrumentation for the logging and keeper-bench queues.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 31, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [69243dc]

Summary: ✅


AI Review

Summary

This PR replaces the ineffective NO_SANITIZE_THREAD workaround on NonblockingBoundedQueue with two __tsan_default_suppressions entries so Keeper TSAN jobs stop flagging the known false-positive while the queue itself stays instrumented. The direction is correct, but the fix is still incomplete: standalone clickhouse-keeper builds do not register the new suppressions, so the same report survives in BUILD_STANDALONE_KEEPER=1 TSAN builds.

Findings

⚠️ Majors

  • [src/Common/NonblockingBoundedQueue.h:88-89] The new comment says these reports are suppressed by __tsan_default_suppressions, but that is only true for executables whose main translation unit includes base/sanitizer_options.h. Standalone Keeper still uses programs/keeper/keeper_main.cpp, which does not include that header, and tests/integration/helpers/cluster.py:1384-1389 prefers the standalone clickhouse-keeper binary whenever it exists. That leaves BUILD_STANDALONE_KEEPER=1 + THREAD_SANITIZER reproductions on the old unsuppressed path, so the PR's stated fix is incomplete for a real build configuration.
    Suggested fix: register the same suppressions in the standalone clickhouse-keeper executable as well, but do it through a standalone-only translation unit or target-specific source so the clickhouse binary still sees exactly one definition of each sanitizer hook.
Final Verdict

Status: ⚠️ Request changes

Minimum required action: make standalone clickhouse-keeper builds register the new __tsan_default_suppressions too, without introducing duplicate hook definitions into the multi-call clickhouse binary.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jul 31, 2026
Comment on lines +88 to +89
/// Those reports are suppressed at runtime, per instantiation, by
/// `__tsan_default_suppressions` in base/sanitizer_options.h. A `NO_SANITIZE_THREAD` attribute

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This is only true for executables whose main translation unit includes base/sanitizer_options.h. BUILD_STANDALONE_KEEPER=1 still runs Keeper through programs/keeper/keeper_main.cpp, which does not include that header, and the integration harness prefers the standalone clickhouse-keeper binary whenever it exists (tests/integration/helpers/cluster.py:1384-1389). So a TSAN standalone Keeper build still hits the same false-positive with no suppression registered. If this is meant to be the general Keeper fix, the standalone executable needs the hook too, likely via a standalone-only TU so clickhouse still keeps exactly one definition.

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.

Ok, as we don't use the standalone Keeper build.

@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.60% -0.10%

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

Full report · Diff report

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

Believable.

@alexey-milovidov alexey-milovidov self-assigned this Jul 31, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 31, 2026
Merged via the queue into ClickHouse:master with commit ed34004 Jul 31, 2026
178 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 31, 2026
alexey-milovidov pushed a commit that referenced this pull request Aug 1, 2026
…26.5

Every 26.5 pull request keeps failing the TSan integration shards with
"Sanitizer assert found for instance zoo3-1", whose Keeper container log carries a
ThreadSanitizer data race between the slot payload write in
NonblockingBoundedQueue::tryPush and the read in tryPop. The release/acquire handoff
on slot.pos orders every access to a slot payload, so the report is a false positive.

master fixed this in #112695 by registering the two anchored tryPush patterns through
__tsan_default_suppressions. That fix is not on 26.5, and it cannot be cherry-picked:
base/base/sanitizer_options.h does not exist on this branch, so the hook goes beside
the existing __tsan_default_options in programs/main.cpp, inside the same
"#ifdef THREAD_SANITIZER" block.

The change is purely additive here. #107083, which added the NO_SANITIZE_THREAD
attributes that #112695 removed as ineffective, was never backported either, so there
is no attribute to delete. A function attribute could not have suppressed these
reports anyway: the reported access happens in the element type's implicitly
generated move assignment, a separate function that stays instrumented, and the
attribute additionally prevents it from being inlined into the annotated one.

Only tryPush is listed. tryPop writes the payload too, but the dequeue_pos
compare-exchange gives one consumer sole ownership of a slot before the move-out, so
two pops never touch one payload concurrently, whatever the consumer count. A tryPop
entry would be dead, and a "race:" entry also hides heap-use-after-free reports
through the frame it names.

Sanitizer builds only: outside THREAD_SANITIZER the hook is preprocessed away, and
the queue header change is a comment.

Co-Authored-By: Claude Fable 5 <[email protected]>
clickhouse-gh Bot pushed a commit that referenced this pull request Aug 1, 2026
…26.7

The TSan integration shards abort in teardown with `Sanitizer assert found
for instance zoo<N>`. The Keeper container log carries a data race between the
slot payload write in `NonblockingBoundedQueue<DB::KeeperResponseForSession>::tryPush`
and the read in `tryPop`. The release/acquire handoff on `slot.pos` orders every
access to a slot payload, so the report is a false positive, but it aborts the
Keeper process and reds the whole shard.

master fixed this in #112695 by registering two anchored `tryPush` patterns
through `__tsan_default_suppressions`. A function attribute cannot suppress
these reports: the reported access happens in the element type's implicitly
generated move assignment, a separate function that stays instrumented, and the
attribute additionally prevents it from being inlined. A runtime suppression is
consulted for every frame of a report, so one entry per instantiation covers the
whole nested move chain.

Authored by hand rather than cherry-picked: master's queue-header hunk does not
apply here, because its context is the `NO_SANITIZE_THREAD` attribute this branch
never had. #107083, which added those attributes, was never backported either, so
this change is purely additive and there is nothing to remove. The hook goes in
`base/base/sanitizer_options.h` beside the existing `__tsan_default_options`,
which is master's placement; the 26.5 sibling (#112899) had to use
`programs/main.cpp` because that header does not exist there.

Only `tryPush` is listed. `tryPop` writes the payload too, but the `dequeue_pos`
compare-exchange gives one consumer sole ownership of a slot before the move-out,
so two pops never touch one payload concurrently, whatever the consumer count. A
`tryPop` entry would be dead, and each `race:` entry also hides
heap-use-after-free reports through the frame it names, so the set is kept at the
proven minimum of two.

Both patterns are `^`-anchored on the two Keeper instantiations and each names
exactly one live symbol in the built binary. keeper-bench also instantiates the
queue, but its element type is a private nested struct of `StorageRunner`, so it
demangles as `NonblockingBoundedQueue<StorageRunner::QueueItem>` and matches
neither pattern.

The signature has not been observed on this branch, unlike 26.5 and 26.6, but
that is sample size rather than immunity: at master's observed rate the
probability of seeing zero occurrences is about 88 percent on this branch's TSan
integration build volume, and about 72 percent on each of 26.5 and 26.6, which
did see one. The reason to include 26.7 is structural. Both carrier files are
present with both explicit instantiations, and its copy of the queue header is
md5-identical to 26.6's. 26.4 and older lack the files entirely.

Sanitizer builds only: outside `THREAD_SANITIZER` the hook is preprocessed away,
verified as zero hook symbols and zero payload strings in a non-sanitizer build,
and inside it is one `const char *` returning a fixed string read once at
sanitizer init. The queue header change is a comment, so no executable line of
the queue changed. No new test, matching #112695: the only end-to-end oracle is
the TSan integration shards going quiet over many runs.

Co-Authored-By: Claude Fable 5 <[email protected]>
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Aug 20, 2026
…e` subtree

On `amd_tsan` integration shards the Keeper container occasionally writes a
ThreadSanitizer report for the request the dispatch thread just popped, which
aborts the container. `helpers/cluster.py` then raises
`Sanitizer assert found for instance zooN` during `cluster.shutdown()`, and
whichever test happened to run last goes red; the victim is incidental.

There is no real race: `KeeperTCPHandler::receiveRequest` writes every payload
field of the request before publishing it with `putRequest`, and
`getRequestBytesCost` on the consumer side only reads the vptr and those fields.

The existing entry was added as `race_top:^DB::getRequestBytesCost`, which
matches the innermost frame only. That covered the vptr read, attributed to the
call site inside `getRequestBytesCost` - but suppressing it just moved the
report one frame down, to the `path` read inside
`Coordination::GetRequest::bytesSize`, which aborts the container all the same.
Use `race:` so the entry covers the whole callee subtree; that subtree is only
`bytesSize`, a read-only size computation.

Validated against the real ThreadSanitizer runtime with a harness that
reproduces both frame shapes (arms differ only in the string returned by
`__tsan_default_suppressions`; `banner` counts runs printing the
`==================` line the integration harness greps for):

| suppression                                | vptr shape | `bytesSize` shape |
|--------------------------------------------|------------|-------------------|
| (empty)                                    | 8/10       | 10/10             |
| `race_top:^DB::getRequestBytesCost`        | 8/10       | 9/10              |
| `race:^DB::getRequestBytesCost`            | 0/20       | 0/20              |

With `race_top:` the surviving report is exactly the one master hit: the
`path.size()` read inside `bytesSize`, one frame below `getRequestBytesCost`.
Controls: a typo'd pattern parses but suppresses nothing (10/10 banner), a
mangled type token makes the runtime die with `failed to parse suppressions`,
and `print_suppressions=1` shows the new entry being hit.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=dddf61ccff5828bb6937cfe680874a04be35932f&name_0=MasterCI&name_1=Integration%20tests%20%28amd_tsan%2C%206%2F6%29

Related: ClickHouse#113552
Related: ClickHouse#112695

Co-Authored-By: Claude Fable 5 <[email protected]>
PedroTadim pushed a commit that referenced this pull request Sep 4, 2026
Backport of #112695 to 26.6, requested by alexey-milovidov on #112722.
26.6 still carries the defect and has no fix.

`Integration tests (amd_tsan, N/6)` fails in teardown with `Sanitizer assert
found for instance zoo<N>`, from a TSAN data race report between the
`slot.value` write in `NonblockingBoundedQueue::tryPush` and the read in
`tryPop`.

The report is a false positive. The release/acquire handoff on `slot.pos`
orders every access to a slot payload, and there is no non-protocol payload
access anywhere in the class, so the code is isomorphic to Vyukov's original
implementation. But `abort_on_error=1` in `__tsan_default_options` turns the
report into an aborted Keeper node, so healthy runs go red.

A `NO_SANITIZE_THREAD` attribute cannot suppress it. Neither
`KeeperRequestForSession` nor `KeeperResponseForSession` declares an
`operator=`, so the racing access happens in the implicitly generated move
assignment, a separate function that keeps `sanitize_thread`. The attribute
also prevents that un-attributed callee from being inlined into the attributed
caller, which is what creates the frame split that defeats it. A runtime
`__tsan_default_suppressions` entry is consulted for every frame of a report,
so one entry covers the whole nested move chain.

Register that hook with two anchored patterns for the two Keeper
instantiations. Only `tryPush` is listed: the `dequeue_pos` compare-exchange
gives one consumer sole ownership of a slot before the move-out in `tryPop`,
so a pop/pop payload race cannot occur at any consumer count, and each `race:`
entry also hides heap-use-after-free reports through the frame it names.

Anchoring is load-bearing. Patterns are matched against each frame's function,
file and module name, and `clickhouse-keeper-bench` is a symlink to the same
binary, so an unqualified pattern would also silence its three unrelated
`NonblockingBoundedQueue<QueueItem>` queues. Verified it does not.

This is purely additive, unlike the master commit: #107083, which added the
attributes master removes, was never backported to 26.6, so there is no
attribute to strip here. A straight cherry-pick does not apply (`git apply
--check` fails on both files); on 26.6 the hook goes in
`base/base/sanitizer_options.h`, which is master's own placement, whereas the
26.5 sibling #112899 had to use `programs/main.cpp` because that header does
not exist on 26.5.

Non-sanitizer builds are unaffected: the hook is inside `#ifdef
THREAD_SANITIZER` and the other change is a comment, so there is no codegen
change and no performance impact. A suppression only affects whether TSAN
prints or aborts on a report.

No test, matching #112695. The only oracle is a CI-side absence property over
many runs, which no functional test can assert.

Co-Authored-By: Claude Fable 5 <[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-ci 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.

4 participants