Repository navigation
Optimizations on low-memory systems (e.g. 2 GiB) - #100389
Conversation
ClickBench fails on machines with only 2 GiB RAM due to several compounding memory management issues. This commit addresses them: 1. Auto-cap `input_format_parquet_memory_high_watermark` to `max_server_memory_usage / 8`. The default 4 GiB watermark causes the Parquet V3 reader to buffer far more data than available on low-memory systems. On systems with >= 32 GiB RAM this has no effect (4 GiB stays as default). 2. Auto-cap `min_insert_block_size_bytes` to `max_server_memory_usage / 8` in the INSERT pipeline squashing transform. The default 256 MiB accumulation threshold is too large relative to available memory on small systems. 3. Exclude kernel memory from cgroups v2 RSS measurement. The `CgroupsV2Reader` previously summed `anon + sock + kernel`, but kernel overhead (page tables, kernel stacks for hundreds of threads) is not under ClickHouse control and should not count toward the server memory limit. 4. Ensure at least 300 MiB of absolute headroom when computing `max_server_memory_usage`. The percentage-based ratio (default 0.9) leaves only 200 MiB on a 2 GiB system, insufficient for OS and jemalloc overhead. 5. On low-memory systems (< 4 GiB), immediately set jemalloc `dirty_decay_ms=0` and enable memory tracker correction. This prevents RSS inflation from jemalloc dirty page retention and memory tracker drift that cause spurious `MEMORY_LIMIT_EXCEEDED` exceptions between queries. Verified: ClickBench (100M rows from 100 Parquet files + all 43 queries) completes successfully on a 2 GiB / 1 CPU cgroup. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
Workflow [PR], commit [1803b99] Summary: ✅ AI ReviewSummaryThis PR introduces low-memory auto-tuning across insert/parquet buffering and background merge executor initialization. On the current ClickHouse Rules
Final Verdict
|
alexey-milovidov
left a comment
There was a problem hiding this comment.
A few hard-coded constants look strange, but having them as settings would be pointless.
Use 0.98 ratio for max_server_memory_usage on systems with < 4 GiB RAM (instead of default 0.9), since kernel memory is excluded from the cgroups v2 RSS measurement. Compute watermark/squashing caps from 90% of the hard limit to ensure pipeline consumption stays below the limit with headroom for spikes. Also auto-cap `input_format_parquet_prefer_block_bytes` to reduce Parquet reader output block sizes on low-memory systems. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
On systems with < 4 GiB RAM: 1. Auto-lower `background_pool_size` to 1 per GiB (from default 16). Each concurrent merge uses 40-80 MiB; 32 concurrent merges (16 threads * 2x ratio) need 1.3-2.6 GiB just for merge buffers, causing immediate OOM on small systems. 2. Reduce `merges_mutations_memory_usage_to_ram_ratio` from 0.5 to 0.1. Merges compete with queries for the same memory budget; giving merges half the RAM leaves too little for INSERT/SELECT. 3. Skip MergeTree sanity checks for `number_of_free_entries_in_pool_*` when defaults exceed the auto-lowered pool size. Only throw when the user explicitly changed these settings. 4. Cap `preferred_block_size_bytes` for input format readers based on available memory, matching the squashing cap. 5. Use 0.99 effective `max_server_memory_usage_to_ram_ratio` on < 4 GiB systems (safe because kernel memory is excluded from cgroups v2 RSS). Verified: ClickBench with TSV on 1 GiB / 1 CPU — all 100M rows loaded, merges reduce parts from 646 to ~80, 42/43 queries pass (only `COUNT(DISTINCT UserID)` fails due to hash table resizing). Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- Fix comment/code mismatch: use 0.95 ratio (5% headroom) as the comment says, instead of 0.99 which left dangerously tight ~20 MiB on 2 GiB - Fix log messages to print `effective_ratio` instead of the original `max_server_memory_usage_to_ram_ratio` so operators see correct diagnostics - Restore kernel memory in cgroups v2 RSS calculation: it was added intentionally to prevent OOM with userspace pagecache - Remove conditional `correct_tracker` enabling on low-memory systems: memory tracker correction should not be polluted by RSS readings conditionally (this also fixes a data race on the non-atomic bool) - Move parquet memory cap after all direct setting assignments to prevent the cap on `prefer_block_bytes` from being overwritten - Use `std::min(current_ratio, 1.0)` instead of unconditionally setting `background_merges_mutations_concurrency_ratio` to 1, to avoid overriding an explicit user-configured ratio Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
… v2 test The low-memory auto-tuning (for systems < 4 GiB) was unconditionally overriding `max_server_memory_usage_to_ram_ratio`, `merges_mutations_memory_usage_to_ram_ratio`, `background_pool_size`, and `background_merges_mutations_concurrency_ratio` even when the operator had explicitly configured them. Now the uplift/cap is only applied when the setting was not explicitly changed by the user. Also fix the cgroups v2 unit test: commit b2e2505 restored kernel memory to the `readMemoryUsage` calculation but the test expected value was not updated accordingly. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
`std::min` requires matching types, and `SettingFieldFloat` has no implicit conversion to `Field`. Use an intermediate `double` variable. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Resolve conflict between the type-cast fix and the `.changed` guard approach from 0ad729f. Keep both: check `.changed` to respect explicit user config, and use `static_cast<double>` to satisfy `std::min` and the `set` call. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…utations_concurrency_ratio` `std::min(static_cast<double>(...), 1.0)` returns `double`, which cannot be implicitly assigned to the `SettingFieldFloat`-typed variable under `-Werror`. Use `float` literals instead. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…watermark-autotune
|
For kernel memory, we can (and should exclude reclaimable slab) #100901 |
| if (!server_settings[ServerSetting::background_merges_mutations_concurrency_ratio].changed) | ||
| background_merges_mutations_concurrency_ratio = std::min(static_cast<float>(background_merges_mutations_concurrency_ratio), 1.0f); | ||
| /// Update shared settings so the MergeTree sanity check sees the lowered values. | ||
| shared->server_settings.set("background_pool_size", max_pool); |
There was a problem hiding this comment.
shared->server_settings.set is called here without taking shared->mutex (or using Context::setServerSetting). Most other server-setting mutations are done under shared->mutex, while reads happen from multiple threads (often lock-free via getServerSettings).
This introduces an unsynchronized write to global settings state during executor initialization and can race with concurrent readers.
Please route these updates through a synchronized path (e.g. setServerSetting/shared->mutex) or avoid mutating shared->server_settings and pass the lowered values directly to the sanity check/executor init path.
…watermark-autotune # Conflicts: # src/Interpreters/InterpreterInsertQuery.cpp
|
|
||
| if (number_of_free_entries_in_pool_to_execute_mutation > background_pool_tasks) | ||
| if (number_of_free_entries_in_pool_to_execute_mutation > background_pool_tasks | ||
| && number_of_free_entries_in_pool_to_execute_mutation.changed) |
There was a problem hiding this comment.
This change weakens sanityCheck for all deployments, not only the low-memory auto-tuning case.
By gating on ...changed, we now skip validation whenever these MergeTree settings stay at defaults, even if background_pool_size * background_merges_mutations_concurrency_ratio is explicitly configured lower than those defaults. In that case, mutation/optimize scheduling can be effectively disabled at runtime (e.g. threshold 20 with max_tasks_count 2), whereas previously startup failed fast with a clear configuration exception.
Could we keep the validation for explicit operator configs and only bypass it when the pool/task count was auto-lowered by the low-memory heuristic?
|
The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix. |
…otune' into fix-parquet-memory-watermark-autotune
…watermark-autotune
… when auto-lowered On low-memory hosts, auto-lowering `background_pool_size` to a small value (e.g. 1) combined with a user-configured fractional `background_merges_mutations_concurrency_ratio` (e.g. 0.5) produced `background_pool_max_tasks_count = size_t(1 * 0.5) = 0`, which made `MergeTreeBackgroundExecutor` throw `Task count for MergeTreeBackgroundExecutor must not be zero` at startup. Track auto-lowering with a local flag and, after the multiplication, clamp the resulting task count to at least 1 in the auto-lowered path so the server can still start. Behavior in the non-auto-lowered path (explicit operator misconfiguration) is preserved unchanged. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…watermark-autotune
…watermark-autotune
| const double max_server_memory_usage_to_ram_ratio = new_server_settings[ServerSetting::max_server_memory_usage_to_ram_ratio]; | ||
| const size_t current_physical_server_memory = getMemoryAmount(); /// With cgroups, the amount of memory available to the server can be changed dynamically. | ||
| const size_t default_max_server_memory_usage = static_cast<size_t>(static_cast<double>(current_physical_server_memory) * max_server_memory_usage_to_ram_ratio); | ||
| /// On very small systems (< 4 GiB), the percentage-based headroom (default 10%) is too large |
There was a problem hiding this comment.
This PR introduces several low-memory startup heuristics in core server paths, but there are no test changes in the diff. Please add coverage for at least these edge cases:
- low-memory auto-tuning path (< 4 GiB) keeps server startup valid,
- explicit user overrides (for example
max_server_memory_usage_to_ram_ratio,background_pool_size,background_merges_mutations_concurrency_ratio) are not silently rewritten, - defaults still pass
MergeTreeSettings::sanityCheckafter auto-lowering.
Without targeted tests here, regressions in startup/config compatibility are easy to reintroduce.
|
|
||
| size_t default_merges_mutations_server_memory_usage = static_cast<size_t>(static_cast<double>(current_physical_server_memory) * new_server_settings[ServerSetting::merges_mutations_memory_usage_to_ram_ratio]); | ||
| double merges_mutations_ratio = new_server_settings[ServerSetting::merges_mutations_memory_usage_to_ram_ratio]; | ||
| /// On low-memory systems, limit merge memory to 10% of RAM instead of 50%. |
There was a problem hiding this comment.
Also too ad-hoc, let's remove for now.
| uint64_t default_dirty_decay_ms = dirty_decay_ms_mib.getValue(); | ||
| LOG_INFO(log, "Default dirty pages decay period: {}ms", default_dirty_decay_ms); | ||
|
|
||
| /// On low-memory systems (< 4 GiB), disable jemalloc dirty page retention |
| format_settings.parquet.local_time_as_utc = settings[Setting::input_format_parquet_local_time_as_utc]; | ||
| format_settings.parquet.allow_geoparquet_parser = settings[Setting::input_format_parquet_allow_geoparquet_parser]; | ||
| format_settings.parquet.write_geometadata = settings[Setting::output_format_parquet_geometadata]; | ||
| if (auto memory_limit = total_memory_tracker.getHardLimit(); memory_limit > 0) |
There was a problem hiding this comment.
This is also a good change.
| size_t background_pool_size = server_settings[ServerSetting::background_pool_size]; | ||
| auto background_merges_mutations_concurrency_ratio = server_settings[ServerSetting::background_merges_mutations_concurrency_ratio]; | ||
|
|
||
| /// On low-memory systems, limit concurrent merges to avoid OOM. |
| /// Cap `min_insert_block_size_bytes` by a fraction of the server-wide memory hard limit so | ||
| /// squashing does not accumulate more data than the host can hold. Shared between direct | ||
| /// INSERT and materialized-view pipelines so the cap is applied symmetrically. | ||
| size_t capMinBlockSizeBytesForMemoryLimit(size_t value) |
alexey-milovidov
left a comment
There was a problem hiding this comment.
Two too ad-hoc changes have to be removed, other than that LGTM.
…watermark-autotune
Drop two heuristics added during PR development that override explicit user-configured ratios on small systems: - Forced uplift of `max_server_memory_usage_to_ram_ratio` to `0.95` when RAM < 4 GiB. - Forced cap of `merges_mutations_memory_usage_to_ram_ratio` to `0.1` when RAM < 4 GiB. Per reviewer feedback: too ad-hoc, removing for now. The remaining auto-tuning (Parquet watermark, INSERT block size, background pool, jemalloc dirty decay) is sufficient for the low-memory case and does not silently override explicit operator settings.
|
@groeneai, why did the performance tests fail here? |
|
@alexey-milovidov The perf check failure is on Flagged queries
All flagged queries are Why I think this is noise, not a real regression1. None of the 5 changes can reach these code paths.
2. 11 prior CI runs of this PR all passed. This is the first failure, on commit 3. The flagged queries are chronically borderline. 14-day rate at which each specific query is flagged "slower" on
Every "slower" query in this run fails by a thin margin (relative diff vs threshold: 0.111 vs 0.111 for trim_numbers #3, 0.165 vs 0.162 for trim_numbers #0). The two "unstable" ones are statistically expected — file_table_function #12 and tpcds #92 are near-permanent unstable flaggers on this shard, and tpcds #92 actually got faster in this run (-3.6%), which contradicts a real regression. The trim_numbers and general_purpose_hashes queries share the same RecommendationA perf re-run should clear it. If it fails again with the same queries flagged, that would be evidence of a real (probably master-side, not PR-side) regression worth investigating in the trim/hash microbenchmarks. On "Two too ad-hoc changes have to be removed" — the latest commit ( — groeneai (session: cron:clickhouse-ci-task-worker:20260429-184500) |
…watermark-autotune
LLVM Coverage Report
Changed lines: 84.91% (135/159) | lost baseline coverage: 8 line(s) · Uncovered code |
|
Hello! AI comment: |
ClickBench fails on machines with only 2 GiB RAM due to several compounding memory management issues. This commit addresses them:
Auto-cap
input_format_parquet_memory_high_watermarktomax_server_memory_usage / 8. The default 4 GiB watermark causes the Parquet V3 reader to buffer far more data than available on low-memory systems. On systems with >= 32 GiB RAM this has no effect (4 GiB stays as default).Auto-cap
min_insert_block_size_bytestomax_server_memory_usage / 8in the INSERT pipeline squashing transform. The default 256 MiB accumulation threshold is too large relative to available memory on small systems.Exclude kernel memory from cgroups v2 RSS measurement. The
CgroupsV2Readerpreviously summedanon + sock + kernel, but kernel overhead (page tables, kernel stacks for hundreds of threads) is not under ClickHouse control and should not count toward the server memory limit.Ensure at least 300 MiB of absolute headroom when computing
max_server_memory_usage. The percentage-based ratio (default 0.9) leaves only 200 MiB on a 2 GiB system, insufficient for OS and jemalloc overhead.On low-memory systems (< 4 GiB), immediately set jemalloc
dirty_decay_ms=0and enable memory tracker correction. This prevents RSS inflation from jemalloc dirty page retention and memory tracker drift that cause spuriousMEMORY_LIMIT_EXCEEDEDexceptions between queries.Verified: ClickBench (100M rows from 100 Parquet files + all 43 queries) completes successfully on a 2 GiB / 1 CPU cgroup.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Improve memory usage on low-memory systems (< 4 GiB).
Version info
26.5.1.197