Repository navigation
Speculatively reserve growth headroom on top of observed RSS - #104976
Conversation
…ed RSS
`MemoryWorker` refreshes the global `MemoryTracker`'s `rss` field every
`memory_worker_period_ms` (50 ms by default). Between two refreshes,
allocations bump both the `amount` and the `rss` counter, so the gap
`rss - amount` observed at the previous sample is preserved -- but if
that gap is growing, the next sample will be too late and a burst of
allocations can push real RSS past `max_server_memory_usage` before the
tracker has a chance to see it. The global hard-limit check in
`MemoryTracker::allocImpl` already consults `rss` (via the
`will_be_rss > current_hard_limit` branch), so the limit fires earlier
when `rss` is biased upward.
Add a new server setting `memory_worker_rss_speculative_reserve_ratio`
(default `1.0`). Each tick, `MemoryWorker` now sets
rss = resident + (resident - tracked) * ratio
clamped so that no reservation happens when `resident <= tracked`. With
the default ratio `1.0`, we assume the next interval will grow by at
most the same amount as the last one and reserve that much extra
headroom; setting the ratio to `0` disables the speculation and falls
back to the previous behaviour (`rss = resident`).
This patch is independent of the per-thread reservation in
`additional_memory_tracking_per_thread`; the two address different
parts of the same gap (per-thread untracked accumulator vs. periodic
sampling lag of cgroup/jemalloc readings).
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Workflow [PR], commit [1132c4f] Summary: ✅
AI ReviewSummaryThis PR adds Missing context / blind spots
Final VerdictStatus: ✅ Approve No code changes are required from this review. |
Combined test with #104965I tested this PR stacked on top of #104965 (a local branch with both commits; the test code in the existing
What this PR actually does on M/X with default
So default-default is a strict improvement (M was 100 % OOM-kill on master and is now mostly survives), but not yet deterministic for the most aggressive case. To make M deterministic, any one of these on top of the combined patches is sufficient:
The two patches together at default + one of those four knobs gives a deterministic safety margin. One caveat on this PR alone: when |
…peculative-reserve
`programs/server/Server.cpp` and `programs/local/LocalServer.cpp` were passing the new server setting `memory_worker_rss_speculative_reserve_ratio` into `MemoryWorkerConfig`, but `programs/keeper/Keeper.cpp` was building its `MemoryWorkerConfig` without it, so the configured value was silently ignored by `clickhouse-keeper`. Add the missing `ServerSetting` declaration and the corresponding field initialiser. Spotted by AI review on #104976. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`MemoryWorker::updateResidentMemoryThread` was multiplying `delta` by `rss_speculative_reserve_ratio` and adding the result to `resident` without any bounds check. A very large configured ratio could overflow the `double -> Int64` conversion (UB) or the signed `Int64` addition, producing a negative or wrap-around `rss` value and weakening the global hard-limit check inside `MemoryTracker::allocImpl`. Compute the maximum admissible reservation as `std::numeric_limits<Int64>::max() - resident`, compare against the unrounded `double` product before casting, and clamp. Spotted by AI review on #104976. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
CI for #104976 showed that the default ratio of `1.0` causes widespread `MEMORY_LIMIT_EXCEEDED` errors in the ASan + UBSan stateless tests: under those sanitizers the gap `resident - tracked` is dominated by sanitizer shadow memory rather than tracker bookkeeping lag, so doubling the apparent RSS pushes the tracker past `max_server_memory_usage` and stops ordinary, non memory-stress queries. Failing checks (~282 stateless tests in each shard): - https://github.com/ClickHouse/ClickHouse/actions/runs/25880162948/job/76062000101 - https://github.com/ClickHouse/ClickHouse/actions/runs/25880162948/job/76062000097 The mechanism is still useful in OOM-stress scenarios as documented in the PR description, so keep the setting but make it opt-in: change the default from `1.0` to `0.0`. Operators wanting the OOM-survival behaviour set the ratio explicitly (per the PR's own stress harness, e.g. `ratio = 1.0` or `2.0`). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Pushed three follow-up commits addressing review feedback:
The CI failures on the previous commit (1/2, 2/2) showed that with default The |
Change it back to 1.0, but we can disable it for tests with sanitizers. |
azat
left a comment
There was a problem hiding this comment.
I think #104125 will be a better fix for this problem
Because this is asynchronous via some side channel and also resident - tracked is not always untracked, plus it may not allow untracked memory to be flushed with MEMORY_LIMIT_EXCEEDED errors
|
@azat, it is designed for the cases when there is a memory growth, which can be either untracked memory in threads, or tracked memory without the chance of throwing (like allocation by a big std::string), or unaccounted memory like jemalloc tcache and dirty pages. Your PR addresses only a narrow scenario of untracked memory, which, anyway could be fixed much simpler by #104965 |
Yes, but
|
Reverts the opt-in default introduced in 8174a13 (which changed `memory_worker_rss_speculative_reserve_ratio` from `1.0` to `0.0`) so that the OOM-survival behaviour is on by default in regular builds. To keep the ASan + UBSan stateless tests green, `tests/config/install.sh` now installs `memory_worker_rss_speculative_reserve_ratio.yaml` (`ratio = 0`) only when the build is compiled with `-fsanitize=`. Under sanitizer builds the gap `resident - tracked` is dominated by sanitizer shadow / runtime overhead rather than tracker bookkeeping lag, so a non-zero ratio biases the tracker past `max_server_memory_usage` even for ordinary, non-stress queries. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…peculative-reserve
The inline comment in `MemoryWorker::updateResidentMemoryThread` claimed the default `ratio` is `0`, but after the latest follow-up the default in `ServerSettings` is `1.0` and only sanitizer test configs pin it to `0`. Update the comment to match the current contract. Address review: #104976 (comment)
…itizer builds at compile time The previous approach installed a config snippet from `install.sh` for `clickhouse-server` runs on sanitizer builds. However, many stateless tests invoke `clickhouse-local` directly, and `clickhouse-local` does not read the server's `config.d` directory, so the override never took effect there. The ASan / UBSan tests then OOM-failed because the `resident - tracked` gap is dominated by shadow memory and the default `ratio = 1.0` biased the tracker past `max_server_memory_usage` (e.g. `current RSS: 59.04 GiB, maximum: 53.79 GiB` in `04039_arrow_uuid`). Move the sanitizer-aware default into `ServerSettings.cpp` itself, following the `getDefaultOomScore` pattern, so the same default applies to `clickhouse-server`, `clickhouse-local`, and `clickhouse-keeper` without requiring test-time configuration. Drop the now-redundant `install.sh` branch and the corresponding YAML snippet. CI report: #104976
|
@azat, there are more reasons why process' memory usage can be higher than tracked + jemalloc caches: - thread stacks; - situations when we use less than a page; - mmap-ed parts of the binary. |
|
For me, the main argument is easy to reproduce OOM #104976 (comment) |
`total_memory_tracker.get()` can legitimately go negative — the lazy correction inside `updateResidentMemoryThread` handles this through `MemoryTracker::updateAllocated`, but that correction runs *after* the speculative-reserve branch. With the raw value, a transiently negative tracker made `delta = resident - tracked` larger than `resident`, pushing the speculative `rss` arbitrarily far above real resident and triggering false `MEMORY_LIMIT_EXCEEDED` decisions in `MemoryTracker::allocImpl`. Reported by `clickhouse-gh` review on #104976 (comment).
…peculative-reserve
Base the speculative reservation on the actual last-interval RSS growth `resident - prev_resident` (capped by `resident - tracked`, the untracked part), instead of the cumulative `resident - tracked` gap. The cumulative gap is structurally large (gigabytes) on a long-running server because of jemalloc page retention and fragmentation, even when nothing is growing. In particular, right after a large query frees its memory, `tracked` collapses while `resident` stays high, so reserving the whole gap pins the published `rss` at the hard limit and unrelated small allocations get false `MEMORY_LIMIT_EXCEEDED` until a later tick republishes a sane value. This was breaking queries in the performance-comparison CI. Reserving only the last-interval growth keeps the early-throw behaviour the setting was designed for while staying quiet on steady-state and post-query workloads. As a result, the per-test `no_speculative_rss_reserve.xml` drop-ins (`test_memory_limit`, `test_merges_memory_limit`, `test_userspace_page_cache`, SQLLogic) are no longer needed and are removed. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Reworked the speculative reservation to base it on the actual last-interval RSS growth The cumulative gap is structurally large on a long-running server (jemalloc page retention / fragmentation), and right after a large query frees its memory Reserving only the last-interval growth keeps the early-throw behaviour the setting was designed for while staying quiet on steady-state and post-query workloads, so the per-test |
…peculative-reserve # Conflicts: # programs/local/LocalServer.cpp # programs/server/Server.cpp # src/Common/MemoryWorker.cpp # src/Common/MemoryWorker.h # src/Core/ServerSettings.cpp
|
Merged the latest The merge conflicted with the new
Verified The earlier red was only Performance Comparison noise on |
|
Dear @azat, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
…peculative-reserve
…peculative-reserve Branch was 1157 commits behind master and the only CI red was the chronic master-wide `Hung check failed, possible deadlock found` flake (13-70/day on master itself; this PR is a compile-time no-op under `SANITIZER` so it cannot affect the `arm_asan_ubsan` stress run). Re-merge to refresh CI on the current master and to re-run the AI review against the already-updated PR description. The merge conflicted only in `src/Common/MemoryWorker.cpp`: master evolved the `memory_worker_dynamic_hard_limit` apply block to skip adjustments smaller than `min_change_ratio` (1%) of the current limit, still naming the local `current_hard_limit`. The branch had renamed that local to `installed_hard_limit` to avoid shadowing the `current_hard_limit` the speculative-reserve block reads earlier in `updateResidentMemoryThread` (`-Wshadow`/`-Werror`). Kept master's new threshold logic verbatim and renamed its local to `installed_hard_limit`; the `LOG_TRACE` already references `installed_hard_limit`. No behavior change. Verified the resolved `MemoryWorker.cpp` compiles cleanly (`-fsyntax-only`, `-Werror -Wall -Wextra`) against the merged tree.
|
Merged the latest Conflict resolution — the merge conflicted only in CI status before the re-merge — the only red was the AI Review — the previous verdict ( |
…peculative-reserve
|
Merged the latest The reason for the re-merge: the previous run's The remaining |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 89/93 (95.70%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 3 line(s) · Uncovered code |
alexey-milovidov
left a comment
There was a problem hiding this comment.
Sounds reasonable.
`programs/server/Server.cpp` and `programs/local/LocalServer.cpp` were passing the new server setting `memory_worker_rss_speculative_reserve_ratio` into `MemoryWorkerConfig`, but `programs/keeper/Keeper.cpp` was building its `MemoryWorkerConfig` without it, so the configured value was silently ignored by `clickhouse-keeper`. Add the missing `ServerSetting` declaration and the corresponding field initialiser. Spotted by AI review on ClickHouse#104976. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`MemoryWorker::updateResidentMemoryThread` was multiplying `delta` by `rss_speculative_reserve_ratio` and adding the result to `resident` without any bounds check. A very large configured ratio could overflow the `double -> Int64` conversion (UB) or the signed `Int64` addition, producing a negative or wrap-around `rss` value and weakening the global hard-limit check inside `MemoryTracker::allocImpl`. Compute the maximum admissible reservation as `std::numeric_limits<Int64>::max() - resident`, compare against the unrounded `double` product before casting, and clamp. Spotted by AI review on ClickHouse#104976. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
CI for ClickHouse#104976 showed that the default ratio of `1.0` causes widespread `MEMORY_LIMIT_EXCEEDED` errors in the ASan + UBSan stateless tests: under those sanitizers the gap `resident - tracked` is dominated by sanitizer shadow memory rather than tracker bookkeeping lag, so doubling the apparent RSS pushes the tracker past `max_server_memory_usage` and stops ordinary, non memory-stress queries. Failing checks (~282 stateless tests in each shard): - https://github.com/ClickHouse/ClickHouse/actions/runs/25880162948/job/76062000101 - https://github.com/ClickHouse/ClickHouse/actions/runs/25880162948/job/76062000097 The mechanism is still useful in OOM-stress scenarios as documented in the PR description, so keep the setting but make it opt-in: change the default from `1.0` to `0.0`. Operators wanting the OOM-survival behaviour set the ratio explicitly (per the PR's own stress harness, e.g. `ratio = 1.0` or `2.0`). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The inline comment in `MemoryWorker::updateResidentMemoryThread` claimed the default `ratio` is `0`, but after the latest follow-up the default in `ServerSettings` is `1.0` and only sanitizer test configs pin it to `0`. Update the comment to match the current contract. Address review: ClickHouse#104976 (comment)
…itizer builds at compile time The previous approach installed a config snippet from `install.sh` for `clickhouse-server` runs on sanitizer builds. However, many stateless tests invoke `clickhouse-local` directly, and `clickhouse-local` does not read the server's `config.d` directory, so the override never took effect there. The ASan / UBSan tests then OOM-failed because the `resident - tracked` gap is dominated by shadow memory and the default `ratio = 1.0` biased the tracker past `max_server_memory_usage` (e.g. `current RSS: 59.04 GiB, maximum: 53.79 GiB` in `04039_arrow_uuid`). Move the sanitizer-aware default into `ServerSettings.cpp` itself, following the `getDefaultOomScore` pattern, so the same default applies to `clickhouse-server`, `clickhouse-local`, and `clickhouse-keeper` without requiring test-time configuration. Drop the now-redundant `install.sh` branch and the corresponding YAML snippet. CI report: ClickHouse#104976
`total_memory_tracker.get()` can legitimately go negative — the lazy correction inside `updateResidentMemoryThread` handles this through `MemoryTracker::updateAllocated`, but that correction runs *after* the speculative-reserve branch. With the raw value, a transiently negative tracker made `delta = resident - tracked` larger than `resident`, pushing the speculative `rss` arbitrarily far above real resident and triggering false `MEMORY_LIMIT_EXCEEDED` decisions in `MemoryTracker::allocImpl`. Reported by `clickhouse-gh` review on ClickHouse#104976 (comment).
…ges_memory_limit` The test asserts that three large `INSERT`s followed by `OPTIMIZE TABLE ... FINAL` succeed under a 20 GiB container limit. The default `memory_worker_rss_speculative_reserve_ratio = 1.0` biases the observed RSS upward by the `resident - tracked` gap on every `MemoryWorker` tick, which under this tight budget tips the `INSERT`s past `max_server_memory_usage` and fires `MEMORY_LIMIT_EXCEEDED` in `ColumnString::replicate` before the merge logic the test is exercising can run. The PR's mechanism is not under test here, so pin the ratio to `0` for this test, matching the existing `test_userspace_page_cache` and SQLLogic overrides. CI report: ClickHouse#104976 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…s-speculative-reserve Speculatively reserve growth headroom on top of observed RSS
On every
MemoryWorkertick the gap between observed RSS andMemoryTracker's tracked counter (resident - tracked) represents memorythat the cgroup /
jemalloc::stats.residentview picked up during the lastsampling interval but that has not yet flowed into the tracker (per-thread
max_untracked_memoryaccumulator, kernel-side overhead, dirty pages, etc.).Between samples, the tracker is "blind" to similar growth -- a burst of
allocations can push real RSS past
max_server_memory_usagebefore the nextmemory_worker_period_mstick (50 ms by default) corrects the view, and thekernel OOM-killer then fires before
MemoryTracker::allocImplhas a chanceto throw
MEMORY_LIMIT_EXCEEDED.The global hard-limit check in
MemoryTracker::allocImplalready consultsrssvia thewill_be_rss > current_hard_limitbranch, so biasing thesampled
rssupward causes the limit to fire earlier on subsequentallocations.
This PR adds a new server-level setting
memory_worker_rss_speculative_reserve_ratio(default1.0). On every tick,MemoryWorker::updateResidentMemoryThreadnow setswhere
resident - previous_residentis how much RSS actually grew over thelast tick. On the assumption that the next interval may grow by the same
amount, the default
1.0reserves one full growth delta of headroom; largervalues reserve proportionally more, and
0falls back to the previousbehaviour (
rss = resident). The growth is additionally capped byresident - tracked, the part of RSS the global tracker does not see: growththat has already flowed into the tracker is handled by the ordinary
will_be > current_hard_limitcheck, so reserving for it would only make thelimit fire needlessly early on fully-tracked workloads. The cumulative gap
resident - trackedis deliberately not used as the reservation itself -- ona long-running server jemalloc page retention and fragmentation make that gap
structurally large (gigabytes) even when nothing is growing, which would pin
the published
rssat the hard limit and cause falseMEMORY_LIMIT_EXCEEDEDfor unrelated small allocations (this was breaking queries in the
performance-comparison CI). The reservation is then capped at
current_hard_limit - residentbefore being added, so a very largeconfigured ratio can never overflow the signed
Int64addition or push thepublished
rsspast the hard limit (beyond which it would gain no early-throwpower anyway). Speculation is skipped entirely when no global hard limit is
configured (
current_hard_limit == 0), on the very first worker iteration (noprevious interval to extrapolate from), and once
residentitself reaches thehard limit (any allocation already trips the limit).
Under sanitizer builds (
ASan,UBSan,MSan,TSan) the gapresident - trackedis dominated by shadow-memory / runtime overhead ratherthan tracker bookkeeping lag, so a non-zero ratio would push the tracker past
max_server_memory_usageeven for ordinary, non-stress queries. The defaultis therefore computed at compile time
(
getDefaultMemoryWorkerRssSpeculativeReserveRatioinServerSettings.cpp)and pinned to
0for anydefined(SANITIZER)build, so the default1.0isactive only on the regular non-sanitized configurations the setting was
designed for.
clickhouse-keeperintentionally does not wire this setting:speculation only influences the global
will_be_rss > current_hard_limitbranch in
MemoryTracker::allocImpl, but standalone Keeper never sets theglobal hard limit (it enforces
keeper_server.max_memory_usage_soft_limitseparately in
KeeperServer::isExceedingMemorySoftLimit), so the speculationwould have no effect and is left disabled.
This is independent of the per-thread reservation in
#104965; the two
patches compensate for different parts of the same gap:
additional_memory_tracking_per_thread-- per-threadmax_untracked_memoryaccumulator (worst case =threads * untracked).memory_worker_rss_speculative_reserve_ratio-- periodic-sampling lag of cgroup / jemalloc readings between MemoryWorker ticks.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added a new server setting
memory_worker_rss_speculative_reserve_ratio(default1.0, or0in sanitizer builds) which makes the global memory tracker speculatively reserveratio * min(resident - previous_resident, resident - tracked)on top of the observed RSS eachMemoryWorkertick. This biases the tracker upward when RSS growth is outpacing the tracker bookkeeping between samples, so allocations getMEMORY_LIMIT_EXCEEDEDearlier and the kernel OOM-killer is less likely to fire first. Set the ratio to0to disable speculation. Sanitizer builds default to0because theresident - trackedgap is dominated by sanitizer shadow memory there.Documentation entry for user-facing changes
Version info
26.7.1.188(included in26.7and later)