Skip to content

Try to do something about TSAN error in NonblockingBoundedQueue - #106801

Closed
al13n321 wants to merge 1 commit into
masterfrom
tsanope
Closed

al13n321 wants to merge 1 commit into
masterfrom
tsanope

Conversation

@al13n321

@al13n321 al13n321 commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

A perplexing TSAN error. I didn't figure out the cause. Happened ~6 times over 2 weeks, in different integration tests.

https://play.clickhouse.com/play?user=play#U0VMRUNUIGNoZWNrX3N0YXJ0X3RpbWUsIHRlc3RfbmFtZSwgcHVsbF9yZXF1ZXN0X251bWJlciwgcmVwb3J0X3VybApGUk9NIGNoZWNrcwpXSEVSRSBjaGVja19zdGFydF90aW1lID49IG5vdygpIC0gSU5URVJWQUwgMzAgREFZCiAgQU5EIGNoZWNrX25hbWUgSUxJS0UgJyVJbnRlZ3JhdGlvbiUnCiAgQU5EIHRlc3RfY29udGV4dF9yYXcgTElLRSAnJVNhbml0aXplciBhc3NlcnQgZm91bmQgZm9yIGluc3RhbmNlIHpvbyUnCiAgYW5kIGJhc2VfcmVmID0gJ21hc3RlcicKICBhbmQgcHVsbF9yZXF1ZXN0X251bWJlciAhPSAxMDE3NTcKT1JERVIgQlkgY2hlY2tfc3RhcnRfdGltZSBERVND

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106185&sha=fb27559f055b68972384718352e7c41b809441b3&name_0=PR&name_1=Integration%20tests%20%28amd_tsan%2C%206%2F6%29&name_1=Integration%20tests%20%28amd_tsan%2C%206%2F6%29

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

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=105891&sha=775580d0e4e076b016a615cd1fee61e5fc640d17&name_0=PR&name_1=Integration%20tests%20%28amd_tsan%2C%201%2F6%29&name_1=Integration%20tests%20%28amd_tsan%2C%201%2F6%29

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=97676&sha=8e774bd9e9054aaae7708ffad555f15c570c77ae&name_0=PR&name_1=Integration%20tests%20%28amd_tsan%2C%205%2F6%29&name_1=Integration%20tests%20%28amd_tsan%2C%205%2F6%29

(etc)

TSAN says data race in NonblockingBoundedQueue between writing slot.value in tryPush and reading slot.value in tryPop from another thread. I.e. exactly the normal usage of the queue, exactly the race the queue's fancy atomics with fancy memory_orders are meant to prevent.

  • Neither I nor claude found any significant difference between this code and Vykov's original code, which seems very unlikely to be incorrect.
  • I think I have a proof that this particular race can't happen.
  • Claude failed to find or reproduce known TSAN problems that lead to such blatant false positives on spinlock-like things. It guessed it may have something to do with pushing to the queue from lots of threads (one KeeperTCPHandler thread per client connection) or with those threads exiting between the enqueue and dequeue.

So, I'm confused and ran out of plausible hypotheses. Maybe I'm just being silly and there's an obvious bug.

Here's a desperate PR that adds another atomic load to (a) explicitly re-check the invariant and possibly crash if the code is actually wrong, (b) possibly work around TSAN problem.

@clickhouse-gh

clickhouse-gh Bot commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c1a2f73]

Summary: ✅


AI Review

Summary

This PR adds a second acquire load of slot.pos plus a release-build std::abort invariant check in both NonblockingBoundedQueue::tryPush and NonblockingBoundedQueue::tryPop, aiming to affect a rare Keeper TSan report. The underlying queue algorithm and current call sites look consistent with the intended MPMC/MPSC contract, but the proposed mitigation still changes a hot production primitive without evidence that the unconditional cost and process abort semantics are acceptable, so I would not approve it as-is.

Findings

⚠️ Majors

  • [src/Common/NonblockingBoundedQueue.h:126] NonblockingBoundedQueue promises a high-throughput nonblocking queue for Keeper request/response paths, but the new invariant recheck adds another acquire load on every successful tryPush and can call std::abort in release builds. The same issue exists in tryPop at line 164. This turns a TSan-only investigation into production overhead and a new process-termination path without evidence that either is needed or acceptable.

    Suggested fix: keep the additional synchronization/checking out of normal release builds, for example by guarding it under THREAD_SANITIZER or a debug/sanitizer-only assertion path, or replace it with a TSan suppression/annotation after validating it against the failing job. If the checks must stay enabled in release builds, provide a focused benchmark and rationale for the abort semantics.

Tests
  • ⚠️ The PR is trying to mitigate a rare TSan report, but the current evidence only shows the latest PR CI passing; because the failure is rare, that does not prove the new acquire reload affects the reported race. Please validate the chosen mitigation against the failing Keeper TSan scenario, a focused reproducer, or a documented suppression/annotation strategy.
  • ⚠️ If the extra acquire loads remain in production builds, please add before/after measurements for the affected NonblockingBoundedQueue hot paths, especially the Keeper request and response queues.
Performance & Safety
  • The added checks are on every successful queue operation in a primitive explicitly used to avoid futex overhead in high-throughput paths. The process abort path also changes failure behavior from a sanitizer-only diagnostic concern into a production availability risk.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions: remove or gate the production hot-path checks, and provide evidence that the selected TSan mitigation actually addresses the reported failure mode. If keeping release-build checks, provide performance data and justify the std::abort behavior.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Jun 9, 2026
/// (slot.pos - i) parity to odd.
/// * tryPop symmetrically does slot.pos.load(acquire), checks that parity is odd,
/// does the read, does slot.pos.store(release) that flips parity back to even.
size_t slot_pos_again = slot.pos.load(std::memory_order_acquire);

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 PR is trying to work around a TSan-only report, but this check runs in every release build too. NonblockingBoundedQueue is explicitly a high-throughput queue and tryPush/tryPop are on Keeper request/response paths, so adding an acquire load, plus a release-build std::abort path, to every successful operation changes production behavior without evidence that production needs it. Please either gate the extra loads/checks under THREAD_SANITIZER/DEBUG_OR_SANITIZER_BUILD, or include a benchmark/justification showing the unconditional cost and abort semantics are acceptable. The same applies to the matching check in tryPop.

@antonio2368 antonio2368 self-assigned this Jun 9, 2026
@antonio2368

Copy link
Copy Markdown
Member

I got the same from my investigation here is AI summary of it:

The failures

Four Keeper TSan CI runs (PRs 106185, 106178, 105891, 97676) all report the same race,
inside the zoo* Keeper nodes (not the test target). The harness surfaces it as
Sanitizer assert found for instance zooN-1; whichever integration test happens to exercise
Keeper trips it.

The race: slot.value written in tryPush (src/Common/NonblockingBoundedQueue.h:107) vs read in
tryPop (:138) on the same ring-buffer slot — i.e. exactly the producer→consumer handoff the
queue's atomics are meant to order. Two variants: the request queue (producer = per-connection
KeeperTCPHandler thread; consumer = single dispatchThread) and the response queue
(producer via onResponse; consumer = single responseThread).

Root cause: a benign TSan false positive

  • The queue is correct. NonblockingBoundedQueue is a textbook Vyukov bounded MPMC queue. The
    per-slot slot.pos acquire/release pairing provably orders every slot.value access in both
    directions — producer-write→consumer-read (release@108 sync-with acquire@120) and
    consumer-read→next-wrap-producer-write (free release@139 sync-with acquire@89). The relaxed init
    store (pre-threads) and the relaxed enqueue_pos/dequeue_pos CAS (index mutual-exclusion only)
    gate no value access, so they break nothing.
  • No call-site misuse. Both queues are used as MPSC (many producers, one dedicated consumer),
    a valid subset of the queue's MPMC contract. The flagged conflict is producer↔consumer, not
    producer↔producer.
  • A TSan race report ⟺ TSan held no happens-before edge. Since the edge provably exists in the
    abstract machine, TSan must have dropped the per-slot edge → false positive. The
    "As if synchronized via sleep" note (it could only point at the dispatch busy-wait) and
    "mutexes: write M0" (an incidental lock on the producer path) both confirm TSan found no real
    atomic edge.

Likely mechanism (thread recycling)

The producers are short-lived, per-connection Poco worker threads: a producer does the
release@108, the connection closes, the thread exits and TSan recycles its (finite) thread slot,
dropping the dead thread's release clock. The long-lived single consumer then acquires and imports
nothing → spurious race, annotated "as if synchronized via sleep." This matches the queue author's own
best guess and explains why it's producer↔consumer-only, rare/timing-dependent, and PR-independent.

On PR #106801 ("Try to do something about TSAN error") — not a good solution

The PR (by the queue's author, self-described "desperate hack") adds a second slot.pos.load(acquire)

  • std::abort() in both tryPush/tryPop. Problems:
  1. Won't fix it. It re-acquires an atomic already acquired 3 lines earlier, from the same thread;
    it does not recreate the lost cross-thread producer→consumer edge (and won't survive thread-slot
    recycling either).
  2. Crash + cost on the hot path in every build. Unconditional std::abort() (no #ifdef THREAD_SANITIZER, no chassert) + an extra atomic load on Keeper's hottest dispatch path. Converts
    a benign/non-existent condition into a hard Keeper crash, on a primitive built for max throughput.
  3. Logically dead. Between the CAS and the re-load, only this thread can advance slot.pos, so the
    check is a tautology that can fire only if the (proven-correct) memory model is broken.

Recommended fix

A suppression, not a runtime hack (infra confirmed: tests/tsan_ignorelist.txt, wired at
cmake/sanitize.cmake:94):

[thread]
src:*/Common/NonblockingBoundedQueue.h

Use src: (not fun:) because tryPush/tryPop are templated/inlined. Zero runtime cost, no crash;
downside is it blinds TSan to future genuine misuse — acceptable for a proven leaf primitive, ideally
paired with the unit tests the queue currently lacks (SPSC/MPSC/MPMC, empty/full, wrap, move-only).
If a fix to TSan's view is wanted instead of a suppression, use __tsan_acquire/__tsan_release
annotations guarded by #if defined(THREAD_SANITIZER) (no release-build cost) — but validate against
the actual failing job, as they may not survive thread recycling. Never leave an unconditional
std::abort() on the release hot path; a debug-only chassert is the most a runtime check should be.

Caveats

Memory-model and call-site verdicts are proven from source. The exact TSan lost-edge trigger
(thread-slot recycling vs sync-state reset) is a well-supported hypothesis, not proven — confirming it,
and validating any mitigation, requires the raw TSan artifact or a local TSan reproducer.

@al13n321

al13n321 commented Jun 9, 2026

Copy link
Copy Markdown
Contributor Author

I couldn't get claude to reproduce it though, so I don't trust the theory about what exactly goes wrong in TSAN. Still a chance the bug is in NonblockingBoundedQueue.

The idea for second load is that maybe TSAN gets confused by the compare_exchange_weak after the first load. If this doesn't work, I guess we'll have to suppress. Or should we just suppress now?

@clickhouse-gh

clickhouse-gh Bot commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.70% 84.70% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.30% 77.30% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 23/24 (95.83%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@antonio2368

Copy link
Copy Markdown
Member

In any case, our theory is that we have a false positive in TSAN. I would prefer explicitly disabling the check over doing hacks to make it work.

@al13n321

Copy link
Copy Markdown
Contributor Author

Ok, let's do #107083 instead. I don't mind because the current PR seems unlikely to work. I still think tweaking the code would be better, if it made TSAN pass, because that would provide strong additional evidence that there really isn't a data race (either because the original error was a false positive or because the change accidentally fixed a real race).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-not-for-changelog This PR should not be mentioned in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants