Skip to content

Fix the global memory tracker going negative while max_server_memory_usage refuses an allocation - #131625

Open
groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:fix-memory-tracker-correction-keeps-refused-charges
Open

groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:fix-memory-tracker-correction-keeps-refused-charges

Conversation

@groeneai

@groeneai groeneai commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #127054
Related: #118094

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):

Fixed the global memory tracker going negative by the size of an allocation that max_server_memory_usage refused after waiting for memory, when memory_worker_correct_memory_tracker is enabled (the default since 26.10). While it was negative, the server memory limit admitted allocations it should have refused, and the server could be killed by the OOM killer.

Description

On 26.10.2.103-stable, a query whose 4.47 GiB allocation is refused after a 2 s overcommit wait under a 2.79 GiB max_server_memory_usage leaves the global memory tracker at -4.2 GiB (3 of 3 runs), and until the next memory worker tick the limit admits allocations past it.

The tracker charges an allocation before deciding on it, and the decision can take seconds (overcommit wait, jemalloc profile flush, cache resize). Each memory worker tick replaces rss, and with the correction on also amount, with a measurement, which cannot contain that charge, so the refusal subtracts the allocation from counters that no longer hold it.

refusing_amount (#127252) already counts these allocations. updateAllocated and updateRSS now add it to the measurement; the metric and the peak keep the measured value. It is registered before the profile flush and released with the rollback. No new member, no lock: this replaces #127054.

CI: the tracker read -500.84 GiB, -63.14 GiB, and a 64 GiB allocation was admitted under a 40 GiB limit before the cgroup killed the server (#123890, #99639, #131551).

Validation: two gtests run a worker correction inside the over-limit decision, for a refused and an admitted allocation; on master both fail by exactly the allocation size. With the fix, the end-to-end repro shows no negative correction, also with the correction off.

A correction within a few instructions of the charge or the rollback can still miss or keep that allocation once, until the next correction.


Workflow [PR]
Sync PR [sync-upstream/pr/131625]

…tracker

`MemoryTracker::allocImpl` charges an allocation to the global `amount` and
`rss` before deciding on it. Over the limit, the decision can take long: the
jemalloc profile flush, the page and columns cache resize, and the overcommit
wait (up to `memory_usage_overcommit_max_wait_microseconds`, 5 s by default).
Meanwhile every `MemoryWorker` tick replaces `rss` with a measurement, and
`amount` too with `memory_worker_correct_memory_tracker` (the default since
ClickHouse#118094). A measurement cannot contain the pending charge, because the tracker
is called before the allocation, so the tick erases it, and the refusal then
subtracts the size from counters that no longer hold it. Both stay negative by
the size of the refused allocation until the next tick, and meanwhile
`max_server_memory_usage` admits allocations it should refuse. In the AST
fuzzer the tracker read -500 GiB and the cgroup killed the server.

`refusing_amount` (ClickHouse#127252) already counts these allocations for the peak. The
correction now adds it to the measurement for `amount` and `rss`; the
`MemoryTracking` metric and the peak keep the measurement. The allocation is
registered before the profile flush, not after it, and released together with
the rollback instead of at unwind. The registration and the releases use
release order and the correction loads with acquire, so a correction that sees
a registered size also sees that thread's charge, and one that sees a release
also sees its rollback.

A correction within a few instructions of the charge or the rollback can still
miss or keep that allocation once, until the next correction.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (1 round on 7ca0a8c: 0 open findings)
  • ⚠️ boundary-liveness (the gtests do not cover the registration before the jemalloc profile flush, or the release right after the rollback): DISAGREE. Neither window (mallctl reads, flushProfile and logging; the exception build) has a call a test can hook without a test-only hook in the over-limit branch of allocImpl; both placements can be checked by reading the diff, and the CI report for Auto-enable uncompressed cache for MergeTree reads #99639 shows the flush case.
  • 💡 With memory_worker_correct_memory_tracker = 0, a correction landing between the load of refusing_amount and a rollback can keep the refused size in amount until the next correction (in that mode, only when amount is negative): noted, not changed, disclosed in the PR body; closing it needs the lock that Fix the global memory tracker going negative after a refused allocation over max_server_memory_usage #127054 used, and the over-count only refuses more.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The two new gtests fail on master on every run by exactly the allocation size (60 MiB); end to end, a 4.47 GiB allocation refused after a 2 s overcommit wait drives the tracker to -4.2 GiB 3 of 3 times on master and on 26.10.2.103-stable.
b Root cause explained? The global tracker charges an allocation before deciding on it; a memory worker tick during the decision replaces amount/rss with a measurement that cannot contain the charge, so the refusal's rollback leaves both counters the allocation size below the truth.
c Fix matches root cause? Yes. The correction keeps the charges being refused (refusing_amount), at the only code that replaces the counters; no limit or refusal-site change.
d Test intent preserved / new tests added? Two gtests in gtest_memory_tracker.cpp run a correction inside the over-limit decision, for a refused and an admitted allocation; existing tests unchanged. SQL cannot place a worker tick inside one allocation's decision.
e Both directions demonstrated? Master: both new tests fail only on get()/getRSS() by 60 MiB; fix: 18/18, 50 shuffled repeats green. Mutations of each changed line redden only their own assertion.
f Fix is general across code paths? Both correction functions and all their callers; the profile-flush window, the page/columns cache resize and the overcommit wait are all inside the registered span; the admitted path is released before commit, so nothing is counted twice.
g Fix generalizes across inputs (params/datatypes/wrappers)? Both correction modes (end to end with the correction on and off), flush on and off, zero-size checks register nothing.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; a waiting refused request now stays counted across ticks, as it already did between ticks and with the correction off.
i Invariants and contracts preserved? Every charge not yet decided survives a correction and nothing else is added; the metric and the peak keep the measured value; the scope guard releases on every exit.

Session id: cron:clickhouse-impl-slot-41:20261114-114102

@clickhouse-gh

clickhouse-gh Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7ca0a8c]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR preserves pending refused allocations when the memory worker corrects the global counters. The refusal path is improved, but successful admission releases the pending charge before potentially blocking allocation bookkeeping finishes, leaving a path to the same undercount and memory-limit bypass.

Findings

❌ Blockers

  • src/Common/MemoryTracker.cpp:436: The new guard ends before commitAllocation, whose updatePeak can log and synchronously flush a jemalloc profile before the actual allocation. A correction there sees no pending charge and overwrites the counters without it. A later free or allocator-failure rollback can make them negative. For example: 8 GiB initially, a 10 GiB limit, a 9 GiB request, and 7 GiB evicted leave 10 GiB charged; a correction to a 1 GiB measurement during peak reporting followed by release of the request leaves -8 GiB. Retain pending accounting through the slow successful bookkeeping, including the equivalent ordinary successful-allocation path, or explicitly track that remaining pre-existing path in a linked issue.
Tests
  • ⚠️ Both added tests correct the tracker inside autoResize, before the guard ends. Add a focused regression that performs a correction during successful allocation peak reporting and verifies the counters after release.
Missing context / blind spots
  • ⚠️ The finding is based on the source and a concrete interleaving, without an independent runtime reproduction. This checkout has no configured build or test binary, and the CI unit-test report has no completed results yet. The focused regression above would close this gap.
Final Verdict

❌ Block — Preserve the pending charge through successful allocation bookkeeping and cover the correction during peak reporting.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default can be tested Allows running workflows for external contributors comp-memory Memory management infrastructure: allocators (Allocator, Arena, PODArray), memory tracking, memor... labels Nov 14, 2026
Int64 refusing_size = can_refuse ? size : 0;
if (refusing_size)
refusing_amount.fetch_add(refusing_size, std::memory_order_release);
SCOPE_EXIT({

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.

[Blocker] Keep an admitted charge registered through commitAllocation.

This guard runs when the over-limit block ends, before commitAllocation at line 601. If a cache resize admits the allocation, commitAllocation can still call updatePeak, which logs and can synchronously flush a jemalloc profile. The actual allocator has not run yet, but refusing_amount no longer contains its charge. A worker correction during that work therefore erases the charge again; a subsequent free or allocator-failure rollback subtracts bytes the counters no longer contain, recreating the negative tracker and memory-limit bypass.

For example, start with an 8 GiB tracker/peak and a 10 GiB limit: a 9 GiB request can be admitted after evicting 7 GiB of cache, leaving a 10 GiB charge and raising the peak. If a correction in that peak logging/profile flush measures 1 GiB, it replaces the charge with 1 GiB; releasing the 9 GiB request then leaves -8 GiB, ignoring small accounting noise. This window includes blocking work, beyond the short charge/rollback races disclosed in the description.

Keep the pending accounting alive through this work, retaining the explicit release after rejection rollback. Please add a regression that corrects the tracker from the successful path's peak logging/profile flush; the existing admission test corrects only inside autoResize, before this guard runs.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Not changed: every successful allocation, in-limit or not, runs this bookkeeping with its charge unregistered, on master too (the updatePeak profile flush only when jemalloc_flush_profile_interval_bytes is set, 0 by default), and a correction there undercounts it until the next correction, while a refused allocation is rolled back right after a wait of up to 5 s, which is what took the tracker to -500 GiB in CI. Keeping every successful allocation registered until the allocator runs would add two atomic operations on a shared counter to each allocation, so I leave that out of this PR.

@clickhouse-gh

clickhouse-gh Bot commented Nov 14, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7ca0a8c6b with master 1b7851acb (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.57, programs/clickhouse-keeper ×0.63 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 6.1 s 11.1 s +7.7 s (+220%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.5 s 7.2 s +5.2 s (+259%)
Compile time of recompiled translation units

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

Job report

This branch has not been deployed

No deployments
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 comp-memory Memory management infrastructure: allocators (Allocator, Arena, PODArray), memory tracking, memor... pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant