Skip to content

Reduce mutex contention in PipelineExecutor::allocateCPU to mitigate TSan crash in 02124_buffer_with_type_map_long - #101060

Closed
tuanpach wants to merge 4 commits into
ClickHouse:masterfrom
tuanpach:fix-pipeline-executor-cpu-resource-contention
Closed

tuanpach wants to merge 4 commits into
ClickHouse:masterfrom
tuanpach:fix-pipeline-executor-cpu-resource-contention

Conversation

@tuanpach

@tuanpach tuanpach commented Mar 29, 2026 •

Copy link
Copy Markdown
Member

PipelineExecutor::allocateCPU called getMasterThreadResourceName() and getWorkerThreadResourceName() as two separate operations, each acquiring and releasing WorkloadEntityStorageBase::mutex. Under TSan with 10 concurrent connections (as in 02124_buffer_with_type_map_long), this contributed to a high mutex lock/unlock rate that reproducibly triggered a crash inside TSan's TraceEvent<EventUnlock> (tsan_rtl.h:745).

Two distinct crash stack traces were observed, both at the same TSan location:

  1. WorkloadEntityStorageBase::getWorkerThreadResourceName → PipelineExecutor::allocateCPU → pthread_mutex_unlock
  2. ConcurrentBoundedQueue::popImpl → condition_variable::wait_for → pthread_cond_timedwait (internal mutex release) → TCPHandler::processOrdinaryQuery

The second trace has no relation to WorkloadEntityStorageBase::mutex, which confirms that the root cause is a TSan internal bug: thr->tctx becomes null for a live, running thread under certain conditions, and TraceAcquire (inlined into TraceEvent) dereferences it without a null guard. The crash can be triggered by any mutex unlock when TSan's internal state is in this condition.

This PR is a partial mitigation. The fix has two parts:

  1. Add getCPUThreadResourceNames() to IWorkloadEntityStorage and WorkloadEntityStorageBase to fetch both resource names under a single mutex acquisition instead of two.

  2. Cache the result in Context as cpu_thread_resource_names (same pattern as ClassifierPtr classifier / getWorkloadClassifier()). CPU resource names are semantically fixed for the lifetime of a query — the workload cannot change after query start — so caching is correct. PipelineExecutor now calls query_context->getCPUThreadResourceNames() once per pipeline execution; subsequent pipelines within the same query hit the cache and never touch WorkloadEntityStorageBase::mutex again.

This reduces the rate of mutex events from the hot executor path, making the flaky test reproducibly pass, but does not eliminate the underlying TSan bug.

Crash stack traces:
https://pastila.clickhouse.com/?00a7c7eb/06f31ac959a0d293bf9ce4e3c190b405#Jf+fDAZ0EpLylxyoLMLGzw==GCM

Changelog category (leave one):

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

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

…CPU resource names per query

`PipelineExecutor::allocateCPU` called `getMasterThreadResourceName()` and
`getWorkerThreadResourceName()` as two separate operations, each acquiring and
releasing the global `WorkloadEntityStorageBase::mutex`. Under TSan with 10
concurrent connections (as in `02124_buffer_with_type_map_long`), the high
lock/unlock rate of this global mutex triggered a TSan-internal bug in
`TraceSkipGap`: when TSan's slot-recycling sets `trace_pos = 0` transiently
during a thread epoch change, a concurrent `TraceAcquire` call dereferences
`thr->tctx->trace` with `tctx == nullptr`, causing a near-NULL read segfault.

The fix has two parts:

1. Add `getCPUThreadResourceNames()` to `IWorkloadEntityStorage` and
   `WorkloadEntityStorageBase` to fetch both resource names under a single
   `mutex` acquisition instead of two.

2. Cache the result in `Context` as `cpu_thread_resource_names` (same pattern
   as `ClassifierPtr classifier` / `getWorkloadClassifier()`). CPU resource
   names are semantically fixed for the lifetime of a query — the workload
   cannot change after query start — so caching is correct. `PipelineExecutor`
   now calls `query_context->getCPUThreadResourceNames()` once per pipeline
   execution; subsequent pipelines within the same query hit the cache path and
   never touch `WorkloadEntityStorageBase::mutex` again.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c7d4369]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_llvm_coverage, 3/5) failure
test_overcommit_tracker/test.py::test_user_overcommit FAIL cidb
Stress test (arm_msan) failure
Server died FAIL cidb
MemorySanitizer: use-of-uninitialized-value (STID: 1003-326e) FAIL cidb

AI Review

Summary

This PR reduces lock contention in CPU resource lookup by introducing IWorkloadEntityStorage::getCPUThreadResourceNames and caching the pair in Context for query execution. On the current PR head, I did not find additional correctness, safety, performance, or metadata issues that require new comments beyond existing discussion.

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Mar 29, 2026
Comment thread src/Interpreters/Context.cpp Resolved
…rge` / `makeQueryContextForMutate`

When a context is copied and repurposed for a merge or mutate operation,
`classifier` was reset so a new one would be acquired for the correct workload.
However, `cpu_thread_resource_names` was not reset, so if it had been populated
before the copy it would remain stale — pairing the new classifier with CPU
resource names from the wrong workload.

Fix: reset `cpu_thread_resource_names` alongside `classifier` in both
`makeQueryContextForMerge` and `makeQueryContextForMutate`, so both caches
share identical lifetime semantics and are repopulated together on next use.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Comment thread src/Interpreters/Context.h Resolved
@clickhouse-gh

clickhouse-gh Bot commented Apr 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.00% 84.00% +0.00%
Functions 90.90% 90.90% +0.00%
Branches 76.50% 76.60% +0.10%

Changed lines: 100.00% (39/39) · Uncovered code

Full report · Diff report

@tuanpach

tuanpach commented Apr 2, 2026

Copy link
Copy Markdown
Member Author

@tuanpach tuanpach changed the title Fix flaky TSan crash in 02124_buffer_with_type_map_long by caching CPU resource names per query Reduce mutex contention in PipelineExecutor::allocateCPU to mitigate TSan crash in 02124_buffer_with_type_map_long Apr 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant