Skip to content

Bound untracked memory per-CPU to avoid overcommit and OOMs - #106055

Merged
azat merged 5 commits into
ClickHouse:masterfrom
azat:per-cpu-untracked-memory
Jun 27, 2026
Merged

azat merged 5 commits into
ClickHouse:masterfrom
azat:per-cpu-untracked-memory

Conversation

@azat

@azat azat commented May 28, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Performance Improvement

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_memory and per_cpu_untracked_memory_thread_buffer server 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 settings

By bounding maximum untracked memory to ncpu*max_per_cpu_untracked_memory we can avoid this massive memory overcommit, and also with default max_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 default max_server_memory_usage_to_ram_ratio already.

Note, librseq gives ±1% (in the best case), and complexity does not worth it

Version info

  • Merged into: 26.7.1.157 (included in 26.7 and later)

@clickhouse-gh

clickhouse-gh Bot commented May 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fad69b8]

Summary: ✅


AI Review

Summary

This PR adds a process-wide per-CPU budget for deferred CurrentMemoryTracker accounting, wires the new server settings into clickhouse-server and clickhouse-local, refreshes cached memory-sample settings when tracker parents/configs change, and adds focused unit/stateless/integration coverage plus a benchmark. Most earlier review findings have been addressed in the current code; one previously reported exception-path accounting issue still appears to hold, but the author has dismissed it as pre-existing.

Missing context / blind spots
  • ⚠️ I could not run local targeted tests because this checkout has no usable build directory or clickhouse binary. The Praktika PR report currently shows no failed jobs, and the PR discussion includes cloud benchmark evidence.
Findings

⚠️ Majors

  • [src/Common/CurrentMemoryTracker.cpp:104] [dismissed by author -- https://github.com/Bound untracked memory per-CPU to avoid overcommit and OOMs #106055#discussion_r3480843043] The restore path still adds the saved query untracked_memory back after MemoryTracker::allocImpl has constructed MEMORY_LIMIT_EXCEEDED under MemoryTrackerBlockerInThread(Global). If those exception-formatting allocations changed untracked_memory_blocker_level, the previously live query bytes are later flushed under the wrong blocker level and can bypass the query/user trackers. The same restore pattern existed before, but the new per-CPU budget adds another default flush trigger, so the invariant is still relevant to this PR. Suggested fix: restore the saved untracked_memory_blocker_level before reattaching previous_untracked_memory, or keep exception-formatting bytes separate from the saved query bytes.
Final Verdict

Status: ⚠️ Request changes

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.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements submodule changed At least one submodule changed in this PR. labels May 28, 2026
@azat
azat force-pushed the per-cpu-untracked-memory branch from 359d2e9 to b4bca3f Compare May 28, 2026 16:08
@azat
azat force-pushed the per-cpu-untracked-memory branch from b4bca3f to d935181 Compare May 28, 2026 20:26
Comment thread src/Common/CurrentMemoryTracker.cpp Resolved
Comment thread src/Common/ThreadStatus.h Resolved
Comment thread src/Core/Settings.cpp Resolved
@Ergus Ergus self-assigned this May 29, 2026

@Ergus Ergus 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 is labelled "Performance Improvement" but the primary goal is OOM prevention... a correctness/safety fix.

So I think this is an Improvement,

Comment thread src/Common/MemoryTrackerSwitcher.cpp Resolved
Comment thread src/Common/CurrentMemoryTracker.cpp Resolved
@azat

azat commented May 31, 2026

Copy link
Copy Markdown
Member Author

This is labelled "Performance Improvement" but the primary goal is OOM prevention... a correctness/safety fix.

It is marked as so to run performance tests, and in some sense "OOM prevention" can be "performance improvement"

Comment thread src/Common/PerCPUMemory.h Resolved
@azat
azat marked this pull request as draft June 1, 2026 09:27
@azat

azat commented Jun 1, 2026

Copy link
Copy Markdown
Member Author

@Ergus I do not like current implementation, will keep it as draft for now, and ping you/undraft once it will be ready

Comment thread programs/server/Server.cpp Resolved
Comment thread src/Common/CurrentMemoryTracker.cpp Resolved
Comment thread programs/server/Server.cpp Resolved
Comment thread src/Common/PerCPUMemory.h Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 2 query(s) improved out of 38 analysed

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)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 4 improvement 264 223 -15.5% <0.0001 memory: PR reworks the per-allocation memory-tracker hot path; cheaper alloc/free plausibly speeds this allocation-heavy query
🟢 15 improvement 249 198 -20.5% <0.0001 memory: Same memory-tracker fast-path change; larger -20.5% delta fits a GROUP BY that allocates heavily per row

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: 192275d1-a600-4708-92e2-c8d2681d5e87
  • MIRAI run: 09374a6b-f9b3-414d-a8da-e25fa35fb772
  • PR check IDs:
    • clickbench_240604_1782572096
    • clickbench_240610_1782572096
    • clickbench_240620_1782572096
    • tpch_adapted_1_official_240627_1782572096
    • tpch_adapted_1_official_240637_1782572096
    • tpch_adapted_1_official_240652_1782572096

@azat azat changed the title Per-CPU bound on untracked memory to prevent OOMs Bound untracked memory per-CPU to avoid overcommit and OOMs Jun 4, 2026
@azat
azat marked this pull request as ready for review June 4, 2026 16:35
@azat

azat commented Jun 4, 2026

Copy link
Copy Markdown
Member Author

@Ergus now it should be better, it uses reservation on per-cpu counters instead

Comment thread src/Common/CurrentMemoryTracker.cpp Resolved
@azat
azat force-pushed the per-cpu-untracked-memory branch 2 times, most recently from b81c6a0 to 0c3d87e Compare June 25, 2026 15:22
Comment thread src/Interpreters/ThreadStatusExt.cpp Resolved
@azat
azat force-pushed the per-cpu-untracked-memory branch from 0c3d87e to f09ba51 Compare June 25, 2026 16:43
Comment thread src/Common/PerCPUMemory.h Resolved
@azat
azat force-pushed the per-cpu-untracked-memory branch from f09ba51 to 77ee5d8 Compare June 26, 2026 10:39
}
catch (...)
{
current_thread->untracked_memory += previous_untracked_memory;

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.

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This is existing bug, please do not report such, only new that this PR introduces. I will address this later,

Comment thread src/Common/ThreadStatus.cpp Resolved
@azat
azat force-pushed the per-cpu-untracked-memory branch 2 times, most recently from 3430ad4 to ae6e0e8 Compare June 26, 2026 11:58
azat and others added 4 commits June 27, 2026 14:32
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]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 27, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.30% 85.40% +0.10%
Functions 92.60% 92.60% +0.00%
Branches 77.60% 77.60% +0.00%

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

Full report · Diff report

@azat
azat added this pull request to the merge queue Jun 27, 2026
Merged via the queue into ClickHouse:master with commit 7d9938c Jun 27, 2026
169 checks passed
@azat
azat deleted the per-cpu-untracked-memory branch June 27, 2026 16:20
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 27, 2026
@azat azat added the memory When memory usage is higher than expected label Jun 28, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Bound untracked memory per-CPU to avoid overcommit and OOMs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

memory When memory usage is higher than expected pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants