Skip to content

Merge Fan-In - #121955

Open
nihalzp wants to merge 30 commits into
ClickHouse:masterfrom
nihalzp:bounded-external-merge-fan-in
Open

nihalzp wants to merge 30 commits into
ClickHouse:masterfrom
nihalzp:bounded-external-merge-fan-in

Conversation

@nihalzp

@nihalzp nihalzp commented Sep 24, 2026 •

Copy link
Copy Markdown
Member

Spilling reduces memory while collecting rows, but merging thousands of temporary files can bring the memory usage back up. External sorting and external DISTINCT open every spill file for the final merge. Each reader needs buffers and a decoded block, so memory grows with the number of files. full_sorting_merge joins have the same problem when sorting their inputs.

Add a shared ExternalMergeSource that reduces the file count through intermediate merges. Each merge reads a bounded group of files and writes one replacement file. It chooses the smallest files by compressed size, then puts the replacement back into the selection. This reduces unnecessary rewriting of large files. Only enough files are merged to bring the final merge within the limit.

max_external_merge_fan_in defaults to 64; 0 keeps unlimited fan-in. The setting applies to external sorting, external DISTINCT, and sorting for full_sorting_merge joins. partial_merge joins already bounded fan-in; they now use the shared implementation with their existing join_on_disk_max_files_to_merge setting.

External sort

Sort 81,920,000 keys in 4,096-row chunks. Each chunk becomes one initial file.

SELECT cityHash64(number) AS k
FROM numbers(81920000)
ORDER BY k
SETTINGS
    max_threads = 64,
    max_block_size = 4096,
    max_bytes_before_external_sort = 1,
    max_bytes_ratio_before_external_sort = 0,
    max_memory_usage = 10737418240
FORMAT Null;
Metric Before After
Initial temporary files 20,000 20,000
Files entering the final merge 20,000 64
Elapsed time 56.20 s 14.48 s
Peak query memory 3.35 GiB 272.14 MiB

External DISTINCT

Find distinct keys among 81,920,000 rows. The threshold forces spilling from the first chunk, producing one initial file per 4,096 rows.

SELECT count()
FROM
(
    SELECT DISTINCT cityHash64(number) AS k
    FROM numbers(81920000)
)
SETTINGS
    max_threads = 64,
    max_block_size = 4096,
    max_bytes_before_external_distinct = 1,
    max_bytes_ratio_before_external_distinct = 0,
    allow_preliminary_distinct_abandoning = 1,
    max_memory_usage = 10737418240
FORMAT TSV;
Metric Before After
Initial temporary files 20,000 20,000
Files entering the final merge 20,000 64
Elapsed time 69.93 s 18.18 s
Peak query memory 3.53 GiB 205.40 MiB

External join

Join two inputs of 40,960,000 rows with full_sorting_merge. Each side produces 10,000 sorted files, for 20,000 initial files in total.

SELECT count()
FROM
(
    SELECT cityHash64(number) AS k
    FROM numbers(40960000)
) AS l
INNER JOIN
(
    SELECT cityHash64(number) AS k
    FROM numbers(40960000)
) AS r USING k
SETTINGS
    join_algorithm = 'full_sorting_merge',
    max_threads = 64,
    max_block_size = 4096,
    max_bytes_before_external_sort = 1,
    max_bytes_ratio_before_external_sort = 0,
    max_rows_in_set_to_optimize_join = 0,
    max_memory_usage = 10737418240
FORMAT TSV;
Metric Before After
Initial temporary files 20,000 20,000
Files entering the final merge 10,000 per side 64 per side
Elapsed time 30.41 s 8.04 s
Peak query memory 3.34 GiB 506.42 MiB

Changelog category (leave one):

  • Performance Improvement

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

Bound the number of temporary files merged simultaneously for external sorting, external DISTINCT, and full_sorting_merge joins with the new max_external_merge_fan_in setting, which defaults to 64. Intermediate merges choose the smallest compatible files first, reducing peak memory during merges at the cost of additional disk I/O. Set it to 0 to retain unlimited fan-in. partial_merge joins share the merge implementation and retain their existing join_on_disk_max_files_to_merge setting.


Workflow [PR]
Sync PR [sync-upstream/pr/121955]

@clickhouse-gh

clickhouse-gh Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6555451]

Summary: ❌

job_name test_name status info comment
Fast test (arm_darwin) FAIL
05238_pretty_squash_broken_pipe FAIL cidb
Stress test (amd_tsan) FAIL
ThreadSanitizer (STID: 2067-34ca) FAIL cidb

AI Review

Summary

This PR adds ExternalMergeSource to bound spill fan-in for external sorting, external DISTINCT, and sort-based joins, and it refactors the spill pipelines so intermediate merge readers and writers release their buffers before the next merge starts. The execution-side changes look reasonable overall, but the release gating around the new max_external_merge_fan_in setting is stale now that 26.10 is already cut: the setting is still serialized on the shipped query-plan version 20, and its compatibility history still claims 26.10 even though the feature can now only ship first in 26.11.

Findings
  • ❌ Blocker: [dismissed by author -- https://github.com/Merge Fan-In #121955#discussion_r4104602269] [src/Core/ProtocolDefines.h:221], [src/Core/ProtocolDefines.h:147], [src/Core/BaseSettings.h:807], [src/Processors/QueryPlan/SortingStep.cpp:212], [src/Processors/QueryPlan/DistinctStep.cpp:126], [src/Processors/QueryPlan/JoinStepLogical.cpp:2772] max_external_merge_fan_in is still keyed off query-plan version 20, but version 20 is already the shipped 26.10 wire format. New servers therefore write a setting name that older 26.10.x readers still reject as unknown, so mixed-patch 26.10.x rollouts fail distributed plans with UNKNOWN_SETTING. I still consider this real because the earlier dismissal relied on 26.10 not being released yet, and that premise no longer holds.
  • ❌ Blocker: [src/Core/Settings.cpp:4440] The SettingsChangesHistory entry still says the new default belongs to 26.10, but 26.10 is already cut, so this PR can only ship first in 26.11. Leaving the marker at 26.10 breaks the compatibility contract: on a future 26.11 build, compatibility = '26.10' will still derive max_external_merge_fan_in = 64, even though real 26.10 builds never had bounded fan-in enabled by default. Please move this entry to the first release that can actually contain the feature, together with the plan-version bump, and update the serialization/compatibility test accordingly.
Final Verdict

Needs changes before merge: bump the query-plan / compatibility release markers for max_external_merge_fan_in to the first release that can actually ship this feature, then rerun the serialization-compatibility coverage.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Sep 24, 2026
Comment thread src/Interpreters/SortedBlocksWriter.cpp Resolved
@azat azat self-assigned this Sep 24, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 65554517a with master 46dfb8152 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

172 object files changed (+387.09 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Sources/ExternalMergeSource.cpp.o new 193.34 KiB +193.34 KiB
src/CMakeFiles/dbms.dir/Processors/Transforms/ExternalDistinctTransform.cpp.o 784.76 KiB 862.54 KiB +77.78 KiB (+9.91%)
src/CMakeFiles/dbms.dir/Processors/Transforms/MergeSortingTransform.cpp.o 625.80 KiB 665.68 KiB +39.88 KiB (+6.37%)
src/CMakeFiles/dbms.dir/Interpreters/SortedBlocksWriter.cpp.o 559.90 KiB 582.23 KiB +22.33 KiB (+3.99%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

16349 translation units recompiled, 34720 s compile time in total, 15841 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×1.05 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +1584.9 s (+5%) in total before that adjustment.

Translation unit Master PR Δ vs median
contrib/aws-cmake/__/aws/generated/src/aws-cpp-sdk-s3/source/S3Client.cpp 7.0 s 14.6 s +7.2 s (+98%)
contrib/aws-cmake/__/aws/generated/src/aws-cpp-sdk-glue/source/GlueClient1.cpp 5.4 s 12.4 s +6.7 s (+117%)
contrib/aws-cmake/__/aws/generated/src/aws-cpp-sdk-glue/source/GlueClient.cpp 5.6 s 12.2 s +6.2 s (+105%)
contrib/grpc-cmake/__/grpc/src/core/lib/channel/promise_based_filter.cc 6.2 s 11.6 s +5.1 s (+79%)
contrib/grpc-cmake/__/grpc/src/core/filter/composite/composite_filter.cc 6.7 s 12.1 s +5.1 s (+72%)
contrib/grpc-cmake/__/grpc/src/core/ext/transport/chttp2/transport/http2_server_transport.cc 11.2 s 16.9 s +5.1 s (+43%)
contrib/grpc-cmake/__/grpc/src/core/ext/transport/chttp2/transport/frame_data.cc 5.5 s 10.9 s +5.1 s (+87%)

Job report

/// First global query-plan version that writes `max_external_merge_fan_in` in the step settings.
/// Zero omits the setting and preserves unlimited merging. Nonzero values require a reader that
/// knows the setting; older readers reject the unknown name before reading its value.
static constexpr auto DBMS_MIN_QUERY_PLAN_SERIALIZATION_VERSION_WITH_EXTERNAL_MERGE_FAN_IN = 20;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

QueryPlanSerializationSettings::readBinary throws on unknown setting names, so keying this on the already-shipped global plan version 20 makes new 26.10.x writers incompatible with older 26.10.x readers as soon as they serialize max_external_merge_fan_in. With the new default 64, SortingStep::Settings::updatePlanSettings and DistinctStep::Settings::updatePlanSettings emit the new name by default, and JoinStepLogical::serializeSettings now forwards the same sort settings for every serialized Join step, even when the selected join algorithm never uses full_sorting_merge. That turns mixed-patch rollouts into UNKNOWN_SETTING failures unless operators pin compatibility = '26.9' or max_external_merge_fan_in = 0 cluster-wide.

Can we keep this setting off the version-20 wire format by default (for example by deriving it from the worker's local query settings, or by postponing wire serialization until the next global plan version) instead of keying it off >= 20?

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.

Version 20 has not shipped. 26.9 announces 19, both in v26.9.1.1629-stable and at the tip of the 26.9 branch, and 26.10 has no release branch or stable tag yet. So once this is in 26.10, every 26.10.x reader knows max_external_merge_fan_in, and a mixed-patch 26.10.x rollout cannot hit UNKNOWN_SETTING. The mechanism is right: QueryPlanSerializationSettings::readBinary throws on an unknown name, and the default 64 writes it. It only matters between two development builds of the same cycle, the same as for BlocksMarshalling and legacy_join_size_limits_trigger_spilling, which also use 20.

Using 20 is what the rules above DBMS_QUERY_PLAN_SERIALIZATION_VERSION ask for: the version moves at most once per release, and a new plan setting name reuses the value of the current release. Postponing the setting to the next global version would mean either a second bump in 26.10 or leaving it out of 26.10 plans entirely. Deriving it from the worker's local query settings would split the spill settings between the plan and the worker context, while max_bytes_before_external_sort and min_free_disk_space_for_temporary_data travel with the plan. If the PR misses the 26.10 cut, I will bump the version to 21 for 26.11. I have also listed the setting under version 20 in 99f15d898d4.

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 guess now we need to increment the version

nihalzp and others added 2 commits September 25, 2026 15:34
…rge-fan-in

Resolve the conflict with the move of the settings changes history into the setting declarations
(ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as
trailing arguments of the `DECLARE` of each setting.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 31 queries analysed

No query change is attributed to this PR. One query was flagged: clickbench Q33 ran -5.6% faster (975 ms vs 1033 ms), but that falls inside master's normal range for this query. The query's history is noisy, and CPU time barely moved, so it stays at no_change. Most of the PR changes code that only runs when sorting, DISTINCT or partial-merge joins spill to disk, which these benchmark queries don't do. The pipeline executor change only alters where completed processors are released and adds profiling for them, which shouldn't change query speed.

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 3841b4b9-70e7-4996-b1db-befddd663444
  • MIRAI run: 546fcbf0-759e-40d4-a28f-f7e642ed11b6
  • PR check IDs:
    • clickbench_857907_1791712949
    • clickbench_857919_1791712949
    • clickbench_857925_1791712949
    • tpch_adapted_1_official_857931_1791712949
    • tpch_adapted_1_official_857964_1791712949
    • tpch_adapted_1_official_857978_1791712949

@nihalzp
nihalzp requested a review from azat October 11, 2026 13:25
@clickhouse-gh

clickhouse-gh Bot commented Oct 26, 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.

@azat azat self-assigned this Oct 26, 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.

In general looks ok to me, I've left few comments, please take a look before merge

/// First global query-plan version that writes `max_external_merge_fan_in` in the step settings.
/// Zero omits the setting and preserves unlimited merging. Nonzero values require a reader that
/// knows the setting; older readers reject the unknown name before reading its value.
static constexpr auto DBMS_MIN_QUERY_PLAN_SERIALIZATION_VERSION_WITH_EXTERNAL_MERGE_FAN_IN = 20;

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 guess now we need to increment the version

Comment thread src/Core/Settings.cpp
DECLARE(UInt64, max_external_merge_fan_in, 64, R"(
Limits the number of temporary files merged simultaneously for external sorting, including sorting for `full_sorting_merge` joins, and external `DISTINCT`. Any remaining in-memory run joins only the final merge and does not count toward this limit. Larger collections are reduced through intermediate merges on disk, which combine the smallest files first to minimize the amount of data rewritten.

Smaller nonzero values reduce the number of active readers but can require more disk I/O. This setting does not change the spill threshold or bound total query memory. The `partial_merge` join algorithm uses `join_on_disk_max_files_to_merge` instead.

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.

Do we really need to include "The partial_merge join algorithm uses join_on_disk_max_files_to_merge instead." here?

Comment on lines +194 to +197
return std::make_shared<MergingSortedTransform>(
header, headers.size(), description, block_size, /*max_block_size_bytes=*/ 0,
/*max_dynamic_subcolumns=*/ std::nullopt, SortingQueueStrategy::Default);
};

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.

Do we need this lambda here? Can we inline it into "final_merge"?

}

return flushToManyFiles(tmp_data, std::move(pipeline), callback);
if (headers.size() > 1)

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.

This check looks odd, maybe better to move this PE where we do spilling?


/// Completed processors no longer appear in the pipeline's final profile. Log
/// them before releasing their buffers, outside the graph's preparation locks.
if (profile_processors && !removed.empty())

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.

"logProcessorProfile" already has a check for "profile_processors", so maybe we can remove this one, and cleanup everything later

SharedHeader header, std::vector<Group> groups_, SourcePtr tail_, MergeFactory final_merge_, size_t max_fan_in_,
TemporaryDataOnDiskScopePtr tmp_data_, size_t min_free_disk_space_, LoggerPtr log_);

static size_t validateFanIn(size_t fan_in);

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.

Maybe better to move this into settings serialization?


@pytest.mark.parametrize("operation", ["sort", "distinct"])
@pytest.mark.parametrize("fan_in", [0, 2])
def test_external_merge_removed_processor_profiles(start_cluster, operation, fan_in):

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.

Can we convert this into a regular test? I don't see a reason for keeping it integration

Comment on lines +101 to +104
/// Accumulate sorted input chunks in memory. When the configured spill thresholds are exceeded,
/// merge the buffered chunks into a sorted stream and write it to a temporary file. At the end of
/// input, `ExternalMergeSource` reduces excess files through intermediate merges, then merges the
/// remaining files with the chunks still in memory. Without spill files, merge only in memory.

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 like the old style comment more, maybe we can just update it to include "ExternalMergeSource"?

Comment on lines +17 to +18
/// can retain different column layouts and duplicate-handling rules. The limit applies to file readers
/// owned by this coordinator; it does not bound total query memory or readers in other coordinators.

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.

Suggested change
/// can retain different column layouts and duplicate-handling rules. The limit applies to file readers
/// owned by this coordinator; it does not bound total query memory or readers in other coordinators.
/// can retain different column layouts and duplicate-handling rules.

This looks redundant

@clickhouse-gh clickhouse-gh Bot added the can be tested Allows running workflows for external contributors label Nov 3, 2026
Comment thread src/Core/Settings.cpp

Possible values are `0` for unlimited fan-in, or integers starting from `2`. With `0`, all temporary files enter the final merge directly, without intermediate merges.
)", 0, \
{"26.10", 0, 64, "New setting to limit the number of temporary files merged simultaneously for external sorting, including sorting for `full_sorting_merge` JOINs, and external `DISTINCT`. Any remaining in-memory run joins only the final merge and does not count toward this limit. A value of `0` preserves unlimited fan-in."}) \

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

max_external_merge_fan_in is still recorded here as a 26.10 setting, but 26.10 is already cut (there is a 26.10 release branch and a v26.10.2.103-stable tag), so this PR can now only ship first in 26.11. If this entry stays at 26.10, then compatibility = '26.10' on a future build will still derive max_external_merge_fan_in = 64, even though real 26.10 builds never had bounded fan-in enabled by default. Can we move this history entry to the first release that can actually contain the feature, together with the query-plan version bump, and update the serialization test that currently uses compatibility = '26.9'?

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants