Skip to content

Limit max_threads and max_insert_threads based on available free memory - #100383

Merged
alexey-milovidov merged 39 commits into
masterfrom
max-threads-min-free-memory
May 1, 2026
Merged

alexey-milovidov merged 39 commits into
masterfrom
max-threads-min-free-memory

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Mar 22, 2026 •

Copy link
Copy Markdown
Member

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.

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 to INSERT (including the SELECT side of trivial INSERT ... SELECT).

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Add max_threads_min_free_memory_per_thread and max_insert_threads_min_free_memory_per_thread settings to automatically reduce query parallelism when the server is low on free memory.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

New settings:

  • max_threads_min_free_memory_per_thread (default 1 GiB): if free memory is less than max_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_usage minus the currently tracked memory by the global memory tracker. The settings are documented in the auto-generated session settings reference via their DECLARE blocks in src/Core/Settings.cpp, which populates docs/en/operations/settings/settings.md.

Version info

  • Merged into: 26.5.1.240

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

clickhouse-gh Bot commented Mar 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a6480ad]

Summary: ✅


AI Review

Summary

This PR introduces free-memory-aware caps for max_threads and max_insert_threads via new settings, then propagates the effective capped thread count through legacy interpreter and analyzer planner paths (SELECT, UNION, INTERSECT/EXCEPT, INSERT ... SELECT, aggregation, JOIN, and window reshuffle decisions), with accompanying stateless test coverage and updates to deterministic tests affected by the new default behavior. I did not find additional high-confidence issues beyond already-reported inline bot findings.

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ✅
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ✅
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Mar 22, 2026
Comment thread src/Core/SettingsChangesHistory.cpp Resolved
@qoega

qoega commented Mar 23, 2026

Copy link
Copy Markdown
Member

Will it fix #52254 ?

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

Copy link
Copy Markdown
Member Author

Will it fix #52254 ?

Not yet... it will just start with the minimum number of threads (one).
I'd prefer to add the throwing behavior later.

@azat azat self-assigned this Mar 31, 2026
azat
azat previously requested changes Apr 1, 2026

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

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Of course we will not wait for a draft pull request from more than one year ago.

@alexey-milovidov alexey-milovidov mentioned this pull request Apr 4, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

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

Copy link
Copy Markdown
Member Author

The test 02859_replicated_db_name_zookeeper is fixed in #101952

@alexey-milovidov

Copy link
Copy Markdown
Member Author

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

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The flaky check failure is fixed in #102148, let's update the branch.

Comment thread src/Core/Settings.cpp Resolved
Comment thread src/Planner/Planner.cpp Resolved
…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.
@alexey-milovidov
alexey-milovidov requested a review from azat May 1, 2026 08:34
@alexey-milovidov
alexey-milovidov dismissed azat’s stale review May 1, 2026 08:35

The previous review was based on forward-looking statements, making it impractical with regard to the changes in this PR.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

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

@serxa

serxa commented May 1, 2026

Copy link
Copy Markdown
Member

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.

@clickhouse-gh

clickhouse-gh Bot commented May 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 99.38% (159/160) | lost baseline coverage: 5 line(s) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue May 1, 2026
@alexey-milovidov alexey-milovidov self-assigned this May 1, 2026
Merged via the queue into master with commit 54b6446 May 1, 2026
165 checks passed
@alexey-milovidov
alexey-milovidov deleted the max-threads-min-free-memory branch May 1, 2026 23:35
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 2, 2026
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request May 12, 2026
…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]>
@PedroTadim

Copy link
Copy Markdown
Member

Hello! AI comment:

The PR introduces new default limits (1 GiB and 4 GiB per thread) that will automatically reduce concurrency on memory-constrained servers. This is gracefully handled for existing users via 'SettingsChangesHistory.cpp' (compatibility value is 0), but new clusters might experience lower parallelism than expected under memory pressure.

Comment thread src/Core/Settings.cpp
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"(

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.

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"

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.

@alexey-milovidov alexey-milovidov added the memory When memory usage is higher than expected label Jun 4, 2026
alexey-milovidov pushed a commit that referenced this pull request Jun 26, 2026
… 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
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 18, 2026
…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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
… 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
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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants