Skip to content

Fix memory tracker leak when a parent tracker throws MEMORY_LIMIT_EXCEEDED - #110784

Merged
azat merged 17 commits into
ClickHouse:masterfrom
seva-potapov:fix-memory-tracker-parent-limit-rollback
Aug 14, 2026
Merged

azat merged 17 commits into
ClickHouse:masterfrom
seva-potapov:fix-memory-tracker-parent-limit-rollback

Conversation

@seva-potapov

@seva-potapov seva-potapov commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

MemoryTracker::allocImpl increments amount optimistically at each level and then recurses into the parent tracker. When some ancestor (typically the total server tracker) threw MEMORY_LIMIT_EXCEEDED, only the throwing tracker reverted its own counter. All descendant trackers that had already incremented (thread, query, user) kept the rejected amount forever, together with the already-applied CurrentMetrics updates. Under sustained memory pressure this drifts MemoryTracking and the query/user accounting upward and can produce spurious MEMORY_LIMIT_EXCEEDED errors for queries that use little memory.

Now every level undoes its own increment when the allocation fails anywhere in the chain, and the side effects (peak update, memory profiler trace, metric update) are committed only after the whole parent chain has accepted the allocation. As a consequence, rejected allocations no longer emit TraceType::Memory profiler events, no longer advance the profiler step, and no longer raise peak_memory_usage. Concurrent speculative charges may still affect these values.

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 an accounting leak in memory tracking: when an allocation was rejected by a parent memory tracker (for example, the server-wide memory limit), the thread, query, and user level trackers kept the rejected amount. The error accumulated over time, inflating MemoryTracking and per-query/per-user memory usage, and could lead to spurious MEMORY_LIMIT_EXCEEDED errors.

Version info

  • Backported to: 26.7.14.29, 26.3.33.143

@seva-potapov seva-potapov added the can be tested Allows running workflows for external contributors label Jul 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2e19d3e]

Summary: ✅


AI Review

Summary

This PR correctly defers most MemoryTracker side effects until the parent chain accepts the allocation, and the permanent counter leak itself looks fixed. I would still hold the change because there is one new noexcept failure-path risk in updatePeak, and the shared-tracker false-positive window from parent-thrown exceptions is still present.

Findings

⚠️ Majors

  • [src/Common/MemoryTracker.cpp:634] updatePeak is now noexcept, but its fallback DB::tryLogCurrentException("MemoryTracker") is not: tryLogCurrentException calls getLogger(String{log_name}) in src/Common/Exception.cpp:318-324, so the recovery path can still allocate and throw. If that happens after logMemoryUsage / jemalloc flushing already failed, the second exception escapes the noexcept function and turns this handled path into std::terminate. Wrap the fallback logger in its own swallow-all try/catch, or switch to a reporting path that is actually non-throwing.
  • [src/Common/MemoryTracker.cpp:434-472] [dismissed by author -- https://github.com/Fix memory tracker leak when a parent tracker throws MEMORY_LIMIT_EXCEEDED #110784#discussion_r3755283058] The rejected charge is still visible on shared User / Process trackers until the ancestor finishes formatting and throwing MEMORY_LIMIT_EXCEEDED, because the rollback only runs in the caller-side catch. A concurrent allocation can still observe those phantom bytes and fail its own local hard-limit check even though the committed usage never crossed the limit. I still consider this real because the current code path publishes the speculative increment before the rollback point, so the PR does not fully eliminate the spurious-limit window it describes.
Final Verdict

Needs changes before merge.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 81.20% 86.70% +5.50%
Functions 91.40% 92.00% +0.60%
Branches 73.10% 79.10% +6.00%

Changed lines: Changed C/C++ lines covered: 228/230 (99.13%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 17, 2026
@seva-potapov
seva-potapov requested a review from azat July 17, 2026 13:17
@azat azat self-assigned this Jul 17, 2026
Comment thread src/Common/MemoryTracker.cpp Resolved
Comment thread src/Common/MemoryTracker.cpp Resolved
@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.60% 78.60% +0.00%

Changed lines: Changed C/C++ lines covered: 207/211 (98.10%) · Uncovered code

Full report · Diff report

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

Thanks, good catch. Sadly, but this is indeed a problem. Please take a look at the comments.

Comment thread src/Common/MemoryTracker.cpp Resolved
Comment thread src/Common/MemoryTracker.cpp Resolved
Comment thread src/Common/MemoryTracker.cpp Resolved
Comment thread src/Common/MemoryTracker.cpp Resolved
Comment thread src/Common/MemoryTracker.cpp Resolved
Comment thread src/Common/MemoryTracker.cpp Resolved
Comment thread src/Common/MemoryTracker.cpp Resolved
Comment thread src/Common/MemoryTracker.cpp Resolved
@seva-potapov
seva-potapov requested a review from azat August 11, 2026 02:23
Comment thread src/Common/MemoryTracker.cpp Resolved
Comment thread src/Common/MemoryTracker.cpp Resolved

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

Looks way cleaner now, thanks. Take a look at some comments

Comment thread src/Common/MemoryTracker.cpp Resolved
Comment thread src/Common/MemoryTracker.cpp Resolved
Comment thread src/Common/MemoryTracker.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2e19d3ef2 with master a3f55f041 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 692.20 MiB 689.17 MiB -3.04 MiB (-0.44%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

364 translation units recompiled, 3347 s compile time in total, 364 of them have a recent master baseline.

Job report

…parent-limit-rollback

# Conflicts:
#	src/Common/MemoryTracker.cpp
@seva-potapov
seva-potapov requested a review from azat August 14, 2026 06:41
@azat
azat added this pull request to the merge queue Aug 14, 2026
Merged via the queue into ClickHouse:master with commit 9b26803 Aug 14, 2026
357 of 358 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 14, 2026
@rschu1ze

Copy link
Copy Markdown
Member

@seva-potapov @azat Is it possible to backport to 26.2 as well? If yes, please add label v26.2-must-backport.

@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 23, 2026
PedroTadim added a commit that referenced this pull request Sep 24, 2026
Backport #110784 to 26.7: Fix memory tracker leak when a parent tracker throws MEMORY_LIMIT_EXCEEDED
robot-clickhouse added a commit that referenced this pull request Sep 24, 2026
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 24, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 25, 2026
…rent tracker throws MEMORY_LIMIT_EXCEEDED
PedroTadim added a commit that referenced this pull request Sep 25, 2026
Backport #110784 to 26.3: Fix memory tracker leak when a parent tracker throws MEMORY_LIMIT_EXCEEDED
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-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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants