Repository navigation
Bound untracked memory per-CPU to avoid overcommit and OOMs - #106055
Conversation
|
Workflow [PR], commit [fad69b8] Summary: ✅
AI ReviewSummaryThis PR adds a process-wide per-CPU budget for deferred Missing context / blind spots
Findings
Final VerdictStatus: Minimum required action: fix or explicitly accept the remaining blocker-level restore risk from the existing review thread; no new inline findings were added in this run. |
359d2e9 to
b4bca3f
Compare
b4bca3f to
d935181
Compare
Ergus
left a comment
There was a problem hiding this comment.
This is labelled "Performance Improvement" but the primary goal is OOM prevention... a correctness/safety fix.
So I think this is an Improvement,
It is marked as so to run performance tests, and in some sense "OOM prevention" can be "performance improvement" |
|
@Ergus I do not like current implementation, will keep it as draft for now, and ping you/undraft once it will be ready |
|
📊 Cloud Performance Report 🟢 AI verdict: This PR rewrites the per-allocation memory-tracker hot path (CurrentMemoryTracker alloc/free), which every query exercises, adding a batched per-CPU budget check and caching the memory-sampling config so the path no longer re-resolves it on each allocation. Both flagged improvements are allocation-heavy ClickBench queries — Q4 at -15.5% and Q15 at -20.5% — so faster alloc/free is a credible cause, not noise. Both deltas are large and consistent across the two tests, and they land squarely on the code this change touches, so the improvement verdicts stand. clickbench🟢 2 improved Flagged queries (2 of 43)
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
|
|
@Ergus now it should be better, it uses reservation on per-cpu counters instead |
b81c6a0 to
0c3d87e
Compare
0c3d87e to
f09ba51
Compare
f09ba51 to
77ee5d8
Compare
| } | ||
| catch (...) | ||
| { | ||
| current_thread->untracked_memory += previous_untracked_memory; |
There was a problem hiding this comment.
When this flush throws, exception construction runs under MemoryTrackerBlockerInThread(Global); MemoryTracker::allocImpl installs that blocker before formatting MEMORY_LIMIT_EXCEEDED because the formatting itself can allocate. Those allocations can change current_thread->untracked_memory_blocker_level to Global before this catch runs. Adding previous_untracked_memory back without first restoring/separating the blocker level mixes the query's previously deferred bytes into the Global-blocked bucket. A later flush then calls adjustWithUntrackedMemory under the Global blocker and skips the Thread/User/Process trackers, so a query that catches MEMORY_LIMIT_EXCEEDED can keep those live bytes outside its query/user limits.
Please flush any bytes accumulated under the exception's blocker level, then restore the original blocker level together with previous_untracked_memory and previous_per_cpu (or save/restore the whole untracked-memory state).
There was a problem hiding this comment.
This is existing bug, please do not report such, only new that this PR introduces. I will address this later,
3430ad4 to
ae6e0e8
Compare
Threads defer (de)allocations in a thread-local untracked_memory and flush to the
global MemoryTracker only past max_untracked_memory, so it undercounts by up to
nthreads * max_untracked_memory — tens of GiB with thousands of threads, enough to
overshoot max_server_memory_usage and OOM.
Bound it per-CPU instead. Each CPU keeps two counters, allocated (>= 0) and freed
(<= 0); a thread folds its untracked_memory into the counter for its sign, batched by
per_cpu_untracked_memory_thread_buffer (32 KiB), and must flush once a counter leaves
[-max_per_cpu_untracked_memory, max_per_cpu_untracked_memory]. The deferred total is
then bounded by ncpu * max_per_cpu_untracked_memory regardless of thread count, parked
threads included. The two sides are independent so a deferred free cannot admit a
deferred allocation (which the free would then strand untracked on its own flush).
max_per_cpu_untracked_memory (default 8 MiB, 0 disables) is a new server setting;
max_untracked_memory stays per-thread. Linux only (needs sched_getcpu).
v2: reimplemented — v1 bounded via sum % SLICE on one global counter, which cannot
bound the per-CPU deferred bytes; replaced with the PerCPUMemory class.
v3: two counters instead of one signed net — a signed net let a deferred free cancel
a deferred allocation, stranding it untracked when the free flushed.
v4: restore the per-CPU contribution unconditionally on a failed flush; a gated
re-reserve could drop still-live bytes if another thread took the budget meanwhile.
v5: release the per-CPU contribution only in the caller, not in reserve().
v6: Rename PerCPUMemory::reserve to sync (it sets an absolute value, not a reservation)
v7: Rename net_per_cpu member to slots
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…flush A per-CPU flush hands the MemoryTracker a batch whose size need not match any single allocation and may fall outside [memory_profiler_sample_min_allocation_size, memory_profiler_sample_max_allocation_size], yet the sample is written with the original size. Flush with _sample_probability=0 and sample the original size via getEffectiveSampleProbability, as the non-flush path already does. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Raise the limits/configs the early-limit, async-insert and distributed-constraint tests pinned above the new per-CPU slack; make 04117 deterministic. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…nfig changes getEffectiveSampleProbability reads only ThreadStatus's cached sample config, so it goes stale whenever the effective tracker parent/config changes without a refresh: threads parented to total_memory_tracker with no query context, the initiating thread after ProcessList::insert applies the query's SETTINGS (e.g. memory_profiler_sample_probability in the SQL SETTINGS clause), detach reparenting back to total_memory_tracker, the main thread after the server applies total_memory_tracker_sample_probability (set after MainThreadStatus was created), and MemoryTrackerSwitcher scopes — each kept a stale value and stopped emitting MemorySample. Re-resolve the cache at every such point: ThreadStatus construction, applyGlobalSettings (every attach), applyQuerySettings, ProcessList::insert, detachFromGroup, MemoryTrackerSwitcher (save/re-resolve/restore), and Server after the total-sampler setters. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
ae6e0e8 to
fad69b8
Compare
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 380/385 (98.70%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 13 line(s) · Uncovered code |
Bound untracked memory per-CPU to avoid overcommit and OOMs
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Bound untracked memory per-CPU to avoid overcommit and OOMs (limits are configured with
max_per_cpu_untracked_memoryandper_cpu_untracked_memory_thread_bufferserver settings)Previously ClickHouse works memory overcommit was
max_untracked_memory*threads, which may in theory lead to ±40GiB of overcommited memory in a worst case scenario and 10K threads and default settingsBy bounding maximum untracked memory to
ncpu*max_per_cpu_untracked_memorywe can avoid this massive memory overcommit, and also with defaultmax_server_memory_usage_to_ram_ratio=0.9, all this memory is already reserved, so for now per-cpu memory is not reserved explicitly.There is also very small (32Ki by default) thread local limit, so possible overcommit is
max(nthreads*per_cpu_untracked_memory_thread_buffer, ncpu*max_per_cpu_untracked_memory), which should be covered by defaultmax_server_memory_usage_to_ram_ratioalready.Note, librseq gives ±1% (in the best case), and complexity does not worth it
Version info
26.7.1.157(included in26.7and later)