Repository navigation
Limit simultaneously active streams in UNION ALL to reduce peak memory - #100176
Conversation
A UNION ALL query with many branches opens read buffers for all branches simultaneously, causing memory proportional to num_branches × num_columns × buffer_size. With ~100 branches on a wide table this easily reaches 10+ GB for no good reason. Add two settings that narrow the `UnionStep` pipeline via `ConcatProcessor`s so that only a bounded number of streams are active at once: - `max_streams_for_union_step` (UInt64, default 0): absolute limit - `max_streams_for_union_step_to_max_threads_ratio` (Float, default 8): ratio × `max_threads` gives a dynamic limit The actual limit is min(absolute, ratio×threads); either being 0 means it is ignored; both 0 disables narrowing entirely. Closes #23245 Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
Workflow [PR], commit [37e9a1b] Summary: ✅ AI ReviewSummaryThis PR introduces Missing context
ClickHouse Rules
Final Verdict
|
…_ratio` Replace unsafe `static_cast<size_t>(double)` with `canConvertTo<size_t>` check and `PARAMETER_OUT_OF_BOUND` exception for negative or out-of-range ratio values. This mirrors the existing safe conversion pattern used for `max_streams_to_max_threads_ratio` in `InterpreterSelectQuery`. #100176 (review) Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
| UnionStep::UnionStep(SharedHeaders input_headers_, size_t max_threads_) | ||
| UnionStep::UnionStep(SharedHeaders input_headers_, size_t max_threads_, size_t max_streams_) | ||
| : max_threads(max_threads_) | ||
| , max_streams(max_streams_) |
There was a problem hiding this comment.
UnionStep now has new behavioral state (max_streams), but step serialization still writes nothing and deserialize reconstructs UnionStep(ctx.input_headers) with default limits. That means serialized query plans can silently lose the stream cap and run with a different memory profile than the original plan.
Please persist max_threads and max_streams in UnionStep::serialize / UnionStep::deserialize (with backward-compatible defaults for older payloads if needed).
Previously `UnionStep::serialize` discarded both fields, so serialized query plans (e.g. for distributed execution) would lose the stream cap and revert to unlimited concurrency, negating the memory savings. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The previous commit changed `UnionStep` serialization from empty to writing `max_threads` and `max_streams`. This is a format-breaking change: an older node would misparse the extra bytes. Bumping the global plan-serialization version ensures older nodes reject plans they cannot decode. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The previous approach wrote `max_threads` and `max_streams` directly in `UnionStep::serialize` and bumped `DBMS_QUERY_PLAN_SERIALIZATION_VERSION` from 0 to 1. This breaks backward compatibility during rolling upgrades: - Old→New: an old server sends a v0 plan without these fields, the new server tries to read them and corrupts the stream. - New→Old: the version is negotiated to 0 but `UnionStep::serialize` still writes the fields, which the old deserializer skips, corrupting subsequent step data. The per-step `serialize`/`deserialize` methods do not receive the plan version, so they cannot conditionally include new fields. Fix by using `QueryPlanSerializationSettings` instead — it writes only changed settings as name-value pairs and is naturally backward compatible (unknown settings are ignored by old servers, missing settings use defaults on new servers). Revert the version bump back to 0. #100176 Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
| DECLARE(Bool, serialize_string_in_memory_with_zero_byte, true, "Serialize String values during aggregation with zero byte at the end. Enable to keep compatibility when querying cluster of incompatible versions.", 0) \ | ||
| DECLARE(Bool, use_hash_table_stats_for_join_reordering, false, "Enable using collected hash table statistics for cardinality estimation during join reordering", 0) \ | ||
| \ | ||
| DECLARE(UInt64, max_streams_for_union_step, 0, "Limits the number of simultaneously active data streams in a UNION ALL step via ConcatProcessors. 0 means no narrowing.", 0) \ |
There was a problem hiding this comment.
❌ This adds a new serialized query-plan setting while DBMS_QUERY_PLAN_SERIALIZATION_VERSION is still 0.
QueryPlan::deserialize reads step settings via BaseSettings::readBinary, which throws UNKNOWN_SETTING for unknown names. So when max_streams_for_union_step is non-default (which is common because ratio default is 8), older servers will fail to deserialize version-0 plans with an exception.
Please make this format evolution explicit: either bump/handle query-plan serialization version compatibility for this new setting, or ensure this setting is not emitted to peers that do not support it.
| SELECT 4 | ||
| SETTINGS max_threads = 4, max_streams_for_union_step = 2, max_streams_for_union_step_to_max_threads_ratio = 0; | ||
|
|
||
| -- 2. Default ratio = 1, max_threads = 2 narrows 4 branches to 2 streams |
There was a problem hiding this comment.
💡 Typo in comment: this says "Default ratio = 1", but the setting default is 8 (max_streams_for_union_step_to_max_threads_ratio).
Suggestion: change the wording to "Ratio = 1" (or explicitly "Set ratio = 1") to avoid confusion.
| UNION ALL SELECT 4 | ||
| UNION ALL SELECT 5 | ||
| ) | ||
| SETTINGS max_streams_for_union_step = 0, max_streams_for_union_step_to_max_threads_ratio = 0; |
There was a problem hiding this comment.
Please add at least one negative/out-of-range case (e.g. max_streams_for_union_step_to_max_threads_ratio = -1) and assert PARAMETER_OUT_OF_BOUND. That would prevent regressions in both InterpreterSelectWithUnionQuery and planner-based paths.
Fix misleading "Default ratio = 1" comment (the default is 8, the test sets it to 1). Add test case for negative `max_streams_for_union_step_to_max_threads_ratio` expecting `PARAMETER_OUT_OF_BOUND`. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
| "Invalid value for `max_streams_for_union_step_to_max_threads_ratio`. " | ||
| "Make sure that `max_threads * max_streams_for_union_step_to_max_threads_ratio` is in some reasonable boundaries, current value: {}", | ||
| streams_from_ratio); | ||
| size_t max_streams_from_ratio = static_cast<size_t>(streams_from_ratio); |
There was a problem hiding this comment.
max_streams_for_union_step_to_max_threads_ratio can silently become ineffective for small positive values.
Here, max_streams_from_ratio is computed with truncation (static_cast<size_t>). For example, with max_threads = 8 and ratio 0.1, the product is 0.8, truncates to 0, and then this branch treats ratio-based limit as disabled (max_streams = 0 when absolute limit is also 0).
That contradicts the setting semantics (0 is documented as the explicit disable value). Please either clamp positive ratios to at least 1 stream, or throw PARAMETER_OUT_OF_BOUND when 0 < max_threads * ratio < 1.
Please apply the same fix in both InterpreterSelectWithUnionQuery and Planner paths.
When `max_threads * max_streams_for_union_step_to_max_threads_ratio` produces a small positive value (e.g. 0.8), `static_cast<size_t>` would truncate it to 0, silently disabling the ratio-based stream limit. Now positive products below 1 are clamped to 1 so the limit stays active. Added test case for this edge case (ratio = 0.5, max_threads = 1). Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
|
||
| void UnionStep::serializeSettings(QueryPlanSerializationSettings & settings) const | ||
| { | ||
| settings[QueryPlanSerializationSetting::max_streams_for_union_step] = max_streams; |
There was a problem hiding this comment.
UnionStep now serializes only the already-computed absolute max_streams value, but that value was derived from max_threads * max_streams_for_union_step_to_max_threads_ratio on the initiator side.
On deserialization, max_threads is reset to 0 and only this absolute cap is reused, so remote execution no longer recomputes the ratio from the remote node's max_threads. In heterogeneous clusters (or when max_threads is left as auto), this can make the ratio semantics drift across nodes and either over- or under-limit UNION concurrency.
Could we serialize the ratio input (or recompute from settings on deserialize) instead of persisting only the derived absolute cap?
… in `UnionStep` Move the `max_streams` computation from `InterpreterSelectWithUnionQuery` and `Planner` into `UnionStep::updatePipeline`. Now `UnionStep` stores and serializes the raw `max_streams_for_union_step` and `max_streams_for_union_step_to_max_threads_ratio` settings, and computes the effective limit at pipeline build time using the local `max_threads`. This ensures that in distributed execution the remote node recomputes the ratio-based limit using its own `max_threads`, rather than inheriting a pre-computed value from the coordinator. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
| size_t effective_max_streams = max_streams; | ||
| if (max_streams_ratio > 0 && new_max_threads > 0) | ||
| { | ||
| size_t max_streams_from_ratio = static_cast<size_t>(static_cast<double>(new_max_threads) * max_streams_ratio); |
There was a problem hiding this comment.
max_streams_for_union_step_to_max_threads_ratio is only checked for < 0 in planning paths, so non-finite values (nan, inf) can still reach this code. Here we convert new_max_threads * max_streams_ratio to size_t via static_cast; if the product is non-finite or larger than size_t range, this conversion is undefined behavior.
Please validate the ratio with isFinite and use checked conversion (canConvertTo<size_t>) before casting, throwing PARAMETER_OUT_OF_BOUND for invalid/out-of-range values.
| {"use_statistics_for_part_pruning", false, true, "New setting to use statistics for part pruning during query execution."}, | ||
| {"distributed_index_analysis_only_on_coordinator", false, false, "New setting."}, | ||
| {"max_streams_for_union_step", 0, 0, "New setting to limit the number of simultaneously active data streams in a UNION ALL step to reduce peak memory usage."}, | ||
| {"max_streams_for_union_step_to_max_threads_ratio", 0, 8, "New setting: ratio applied to max_threads to compute the default max_streams_for_union_step when that setting is 0."}, |
There was a problem hiding this comment.
The description here is slightly inconsistent with runtime behavior: max_streams_for_union_step_to_max_threads_ratio is still applied when max_streams_for_union_step is non-zero (effective limit is min(max_streams_for_union_step, max_threads * ratio)).
Current wording says it computes the default only when max_streams_for_union_step is 0, which can mislead users during compatibility rollouts.
Could you reword this entry to reflect the min(...) semantics explicitly?
…ueryPipelineSettings` Move `max_streams_for_union_step` and `max_streams_for_union_step_to_max_threads_ratio` from `UnionStep` state into `BuildQueryPipelineSettings`, as suggested by the reviewer. This removes the need for query-plan serialization settings for these values: `UnionStep::updatePipeline` now reads them directly from the `BuildQueryPipelineSettings` argument at pipeline-build time. Remote nodes read the settings from their own Context, which matches how distributed query settings are already propagated. Remove the corresponding `serializeSettings` override and the two `QueryPlanSerializationSettings` entries. Validation (`isFinite`, non-negative) is consolidated in `UnionStep::updatePipeline` where the values are actually used. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`narrowPipe` shuffles its input-to-output distribution, so the EXPLAIN PIPELINE output for an uneven 4 → 3 narrowing renders with the IO ports of an arbitrary `Concat` in the group. Use 6 branches so the narrowing produces a stable 2,2,2 split. Also, the Float setting parser rejects `inf`/`nan` before `UnionStep::updatePipeline` runs, so those cases must use `clientError CANNOT_PARSE_NUMBER` instead of `serverError PARAMETER_OUT_OF_BOUND`. The `isFinite` guard is still useful as defense in depth for the distributed serialization path. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Test `02995_new_settings_history` compares against the 26.4.1 baseline and only accepts entries from versions strictly newer than 26.4. The new `max_streams_for_union_step` and `max_streams_for_union_step_to_max_threads_ratio` settings were recorded under "26.4", so the test reported them as missing. Move both entries to the "26.5" block so the test recognises them. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100176&sha=7bda36894b645c41c17f09f8552d6bb76873e5e8&name_0=PR PR: #100176
| "Invalid value for `max_streams_for_union_step_to_max_threads_ratio`: {}. Must be a finite non-negative number.", | ||
| max_streams_ratio); | ||
|
|
||
| size_t effective_max_streams = settings.max_streams_for_union_step; |
There was a problem hiding this comment.
UnionStep::updatePipeline now reads max_streams_for_union_step* directly from BuildQueryPipelineSettings, so the cap is applied to every UnionStep, not only SQL UNION planning paths.
This broadens behavior compared to earlier revisions in this PR: call sites like ClusterProxy::executeQuery and StorageBuffer create UnionStep for non-UNION query plumbing, and they now get throttled too when users tune these settings for UNION ALL memory control.
Can we scope this cap to SQL UNION only (e.g. keep per-step fields initialized by InterpreterSelectWithUnionQuery/Planner, defaulting to 0 for other call sites), or otherwise explicitly document and test the widened scope?
| @@ -0,0 +1,112 @@ | |||
| -- Test that max_streams_for_union_step and max_streams_for_union_step_to_max_threads_ratio | |||
There was a problem hiding this comment.
UNION ALL and UNION DISTINCT, but the new test only exercises UNION ALL plans/results.
Please add at least one UNION DISTINCT case (preferably EXPLAIN PIPELINE + a correctness query) to ensure this narrowing logic remains wired through the UNION DISTINCT path and does not regress silently.
…y-usage # Conflicts: # src/Disks/DiskObjectStorage/DiskObjectStorage.cpp
Adds correctness checks that exercise `UNION DISTINCT` with `max_streams_for_union_step` and `max_streams_for_union_step_to_max_threads_ratio`, to ensure the narrowing logic stays wired through the `UnionStep` -> `DistinctStep` path and does not regress silently. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The cap was applied to every `UnionStep::updatePipeline`, but `UnionStep` is also created by `ClusterProxy::executeQuery`, `StorageBuffer`, `MergeTask`, and several projection optimizations as a plumbing primitive. Narrowing those through `narrowPipe` (which inserts `ConcatProcessor` and shuffles streams with `thread_local_rng`) breaks ordering invariants of downstream transforms such as `GroupingAggregatedTransform` for memory-efficient distributed aggregation, manifesting as a result mismatch in `00171_grouping_aggregated_transform_bug` under randomized `max_threads = 1` and `group_by_two_level_threshold_bytes = 1`. Add a per-step `is_sql_union` flag (default `false`) to `UnionStep` and set it `true` only in `InterpreterSelectWithUnionQuery::buildQueryPlan` and `Planner::buildPlanForUnionNode`. The flag is preserved by the `filterPushDown` and `liftUpUnion` optimizations that rebuild `UnionStep`. The settings remain in `BuildQueryPipelineSettings`, so no `QueryPlanSerializationSetting` is introduced. Add `04141_max_streams_for_union_step_distributed` covering the distributed `remote()` path with the cap set, ensuring the cap does not affect correctness of memory-efficient distributed aggregation. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100176&sha=b20d134b8142edec67908336ece1ca560169834f&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29
| @@ -0,0 +1,134 @@ | |||
| -- Test that max_streams_for_union_step and max_streams_for_union_step_to_max_threads_ratio | |||
There was a problem hiding this comment.
Given that UnionStep behavior now depends on SQL-vs-non-SQL scope state, please add a regression test that runs a SQL UNION query through query-plan serialization and verifies the stream cap is still applied after deserialization.
Style check enforces that abbreviations such as SQL must be in all caps (`SQL`, not `Sql`). Rename the accessor on `UnionStep` accordingly. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100176&sha=c5e2810a2fc12cece680c8f64f7980ad69973b0d&name_0=PR&name_1=Style%20check Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
LLVM Coverage Report
Changed lines: 93.33% (70/75) · Uncovered code |
|
Hello! Performance tests missing? |
Drop two randomization adds from this PR that need additional groundwork to ship safely, and revert the seven test files that needed `-- Tags: no-random-settings` because of them: * `max_streams_for_union_step` and `max_streams_for_union_step_to_max_threads_ratio` (ClickHouse#100176) — reshape the `UNION ALL` pipeline, which surfaced pre-existing weak-ordering invariants in 8 tests (constant ORDER BY keys, NaN sort keys from `sin(0/0)`, `ORDER BY tuple()`, duplicate values without secondary sort). The dedicated `04051_max_streams_for_union_step` test also failed in a way suggesting randomized session-level values bypass per-query `SETTINGS` for these settings — a separate interaction worth investigating first. * Pairing `max_bytes_ratio_before_external_join` with `max_bytes_before_external_join` in `randomize_external_sort_group_by` using the same `threshold_generator(0.3, 0.5, 0, 10 GiB)` as sort/group_by — caused `03279_join_choose_build_table` to fail at `--max_bytes_before_external_join 7693351` (grace hash join returned 500/125 rows instead of 1000). That smells like a real correctness issue in grace hash join under spilling. Restore upstream's standalone `max_bytes_before_external_join: random.choice([0, 1000000000])` (binary off / 1 GiB, never spills) and drop the ratio randomization for now. What stays in this PR: * `optimize_dictget_tuple_element` (ClickHouse#100186) * `use_top_k_dynamic_filtering_for_variable_length_types` (ClickHouse#104216) with conditional_settings parent * `page_cache_max_coalesced_bytes` (ClickHouse#104230) * re-enable `grace_hash_join_initial_buckets` randomization with the narrow, previously-working `[1, 2, 4, 8]` range CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=105630&sha=6f3e784ddf7&name_0=PR Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
QA notes on recent PRs flagged that the following settings were introduced but not added to the randomization list in `tests/clickhouse-test`: * `max_bytes_ratio_before_external_join` (ClickHouse#103862) — mirrors the existing `max_bytes_ratio_before_external_group_by` and `max_bytes_ratio_before_external_sort`, so wire it through the Bytes-vs-Ratio choice in `randomize_external_sort_group_by` alongside its absolute counterpart `max_bytes_before_external_join`. * `max_streams_for_union_step` and `max_streams_for_union_step_to_max_threads_ratio` (ClickHouse#100176) — occasionally clamp to a small number of simultaneously active streams to exercise the `UNION ALL` narrowing path. * `optimize_dictget_tuple_element` (ClickHouse#100186) — default-true; disable with a small probability so both planner paths stay covered. * `use_top_k_dynamic_filtering_for_variable_length_types` (ClickHouse#104216) — cover both the fixed-length-only default and the opt-in path. * `page_cache_max_coalesced_bytes` (ClickHouse#104230) — randomize across small/large values so the coalescing path and the cap that splits long miss runs into multiple reads both get exercised. Also re-enable randomization of `grace_hash_join_initial_buckets`, which had been disabled in `tests/clickhouse-test` after wrong results on some tests. Restore the original conservative range `[1, 2, 4, 8]`. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
A UNION ALL query with many branches opens read buffers for all branches simultaneously, causing memory proportional to num_branches × num_columns × buffer_size. With ~100 branches on a wide table this easily reaches 10+ GB for no good reason.
Add two settings that narrow the
UnionSteppipeline viaConcatProcessors so that only a bounded number of streams are active at once:max_streams_for_union_step(UInt64, default 0): absolute limitmax_streams_for_union_step_to_max_threads_ratio(Float, default 8): ratio ×max_threadsgives a dynamic limitThe actual limit is min(absolute, ratio×threads); either being 0 means it is ignored; both 0 disables narrowing entirely.
Closes #23245
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Limit simultaneously active streams in UNION ALL to reduce peak memory usage.
Version info
26.5.1.199