Skip to content

Fix data races in profile events and memory tracker - #112466

Merged
mstetsyuk merged 4 commits into
masterfrom
profile-events-parent-release-acquire
Aug 12, 2026
Merged

mstetsyuk merged 4 commits into
masterfrom
profile-events-parent-release-acquire

Conversation

@mstetsyuk

@mstetsyuk mstetsyuk commented Jul 29, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Critical Bug Fix (crash, data loss, RBAC)

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

Fix data races in profile events and memory tracker.

Version info

  • Merged into: 26.8.1.1253 (included in 26.8 and later)
  • Backported to: 26.7.4.23

@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [62855e8]

Summary: ❌

job_name test_name status info comment
Bugfix validation (unit tests) FAIL
Stress test (amd_tsan) FAIL
Hung check failed, possible deadlock found FAIL cidb
Stress test (arm_release) FAIL
Hung check failed, possible deadlock found FAIL cidb
Stress test (arm_debug) FAIL
Hung check failed, possible deadlock found FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL

AI Review

Summary

This PR switches the MemoryTracker and ProfileEvents::Counters parent links to acquire-release publication and adds regression tests, but the current head still leaves one ProfileEvents publication race unfixed and still has callers that publish a MemoryTracker before its limits are initialized. Because the new contract is not upheld end to end, I do not think this is ready to merge.

Findings

❌ Blockers

  • [src/Common/ProfileEvents.cpp:1856-1868, 1984-1985] The should_trace_array publication path still uses relaxed loads and relaxed failed-CAS ordering, so increment can dereference the tracing array without synchronizing with the thread that allocated it. That leaves the same ProfileEvents::Counters data race that this PR says it fixes. Suggested fix: make the dereferencing loads acquire and use acquire (or stronger) on the failed compare_exchange_strong path before reusing expected.

⚠️ Majors

  • [src/Common/MemoryTracker.h:92-97] setParent is documented here as the publication barrier, but ThreadStatus::attachToGroupImpl still publishes memory_tracker at src/Interpreters/ThreadStatusExt.cpp:382 before applyQuerySettings configures thread_group->memory_tracker at src/Interpreters/ThreadStatusExt.cpp:358. There are allocations in between (query_id = query_context_ptr->getCurrentQueryId() at src/Interpreters/ThreadStatusExt.cpp:347 is enough once it exceeds the untracked-memory threshold), so max_memory_usage can still be bypassed during attach. Suggested fix: configure the group tracker before memory_tracker.setParent(&thread_group->memory_tracker), or keep allocations blocked until configureMemoryTrackerFromSettings has run.
  • [src/Common/MemoryTracker.cpp:793] [dismissed by author -- https://github.com/Fix data races in profile events and memory tracker #112466#discussion_r3676663435] ProcessList::insert still does thread_group->memory_tracker.setParent(&user_process_list.user_memory_tracker) at src/Interpreters/ProcessList.cpp:305, and only sets max_memory_usage_for_user / memory_overcommit_ratio_denominator_for_user at src/Interpreters/ProcessList.cpp:396-397. Another thread in the same group can still charge allocations through a freshly published user tracker whose limits are zero, so user-scoped memory limits are not enforced for that window. Suggested fix: finish configuring user_memory_tracker before publishing it to the thread group.
Final Verdict

❌ Changes requested.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.00% 79.10% +0.10%

Changed lines: Changed C/C++ lines covered: 79/80 (98.75%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels Jul 29, 2026
@mstetsyuk

mstetsyuk commented Jul 29, 2026 •

Copy link
Copy Markdown
Member Author

MemoryTracker::parent loads/stores require acquire-release:

  1. Thread A constructs MemoryTracker object and attaches MemoryTracker pointer (e.g. ProcessList::insert where the user's MemoryTracker is constructed right before calling setParent).
  2. Thread B (e.g. another thread in the thread group) traverses the chain and dereferences each pointer.
  3. If Thread B sees a pointer, it should be guaranteed to see the object's memory without data races. Hence, we need the Thread A's pointer store to synchronize-with the Thread B's pointer load.

Exactly the same applies to ProfileEvents::Counters.

Thread A code:

auto user_process_list_it = user_to_queries.find(client_info.current_user);
if (user_process_list_it == user_to_queries.end())
{
user_process_list_it = user_to_queries.emplace(std::piecewise_construct,
std::forward_as_tuple(client_info.current_user),
std::forward_as_tuple(query_context->getGlobalContext(), this)).first;
}
ProcessListForUser & user_process_list = user_process_list_it->second;
/// Actualize thread group info
CurrentThread::attachQueryForLog(query_);
auto thread_group = CurrentThread::getGroup();
if (thread_group)
{
thread_group->performance_counters.setUserCounters(&user_process_list.user_performance_counters);
thread_group->memory_tracker.setParent(&user_process_list.user_memory_tracker);
.

Thread B can be:

  1. Dictionary (ExternalLoader::LoadingDispatcher::loadImpl) waiting for the query to finish, that QueryProfilerReal landed on and incremented profile events. Sanitizer report.
  2. AsynchronousInsertQueue::processData that increments profile events. Sanitizer report.

Memory tracker is a very hot path, so I evaluated the performance impact. Acquire-release costs 0 vs relaxed on x86 (exact same instructions) and should not cost much on ARM in our use case, according to Claude's analysis: https://pastila.clickhouse.com/?0017eb48/ff68c429ee04b7443f452a37e70d9c58#EnrE2yCkbifettLX+SLeDw==GCM.

Added a performance label to confirm there are no degradations.

@mstetsyuk mstetsyuk added performance pr-performance Pull request with some performance improvements labels Jul 29, 2026
Comment thread src/Common/MemoryTracker.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 37 queries analysed

This PR is a correctness-only change: it upgrades the parent-pointer atomics in the memory tracker and profile-event counters from relaxed to acquire/release ordering, plus adds concurrency tests. That path runs on every allocation and counter increment, but the ordering change is effectively runtime-neutral, so it cannot plausibly produce the isolated -13.7% improvement flagged on clickbench Q17 — I downgraded that to not_sure as run-to-run variance. Q18's -7.6% correctly stayed no_change inside master's normal variance band. No real performance shift is attributable to this diff.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 17 not_sure 556 480 -13.7% <0.0001 memory: This PR only hardens the memory-tracker/profile-event parent-pointer atomics from relaxed to acquire/release ordering. That change is runtime-neutral (if anything slightly costlier), so a targeted -13.7% speedup on Q17 alone is not a plausible effect of the diff.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: f921d839-bfc6-4c9a-b490-58e471261276
  • MIRAI run: f16f78da-98bb-415c-9bd5-9e230ebfff8c
  • PR check IDs:
    • clickbench_789695_1786477312
    • clickbench_789701_1786477310
    • clickbench_789717_1786477311
    • tpch_adapted_1_official_789725_1786477310
    • tpch_adapted_1_official_789751_1786477310
    • tpch_adapted_1_official_789765_1786477310

@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.40% 86.40% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.50% 78.60% +0.10%

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

Full report · Diff report

@mstetsyuk
mstetsyuk requested a review from Michicosun July 30, 2026 09:42
@Michicosun Michicosun self-assigned this Jul 31, 2026

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

LGTM, interesting that on a hot path (increment) seq-cst was left.

@mstetsyuk

Copy link
Copy Markdown
Member Author

LGTM, interesting that on a hot path (increment) seq-cst was left.

You're right, I overlooked that, fixed now.

Comment thread src/Common/ProfileEvents.cpp Resolved
@mstetsyuk
mstetsyuk enabled auto-merge August 6, 2026 13:37
@mstetsyuk
mstetsyuk added this pull request to the merge queue Aug 6, 2026
@mstetsyuk
mstetsyuk removed this pull request from the merge queue due to a manual request Aug 6, 2026
Comment thread src/Common/MemoryTracker.h Resolved
@mstetsyuk

mstetsyuk commented Aug 12, 2026 •

Copy link
Copy Markdown
Member Author

Bugfix validation is run against a UB + Address sanitizer build - which cannot catch this bug. I checked manually, TSan reliably produces 50/50 red before, 50/50 green after.

@groeneai, please check other failing tests and provide a report.

@groeneai

Copy link
Copy Markdown
Collaborator

Report on the reds at 62855e8ef32af4c5e5f141cea541e6f7e96678c7. Coverage first: the praktika report has 175 leaves, 0 DROPPED, 152 OK and 18 skips that all carry a reason, so the run is genuinely covered and the 5 reds are real signal.

Check / test Verdict
Bugfix validation (unit tests) Your premise is right, and it is structural, not a build-flag accident. ci/jobs/unit_tests_bugfix_validation_job.py:53 hardcodes BUILD_TYPE = BuildTypes.AMD_ASAN_UBSAN for the before-binary, so that job has no TSan arm and cannot observe a race. Its log: touched suites ['MemoryTrackerParent', 'ProfileEvents'], 4 tests, 4 PASS on the before-binary. Note the functional and integration validators are arch-parametrized but the unit one is single-build.
Finish Workflow / new_tests_check.py Not a second failure. Its info only restates the unit validator's verdict, so it clears when that one does.
Stress test (amd_tsan) / Hung check Ambient trunk, not yours. See below.
Stress test (arm_release) / Hung check Same signature.
Stress test (arm_debug) / Hung check Same signature.

On the three hung checks: in all three, process-list Row 1 is DROP TABLE prometheus; stuck 2782 s / 3199 s / 3406 s with is_cancelled: 1, and the DROP DATABASE ... SYNC and DETACH DATABASE queries behind it are the convoy on the DDLGuard, not independent failures. That is exactly the shape of #114259.

I checked whether it is specific to your diff by pulling the hung_check.log artifact from other runs and parsing the same Row 1. It is not: 10 of 10 unrelated runs I sampled show byte-identical Row 1 DROP TABLE prometheus;, including two on plain master, with elapsed 472 s to 3335 s. Breadth over 30 days for Hung check failed, possible deadlock found: 1196 rows across 596 distinct PRs plus 155 rows across 113 master commits, spread over all 10 stress variants. Getting 3 hung stress jobs on one commit is also unremarkable: over 14 days, 7.4 percent of PR commits hit exactly 3 and 32 percent hit 2 or more.

One caveat on my own numbers, in case you try to reproduce them: CIDB's test_context_raw keeps only the last 32 KiB of that log and the process-list block is at the top, so a position(test_context_raw, 'DROP TABLE prometheus') > 0 breadth query returns zero rows and looks like the signature is unique to this PR. It is an artifact of the truncation. The artifact logs are the only reliable source here.

So the only thing on this list attributable to the PR is the unit-validator verdict, and that is the job being blind to races rather than a problem with your test. Unit tests (tsan) is green on the same head (19728 passed).

Report URLs: amd_tsan, arm_release, arm_debug.

@mstetsyuk
mstetsyuk added this pull request to the merge queue Aug 12, 2026
Merged via the queue into master with commit 012f2bd Aug 12, 2026
174 of 180 checks passed
@mstetsyuk
mstetsyuk deleted the profile-events-parent-release-acquire branch August 12, 2026 15:29
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

performance pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-critical-bugfix 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-performance Pull request with some performance improvements 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.

7 participants