Repository navigation
Limit max_threads and max_insert_threads based on available free memory - #100383
Conversation
Add two new settings: `max_threads_min_free_memory_per_thread` (default 1 GiB) and `max_insert_threads_min_free_memory_per_thread` (default 4 GiB). When the amount of free memory (server memory limit minus currently tracked memory) is less than N * the setting value, the number of threads is lowered to N-1, down to a minimum of 1. Setting the value to 0 disables the limit. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
Workflow [PR], commit [a6480ad] Summary: ✅ AI ReviewSummaryThis PR introduces free-memory-aware caps for ClickHouse Rules
Final Verdict
|
|
Will it fix #52254 ? |
Not yet... it will just start with the minimum number of threads (one). |
azat
left a comment
There was a problem hiding this comment.
I am not sure that it worth it, maybe we need to wait for #82414 and add support of limiting amount of threads based on available memory there? It will allow to dynamically change it (@serxa interesting what you think as well)
Now few comments about this changes itself, right now it adjust number of threads/streams in multiple places and it is hard to tell is it enough or not, maybe we can simply apply this limitations in executeQuery[Impl], though I guess it will not cover some explicit InterpreterSelectQuery (and others, i.e. for mutations), then maybe it should be in PipelineExecutor?
And it also definitely requires tests for INSERT/SELECT (analyzer and non-analyzer)
|
Of course we will not wait for a draft pull request from more than one year ago. |
|
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. |
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
The test |
|
The MSan stress test failure (MemorySanitizer: use-of-uninitialized-value, STID 4179-5154 or 4148-3044) is a known pre-existing issue unrelated to this PR. Fix: #102158 |
|
The flaky check failure is fixed in #102148, let's update the branch. |
…e-memory # Conflicts: # src/Interpreters/InterpreterSelectWithUnionQuery.cpp
Window planning in `Planner::addWindowSteps` and `InterpreterSelectQuery::executeWindow` decided whether to reshuffle streams between windows based on the raw `settings[Setting::max_threads] != 1` check. When the free-memory limiter reduces the effective thread cap to `1` while `max_threads` is configured higher, the multi-thread branch was still taken and could add an unnecessary `SortingStep` between windows with different `partition_by` cardinality - exactly the memory-heavy work the limiter is meant to avoid. Use `getMaxThreadsForAvailableMemory` to derive the effective thread count for this decision on both the analyzer and the legacy interpreter paths.
The previous review was based on forward-looking statements, making it impractical with regard to the changes in this PR.
|
@azat, when the new scheduler (memory reservations) will be ready, we will use it instead of these settings; in the meantime, these settings look like a small and natural thing to have. |
|
To be honest I think this is an orthogonal features and we can have both of them. With workload scheduler we can also have these or similar settings per workload. Current memory reservations implementation does not provide any features for "elasticity". Instead it either blocks or kills queries. |
LLVM Coverage Report
Changed lines: 99.38% (159/160) | lost baseline coverage: 5 line(s) · Uncovered code |
…ree-memory limiter The test exercises `EXPLAIN PIPELINE` with `max_threads=32` and asserts the resulting pipeline contains `Resize 16 → 32`. Since ClickHouse#100383 (`Limit max_threads and max_insert_threads based on available free memory`), `max_threads` is trimmed when free memory is below `max_threads_min_free_memory_per_thread` (default 1 GiB) per requested thread. On `Stateless tests (amd_llvm_coverage_per_test, per_test_coverage, 7/8)` the per-test coverage instrumentation reduces available memory, so the limiter clamps the requested 32 threads to ~24 and the test fails: ``` - Resize 16 → 32 - MergeTreeSelect(pool: ReadPool, algorithm: Thread) × 16 0 → 1 + Resize 16 → 24 + MergeTreeSelect(pool: ReadPool, algorithm: Thread) × 16 0 → 1 ``` Disable both `max_threads_min_free_memory_per_thread` and `max_insert_threads_min_free_memory_per_thread` in the test SET block so the requested thread count is preserved regardless of concurrent memory pressure. Same fix pattern applied to `02343_aggregation_pipeline.sql` in the original PR (commit de505d1). The test had its last master failure on the wave introduced by ClickHouse#100383 on 2026-05-02 03:55 UTC, ~4 hours after ClickHouse#100383 merged on 2026-05-01 23:22 UTC. CIDB shows 10 master hits in the 14-day window since, all on `per_test_coverage`. The related auto-generated `Flaky test` issue ClickHouse#101657 covers an older failure mode that was fixed by ClickHouse#102818; this PR addresses a separate failure mode introduced by ClickHouse#100383. **Reproduction (deterministic):** ```bash PATH=build/programs:$PATH \ CLICKHOUSE_CLIENT_OPT='--max_threads_min_free_memory_per_thread=24000000000 --max_insert_threads_min_free_memory_per_thread=24000000000' \ tests/clickhouse-test 02493_max_streams_for_merge_tree_reading ``` Without the fix the test fails with `Resize 4 → 4` instead of `Resize 16 → 32` (same failure shape as CI). With the fix it passes 10/10 runs with the limiter injected and 50/50 runs without it. CI failure example: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=bbf2861532b8871fbc0e3d7d3362e1f0e3fabf3f&name_0=NightlyCoverage&name_1=Stateless%20tests%20%28amd_llvm_coverage_per_test%2C%20per_test_coverage%2C%207%2F8%29 PR introducing the regression: ClickHouse#100383 Co-Authored-By: Claude Opus 4.7 <[email protected]>
|
Hello! AI comment: |
| For ClickHouse Cloud users, the default value will display as `auto(N)` where N matches the vCPU size of your service e.g. 2vCPU/8GiB, 4vCPU/16GiB etc. | ||
| See the settings tab in the Cloud console for a list of all service sizes. | ||
| )", 0) \ | ||
| DECLARE(UInt64, max_threads_min_free_memory_per_thread, 1_GiB, R"( |
There was a problem hiding this comment.
BTW I think default is not good, since now it will likely lead to unexpected "performance degradation", consider lower it (maybe 100MiB)
And also we definitely need some logs in case of the number of threads was lowered in "getMaxThreadsForAvailableMemory"
There was a problem hiding this comment.
… under free-memory limiter The test exercises `EXPLAIN PIPELINE INSERT INTO ... SELECT` with `max_insert_threads=8` and asserts that the resulting pipeline contains exactly 8 sinks. Since #100383 (`Limit max_threads and max_insert_threads based on available free memory`), `max_insert_threads` is trimmed when the server has less than `max_insert_threads_min_free_memory_per_thread` (default 4 GiB) of free memory per requested thread. In `Stateless tests (amd_llvm_coverage_per_test, per_test_coverage, 8/8)` the per-test coverage instrumentation reduces available memory, so the limiter clamps the requested 8 threads to 5–7 and the test fails: ``` - inserting into a remote table from local with concurrency equal to max_insert_threads - 8 + 5 ``` Pass `--max_threads_min_free_memory_per_thread=0` and `--max_insert_threads_min_free_memory_per_thread=0` on every `clickhouse-client` invocation in the test so the requested `max_insert_threads=8` is preserved regardless of concurrent memory pressure. Same fix pattern applied to `02343_aggregation_pipeline.sql` in the original PR. Reproduced locally by injecting `--max_threads_min_free_memory_per_thread=24000000000` `--max_insert_threads_min_free_memory_per_thread=24000000000` into `CLICKHOUSE_CLIENT_OPT`: before the fix the test fails with 4 sinks instead of 8; after the fix it passes 50/50 runs both with and without the injected throttle. CI failure example: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=8eaaf96ca45fffc4f228cc8892660bd20e9f4b99&name_0=NightlyCoverage&name_1=Stateless%20tests%20%28amd_llvm_coverage_per_test%2C%20per_test_coverage%2C%208%2F8%29
…s clamp test Under memory pressure (per_test_coverage and other memory-constrained builds) getMaxThreadsForAvailableMemory clamps the effective max_threads down to 1. At max_threads = 1 the async read branch no longer amplifies requested_num_streams, so a build missing the clamp would false-pass instead of hitting the old pipes.reserve std::length_error. Disable the free-memory limiter in the test, the same guard 02493_max_streams_for_merge_tree_reading uses (see PR ClickHouse#100383). Co-Authored-By: Claude Opus 4.8 <[email protected]>
… under free-memory limiter The test exercises `EXPLAIN PIPELINE INSERT INTO ... SELECT` with `max_insert_threads=8` and asserts that the resulting pipeline contains exactly 8 sinks. Since ClickHouse#100383 (`Limit max_threads and max_insert_threads based on available free memory`), `max_insert_threads` is trimmed when the server has less than `max_insert_threads_min_free_memory_per_thread` (default 4 GiB) of free memory per requested thread. In `Stateless tests (amd_llvm_coverage_per_test, per_test_coverage, 8/8)` the per-test coverage instrumentation reduces available memory, so the limiter clamps the requested 8 threads to 5–7 and the test fails: ``` - inserting into a remote table from local with concurrency equal to max_insert_threads - 8 + 5 ``` Pass `--max_threads_min_free_memory_per_thread=0` and `--max_insert_threads_min_free_memory_per_thread=0` on every `clickhouse-client` invocation in the test so the requested `max_insert_threads=8` is preserved regardless of concurrent memory pressure. Same fix pattern applied to `02343_aggregation_pipeline.sql` in the original PR. Reproduced locally by injecting `--max_threads_min_free_memory_per_thread=24000000000` `--max_insert_threads_min_free_memory_per_thread=24000000000` into `CLICKHOUSE_CLIENT_OPT`: before the fix the test fails with 4 sinks instead of 8; after the fix it passes 50/50 runs both with and without the injected throttle. CI failure example: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=8eaaf96ca45fffc4f228cc8892660bd20e9f4b99&name_0=NightlyCoverage&name_1=Stateless%20tests%20%28amd_llvm_coverage_per_test%2C%20per_test_coverage%2C%208%2F8%29
Add two new settings:
max_threads_min_free_memory_per_thread(default 1 GiB) andmax_insert_threads_min_free_memory_per_thread(default 4 GiB).When the amount of free memory (server memory limit minus currently tracked memory) is less than N * the setting value, the number of threads is lowered to N-1, down to a minimum of 1. Setting the value to 0 disables the limit.
This helps prevent OOM situations when the server is already under memory pressure, by automatically reducing parallelism instead of starting queries that are likely to fail or cause memory limit exceptions.
The limiter is applied consistently to read-side parallelism (
SELECT,UNION,INTERSECT/EXCEPT) and toINSERT(including theSELECTside of trivialINSERT ... SELECT).Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Add
max_threads_min_free_memory_per_threadandmax_insert_threads_min_free_memory_per_threadsettings to automatically reduce query parallelism when the server is low on free memory.Documentation entry for user-facing changes
New settings:
max_threads_min_free_memory_per_thread(default 1 GiB): if free memory is less thanmax_threads * value, threads are reduced to fit. Set to 0 to disable.max_insert_threads_min_free_memory_per_thread(default 4 GiB): same for insert threads. Set to 0 to disable.Free memory is calculated as the server's
max_server_memory_usageminus the currently tracked memory by the global memory tracker. The settings are documented in the auto-generated session settings reference via theirDECLAREblocks insrc/Core/Settings.cpp, which populatesdocs/en/operations/settings/settings.md.Version info
26.5.1.240