Skip to content

Fix the global memory tracker going negative after a refused allocation over max_server_memory_usage - #127054

Closed
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:fix-global-memory-tracker-pending-charge
Closed

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:fix-global-memory-tracker-pending-charge

Conversation

@groeneai

@groeneai groeneai commented Oct 20, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #118094
Related: #126176

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 to be freed, 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.9.19.9 with memory_worker_correct_memory_tracker = 1, a query whose 4.47 GiB allocation max_server_memory_usage refuses after an overcommit wait leaves the global memory tracker at about -4.2 GiB (3 of 3 runs), so until the next memory worker tick the server limit admits allocations it should refuse.

The global tracker charges an allocation before checking the limit and holds the charge while it waits for memory to be freed. Each memory worker tick replaces amount and rss with a measurement, which cannot contain that charge, so the refusal then subtracts the allocation from counters that no longer hold it.

The global tracker now counts the charges it is still deciding on, and updateAllocated and updateRSS keep them on top of the measurement (the metric and the peak keep the measured value); a refusal's rollback and a correction take one mutex. The waiting charge thus stays in the tracker, and the overcommit tracker stops the query it picked, as it does with the correction off.

CI: refused 64 GiB allocations drove the tracker to -500.84 GiB, then the server was OOM-killed at 43 GiB RSS under a 40 GiB limit (AST fuzzer on #123890).

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

A worker tick within a few instructions of the charge can still miss that allocation until the next correction; closing that needs more atomics on every global allocation.


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

groeneai and others added 2 commits October 20, 2026 22:13
…acker corrections

The global memory tracker charges an allocation before comparing it with
the hard limit, and keeps the charge while it shrinks the caches and waits
in the overcommit tracker (up to memory_usage_overcommit_max_wait_microseconds)
for another query to free memory. Each tick of the memory worker replaces
`rss` (always) and `amount` (every tick with memory_worker_correct_memory_tracker,
the default since ClickHouse#118094) with a measurement, which cannot contain a charge
that has no allocation behind it yet. When the allocation is then refused, the
rollback subtracts it from counters that no longer hold it, and the tracker
stays that far below the truth until the next tick, so the server limit
admits allocations it should refuse. In an AST fuzzer run refused 64 GiB
allocations drove the tracker to -500 GiB and the server was OOM-killed at
43 GiB RSS under a 40 GiB limit.

The global tracker now counts the charges inside its over-limit branch, and
updateAllocated and updateRSS add them to the measurement. The metric and
the peak keep the measured value: a pending charge is added to the metric
only when it is committed, and a refused one must never become a peak.
During an overcommit wait the charge now also survives the ticks, so the
overcommit tracker stops the query it picked, as it did with the correction
off. A refusal rolls its charge back and leaves the pending count under the
mutex that updateAllocated and updateRSS hold while they read the count and
replace the counter, so a correction cannot bring a rolled-back charge back.
The count is published with release and read with acquire, so a correction
that sees a charge also sees it in the counters it replaces.

A worker tick within a few instructions of the charge can still miss that
allocation until the next correction; closing that needs more atomics on
every global allocation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Move the pre-existing uncorrected_amount carry comment back above the line it explains.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (5 rounds, final on 3fae7eb: 0 open findings)
  • ❌ pending-snapshot-race (a correction logging between the pending load and the counter replace): AGREE, fixed; nothing runs between the load and the exchange, and the log prints the exchanged value.
  • ❌ pending-snapshot-mode0 (refusal rollback vs correction race, permanent with memory_worker_correct_memory_tracker = 0): AGREE, fixed; the rollback and the correction's load+replace take one mutex (refusal path and worker tick only).
  • ❌ batched-pending-realized: DISAGREE. The extra count is the batch's already-allocated untracked bytes (at most max_untracked_memory), lasts one correction, and master already double-counts untracked bytes after each correction; refusals stay exact.
  • ⚠️ refused charge released only at unwind time: AGREE, fixed; released right after the rollback.
  • ⚠️ pending-publication-order (on a weakly ordered CPU a correction could see the pending charge before the charge itself): AGREE, fixed; published with release, read with acquire.
  • ⚠️ metric-peak-unasserted, correction-noop-liveness, peak-lower-bound-liveness: AGREE, fixed; the tests assert the metric, the peak (read inside the simulated tick) and an offset measurement, and each assertion was shown to fail under the matching mutation.
  • 💡 refusal test order dependence when run alone: AGREE, fixed with a warm-up refusal.

@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 every run; a server with a 3 GB limit and an overcommit wait went to about -4.2 GiB in 3 of 3 runs, also on the official 26.9.19.9 with the correction on.
b Root cause explained? A memory worker tick during the over-limit decision replaces amount/rss by a measurement without the pending charge, so the refusal's rollback underflows both by the allocation size.
c Fix matches root cause? Yes: the correction keeps the pending charges; the charge-then-wait order of allocImpl is unchanged.
d Test intent preserved / new tests added? Two new gtests next to GlobalLimitFailureRollsBackAmountAndRSS (refused and admitted allocation); no existing test changed.
e Both directions demonstrated? Master: both new tests fail by 60 MiB on amount and rss; fix: 18/18 pass (20 shuffled repeats). Server repro: negative 3/3 vs none 3/3.
f Fix is general across code paths? Every replacement of the global counters goes through updateAllocated/updateRSS (all worker call conditions and AsynchronousMetrics); trackers below the global one are never corrected.
g Fix generalizes across inputs (params/datatypes/wrappers)? Refusal and admission tested; correction on and off measured end to end; a zero-size check adds nothing. Type wrappers do not apply.
h Backward compatible? (maintainer-approved exception only) Yes: no setting or format change. During an overcommit wait the charge stays in the tracker, as it does with the correction off.
i Invariants and contracts preserved? MemoryTracking and the peak never include a refused charge (both asserted; a mutation to either fails the test); the hot cache line is unchanged; the rollback and the correction are serialized by correction_mutex (taken only on the refusal path and in updateAllocated/updateRSS), so a correction cannot bring a rolled-back charge back; otherwise the pending charge is released at block exit.

Session id: cron:clickhouse-impl-slot-6:20261020-220800

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @azat @antonio2368, could you review this and add the can be tested label so CI runs? With memory_worker_correct_memory_tracker on, a memory worker tick during an overcommit wait replaced the global tracker's amount/rss with a measurement that does not contain the allocation still being decided, so its refusal drove the tracker negative; the tracker now keeps such pending charges on top of the measurement.

@clickhouse-gh

clickhouse-gh Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f083d42]

Summary: ✅


AI Review

Summary

The PR preserves pending global allocation charges across memory-worker corrections and serializes refusal rollback with those corrections, preventing the allocation-sized undercount after an overcommit wait. No actionable findings in head f083d42021b4c587e58c1cb5b994d2e1397fdb34.

Missing context / blind spots
  • ⚠️ The added regression tests were inspected but not independently executed here because this checkout has no configured build. The author reports deterministic failures before the fix and successful repeated runs afterward; the fetched dedicated unit-test CI reports currently contain no test results. Completed unit-test results would independently confirm that validation.
Final Verdict

Status: ✅ Approve.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-memory Memory management infrastructure: allocators (Allocator, Arena, PODArray), memory tracking, memor... labels Oct 20, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 21, 2026
@azat azat self-assigned this Oct 22, 2026

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

This increases the complexity and does not fixes the issue 100%, there is alternative that allows to avoid mutex but, it is also not 100%

And this should be taken with care, since MemoryTracker can be a bottleneck

@groeneai

Copy link
Copy Markdown
Collaborator Author

Agreed. The new atomic and the mutex are only on the over-limit branch of allocImpl and in updateAllocated/updateRSS (the in-limit path and free are unchanged), but under memory pressure many threads take that branch at once.

Which do you prefer?

  1. Keep pending_amount and drop the mutex. A refusal that races a correction can then leave the tracker too high by that allocation's size until the next correction.
  2. Your mutex-free alternative. Which one do you mean? I will switch the PR to it.
  3. Close this PR.

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.

3 participants