Skip to content

Speculatively reserve growth headroom on top of observed RSS - #104976

Merged
alexey-milovidov merged 31 commits into
masterfrom
memory-worker-rss-speculative-reserve
Jun 28, 2026
Merged

alexey-milovidov merged 31 commits into
masterfrom
memory-worker-rss-speculative-reserve

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented May 14, 2026 •

Copy link
Copy Markdown
Member

On every MemoryWorker tick the gap between observed RSS and
MemoryTracker's tracked counter (resident - tracked) represents memory
that the cgroup / jemalloc::stats.resident view picked up during the last
sampling interval but that has not yet flowed into the tracker (per-thread
max_untracked_memory accumulator, 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_usage before the next
memory_worker_period_ms tick (50 ms by default) corrects the view, and the
kernel OOM-killer then fires before MemoryTracker::allocImpl has a chance
to throw MEMORY_LIMIT_EXCEEDED.

The global hard-limit check in MemoryTracker::allocImpl already consults
rss via the will_be_rss > current_hard_limit branch, so biasing the
sampled rss upward causes the limit to fire earlier on subsequent
allocations.

This PR adds a new server-level setting
memory_worker_rss_speculative_reserve_ratio (default 1.0). On every tick,
MemoryWorker::updateResidentMemoryThread now sets

rss = resident + ratio * min(resident - previous_resident, resident - tracked)

where resident - previous_resident is how much RSS actually grew over the
last tick. On the assumption that the next interval may grow by the same
amount, the default 1.0 reserves one full growth delta of headroom; larger
values reserve proportionally more, and 0 falls back to the previous
behaviour (rss = resident). The growth is additionally capped by
resident - tracked, the part of RSS the global tracker does not see: growth
that has already flowed into the tracker is handled by the ordinary
will_be > current_hard_limit check, so reserving for it would only make the
limit fire needlessly early on fully-tracked workloads. The cumulative gap
resident - tracked is deliberately not used as the reservation itself -- on
a long-running server jemalloc page retention and fragmentation make that gap
structurally large (gigabytes) even when nothing is growing, which would pin
the published rss at the hard limit and cause false MEMORY_LIMIT_EXCEEDED
for unrelated small allocations (this was breaking queries in the
performance-comparison CI). The reservation is then capped at
current_hard_limit - resident before being added, so a very large
configured ratio can never overflow the signed Int64 addition or push the
published rss past the hard limit (beyond which it would gain no early-throw
power anyway). Speculation is skipped entirely when no global hard limit is
configured (current_hard_limit == 0), on the very first worker iteration (no
previous interval to extrapolate from), and once resident itself reaches the
hard limit (any allocation already trips the limit).

Under sanitizer builds (ASan, UBSan, MSan, TSan) the gap
resident - tracked is dominated by shadow-memory / runtime overhead rather
than tracker bookkeeping lag, so a non-zero ratio would push the tracker past
max_server_memory_usage even for ordinary, non-stress queries. The default
is therefore computed at compile time
(getDefaultMemoryWorkerRssSpeculativeReserveRatio in ServerSettings.cpp)
and pinned to 0 for any defined(SANITIZER) build, so the default 1.0 is
active only on the regular non-sanitized configurations the setting was
designed for.

clickhouse-keeper intentionally does not wire this setting:
speculation only influences the global will_be_rss > current_hard_limit
branch in MemoryTracker::allocImpl, but standalone Keeper never sets the
global hard limit (it enforces keeper_server.max_memory_usage_soft_limit
separately in KeeperServer::isExceedingMemorySoftLimit), so the speculation
would 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-thread max_untracked_memory accumulator (worst case = threads * untracked).
  • memory_worker_rss_speculative_reserve_ratio -- periodic-sampling lag of cgroup / jemalloc readings between MemoryWorker ticks.

Changelog category (leave one):

  • Improvement

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 (default 1.0, or 0 in sanitizer builds) which makes the global memory tracker speculatively reserve ratio * min(resident - previous_resident, resident - tracked) on top of the observed RSS each MemoryWorker tick. This biases the tracker upward when RSS growth is outpacing the tracker bookkeeping between samples, so allocations get MEMORY_LIMIT_EXCEEDED earlier and the kernel OOM-killer is less likely to fire first. Set the ratio to 0 to disable speculation. Sanitizer builds default to 0 because the resident - tracked gap is dominated by sanitizer shadow memory there.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

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

…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]>
@clickhouse-gh

clickhouse-gh Bot commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1132c4f]

Summary: ✅


AI Review

Summary

This PR adds memory_worker_rss_speculative_reserve_ratio so MemoryWorker can publish a capped speculative RSS value based on the last observed RSS growth and the untracked resident - tracked gap. I rechecked the current combined diff and all prior review threads; the earlier Keeper wiring, overflow, first-run, negative tracker, and stale metadata issues are addressed in the current code. I did not find a remaining code-level issue that warrants a new inline comment.

Missing context / blind spots
  • ⚠️ .claude/tools/fetch_ci_report.js could not fetch Praktika reports because the available GitHub token was rejected with HTTP 403. The GitHub check rollup I fetched still had several checks in progress; passing CI would close this blind spot.
Final Verdict

Status: ✅ Approve

No code changes are required from this review.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label May 14, 2026
@alexey-milovidov alexey-milovidov added the memory When memory usage is higher than expected label May 14, 2026
Comment thread programs/server/Server.cpp Resolved
Comment thread src/Common/MemoryWorker.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Combined test with #104965

I tested this PR stacked on top of #104965 (a local branch with both commits; the test code in the existing tmp/oom-lab/ harness, 8 GiB systemd-run scope on a 192 GiB host, max_server_memory_usage_to_ram_ratio = 0.9). Scenarios:

  • M — 200 concurrent SELECTs, no per-user or per-query budget.
  • X — 100 concurrent SELECTs with max_memory_usage = 200000000, no per-user budget.
  • W — 200 concurrent SELECTs with max_memory_usage_for_user = 4 GiB (the operator mitigation we already had).
config M X W
master baseline OOM-kill OOM-kill survives
only #104965, 4 MiB OOM-kill OOM-kill survives
only this PR, ratio=1.0 OOM-kill OOM-kill survives
both at defaults (4 MiB + 1.0) mostly survives, flaky mostly survives, flaky survives
both + memory_worker_period_ms=10 survives survives survives
4 MiB + ratio=2.0 survives survives survives
only #104965 at 8 MiB survives survives survives

What this PR actually does on M/X with default ratio=1.0:

  • The tracker's rss view is being inflated. Server logs show current RSS: 7.54 GiB reported against a maximum: 7.20 GiB, so the will_be_rss > current_hard_limit branch in MemoryTracker::allocImpl is the one firing -- the rss-based check kicks in earlier than the amount-based one, which is the intended effect.
  • Several hundred MEMORY_LIMIT_EXCEEDED exceptions get raised cleanly.
  • But the 800 MiB of cgroup headroom (8 GiB - 7.20 GiB) is consumed while 200 queries unwind their stacks. Whether the kernel OOM-killer wins depends on the exact interleaving -- five isolated M-only runs all passed, but two of three back-to-back M+X+W sequences killed M.

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:

  • bump additional_memory_tracking_per_thread 4 → 8 MiB, or
  • bump memory_worker_rss_speculative_reserve_ratio 1.0 → 2.0, or
  • drop memory_worker_period_ms 50 → 10 ms (faster RSS sampling), or
  • set max_memory_usage_for_user (the W mitigation).

The two patches together at default + one of those four knobs gives a deterministic safety margin.

One caveat on this PR alone: when tracked > resident at sample time (ClickHouse's allocator reserves capacity before pages are touched, which is common in aggregations), delta < 0 and the speculative is clamped to zero. So this PR doesn't help workloads where the tracker over-counts -- it specifically helps the inverse case (cgroup growth outpacing tracker bookkeeping between samples). That's why it pairs cleanly with #104965 rather than substituting for it.

alexey-milovidov and others added 4 commits May 15, 2026 00:18
`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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Pushed three follow-up commits addressing review feedback:

  • 88104b93b1b — wire memory_worker_rss_speculative_reserve_ratio into Keeper.cpp so clickhouse-keeper actually honours the configured value (was silently using the default).
  • f451d0c6718 — clamp the speculative reservation against Int64 overflow when the configured ratio is very large.
  • 8174a1333a4 — change default from 1.0 to 0.0 (opt-in).

The CI failures on the previous commit (1/2, 2/2) showed that with default ratio = 1.0 the ASan+UBSan stateless tests hit MEMORY_LIMIT_EXCEEDED because under those sanitizers resident - tracked is dominated by shadow-memory overhead rather than tracker bookkeeping lag — so doubling the apparent RSS pushes the tracker past max_server_memory_usage for ordinary, non-stress queries. The behaviour is still useful for the OOM-stress scenarios documented in the PR description; making the setting opt-in keeps it available without regressing the existing test suite.

The Unit tests (asan_ubsan, function_prop_fuzzer) failure (FunctionsStress.stress — ifNull broken_determinism) is unrelated and tracked by #104877.

Comment thread src/Core/ServerSettings.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

change default from 1.0 to 0.0 (opt-in).

Change it back to 1.0, but we can disable it for tests with sanitizers.

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

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 azat self-assigned this May 15, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

@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

@azat

azat commented May 15, 2026

Copy link
Copy Markdown
Member

it is designed for the cases when there is a memory growth

Yes, but

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.

  • tracked memory w/o MEMORY_LIMIT_EXCEEDED is not a problem, it account memory properly
  • unaccounted memory in jemalloc should not be a problem either, it is actually can be make things "worse" - lead to MEMORY_LIMIT_EXCEEDED earlier

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]>
Comment thread src/Common/MemoryWorker.cpp Resolved
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
Comment thread src/Common/MemoryWorker.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

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

@alexey-milovidov

Copy link
Copy Markdown
Member Author

For me, the main argument is easy to reproduce OOM #104976 (comment)
that this PR fixes.

`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).
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Reworked the speculative reservation to base it on the actual last-interval RSS growth min(resident - prev_resident, resident - tracked) instead of the cumulative resident - tracked gap.

The cumulative gap is structurally large on a long-running server (jemalloc page retention / fragmentation), and right after a large query frees its memory tracked collapses while resident stays high — so reserving the whole gap pinned the published rss at the hard limit and made unrelated small allocations throw false MEMORY_LIMIT_EXCEEDED until a later tick. That was the cause of the slower / Errors while building the report failures in the performance-comparison CI (both ::old and ::new regressed, the signature of the server breaking rather than a real perf change).

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 no_speculative_rss_reserve.xml workarounds (test_memory_limit, test_merges_memory_limit, test_userspace_page_cache, SQLLogic) are no longer needed and have been removed. Built and link-verified locally.

…peculative-reserve

# Conflicts:
#	programs/local/LocalServer.cpp
#	programs/server/Server.cpp
#	src/Common/MemoryWorker.cpp
#	src/Common/MemoryWorker.h
#	src/Core/ServerSettings.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Merged the latest master into the branch (it was ~2500 commits behind, and the last commit — the reworked min(resident - prev_resident, resident - tracked) formula — had never triggered a CI run).

The merge conflicted with the new memory_worker_dynamic_hard_limit feature that landed on master, which touches the same files (MemoryWorker.{h,cpp}, ServerSettings.cpp, Server.cpp, LocalServer.cpp). The two mechanisms are orthogonal, so I kept both side by side:

  • MemoryWorkerConfig / class members, the ServerSetting DECLAREs, the extern declarations, and the designated initializers now carry both rss_speculative_reserve_ratio and dynamic_hard_limit_ratio.
  • The dynamic-hard-limit block declared a local current_hard_limit that shadowed the one the speculative-reserve block reads earlier in updateResidentMemoryThread (-Wshadow/-Werror). Renamed the inner one to installed_hard_limit; no behavior change.

Verified MemoryWorker.cpp and ServerSettings.cpp (the two files carrying actual logic) compile cleanly against the merged tree; the rest of the conflict resolution is purely additive.

The earlier red was only Performance Comparison noise on c379a187 (fetch_perf_report over all shards: no significant performance changes — 3 faster / 8 slower / 21 unstable across 1927 queries). This change cannot slow release-build query performance: it only biases the sampled rss value consulted by the global hard-limit check in MemoryTracker::allocImpl. Fresh CI is running on the merge commit.

@clickhouse-gh

clickhouse-gh Bot commented Jun 15, 2026

Copy link
Copy Markdown
Contributor

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.

Comment thread src/Core/ServerSettings.cpp Resolved
…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.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Merged the latest master into the branch (it was 1157 commits behind) and re-ran CI.

Conflict resolution — the merge conflicted only in src/Common/MemoryWorker.cpp. While this branch was behind, 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. This 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). I kept master's new threshold logic verbatim and renamed its local to installed_hard_limit (the LOG_TRACE already references that name). No behavior change. The other four touched files (Keeper.cpp, Server.cpp, LocalServer.cpp, ServerSettings.cpp) auto-merged cleanly. Verified the resolved MemoryWorker.cpp compiles cleanly (-fsyntax-only, -Werror -Wall -Wextra) against the merged tree.

CI status before the re-merge — the only red was the Hung check failed, possible deadlock found in Stress test (arm_asan_ubsan). That is the chronic master-wide hung-check flake (13–70 failures/day on master itself, e.g. 70 on 2026-06-16, the day this PR's CI ran), and this PR is a compile-time no-op under SANITIZER (memory_worker_rss_speculative_reserve_ratio defaults to 0 for any defined(SANITIZER) build), so it cannot affect the sanitizer stress run. The remaining Performance Comparison reds are measurement noise (both ::old and ::new flagged; the perf tool reports "no significant performance changes").

AI Review — the previous verdict (⚠️ Request changes) ran on 4d043b1e (2026-06-16) and asked only to "update the PR description and Changelog entry to match the final MemoryWorker formula". That was already done in the description edit on 2026-06-18 (the changelog now reads ratio * min(resident - previous_resident, resident - tracked) and the stale test-override paragraph is gone). Fresh CI re-runs the AI review against the corrected description.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Merged the latest master into the branch and re-ran CI. The merge was clean (no conflicts; among this PR's files master only touched src/Core/ServerSettings.cpp, auto-merged additively — the new memory_worker_rss_speculative_reserve_ratio setting and its getDefaultMemoryWorkerRssSpeculativeReserveRatio default are intact). Net PR diff is unchanged (6 files, +125/-8).

The reason for the re-merge: the previous run's BuzzHouse (amd_debug) failure (Fail point tcp_handler_fail_connection_setup is triggered. (MEMORY_LIMIT_EXCEEDED) → lost connection, cannot reconnect) was caused by #107689 (BuzzHouse: do not enable the tcp_handler_fail_connection_setup fail point) not yet being in the branch — it merged to master about three hours after this branch's previous merge-base. That failpoint throws MEMORY_LIMIT_EXCEEDED directly from TCPHandler connection setup, bypassing the MemoryTracker::allocImpl will_be_rss > current_hard_limit path this PR touches, so it is unrelated to the change; once BuzzHouse's random fault-injection enabled it, the fuzzer could no longer reconnect for the rest of the run. That fix is now in the branch.

The remaining Stress test (arm_asan_ubsan, s3) → Hung check failed, possible deadlock found is the chronic master-wide flake (generic TCPHandler::runImpl / TCPServerDispatcher::run stack, not MemoryWorker; this PR is a compile-time no-op under sanitizers, where the ratio defaults to 0).

@clickhouse-gh

clickhouse-gh Bot commented Jun 21, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.20% 85.30% +0.10%
Functions 92.50% 92.50% +0.00%
Branches 77.50% 77.50% +0.00%

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

Full report · Diff report

@alexey-milovidov alexey-milovidov left a comment

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.

Sounds reasonable.

@alexey-milovidov alexey-milovidov self-assigned this Jun 28, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jun 28, 2026
Merged via the queue into master with commit b44eae0 Jun 28, 2026
327 of 328 checks passed
@alexey-milovidov
alexey-milovidov deleted the memory-worker-rss-speculative-reserve branch June 28, 2026 02:57
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 28, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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)
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`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).
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…s-speculative-reserve

Speculatively reserve growth headroom on top of observed RSS
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-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants