Skip to content

Reduce unnecessary spilling and memory usage in external DISTINCT - #121772

Merged
nihalzp merged 31 commits into
ClickHouse:masterfrom
nihalzp:external-distinct-improvements
Oct 1, 2026
Merged

nihalzp merged 31 commits into
ClickHouse:masterfrom
nihalzp:external-distinct-improvements

Conversation

@nihalzp

@nihalzp nihalzp commented Sep 23, 2026 •

Copy link
Copy Markdown
Member

Related: #116569

Use these common settings for the queries below.

SET max_threads = 16;
SET max_memory_usage = 4294967296;
SET max_bytes_ratio_before_external_distinct = 0;
SET optimize_distinct_in_order = 0;

Improvement 1: Avoid spilling when incoming rows are already in the set

DISTINCT estimates hash-table growth as if every incoming row added a new key. When the table is close to needing a larger buffer, even a chunk containing only existing keys can trigger spilling.

The common path still inserts the whole chunk when its estimate fits. Otherwise, each key is looked up first, and memory is checked only before inserting a missing key. The check also reserves the temporary memory needed to start spilling. Processing stops before the first insertion that cannot fit, and the remaining input goes through the spill path.

SELECT count()
FROM
(
    SELECT DISTINCT
        toUInt8((number % 524287) % 251) AS a,
        toUInt64(number % 524287) AS b
    FROM numbers(4000000)
)
SETTINGS
    max_block_size = 65536,
    max_bytes_before_external_distinct = 100663296;
max_threads Time before → after Peak memory before → after
16 274.33 → 51.00 ms 36.26 → 28.32 MiB
64 275.33 → 50.67 ms 36.26 → 28.32 MiB

Elapsed time falls by about 81% at both thread limits, and peak memory falls by 22%. The query goes from one spill file to no spilling.

Improvement 2: Reduce memory held by spill readers

During a merge, each temporary-file reader keeps a decompressed block in memory. Limiting blocks only by row count can leave hundreds of MiB in each reader when rows are wide.

MergeSorter now uses prefer_external_sort_block_bytes and average row size to choose how many rows to write per block. This applies to new rows, keys already returned during hashing, and the sort that restores input order. Previously returned keys are stored to prevent them from being returned again after the spill. The byte target is approximate and does not cap total merge memory.

SELECT count(), sum(length(payload))
FROM
(
    SELECT DISTINCT
        cityHash64(number) AS k,
        repeat('x', if(number % 8 = 0, 8192, 32)) AS payload
    FROM numbers(524288)
)
SETTINGS
    max_block_size = 65536,
    max_bytes_before_external_distinct = 67108864,
    prefer_external_sort_block_bytes = 1048576;
max_threads Time before → after Peak memory before → after
16 660.33 → 512.67 ms 1518.07 → 223.86 MiB
64 671.33 → 515.33 ms 1518.07 → 223.86 MiB

Peak memory falls by 85%, and elapsed time by 22–23%. Both versions write eight files; compressed spill bytes increase by about 2% for this query.

Improvement 3: Make room for spill readers before the final merge

When input ends, external DISTINCT can still hold sorted chunks in memory. Keeping this tail while opening every spill file adds the readers' decoded blocks and buffers to the retained columns, which can exceed the query memory limit.

Before merging, estimate the memory needed by the file readers and output blocks. Keep the tail when current query memory plus this estimate fits max_bytes_before_external_distinct. Otherwise, spill a prefix of whole chunks in arrival order, wait for its writer to finish, and reassess the remaining suffix. Preserving arrival order keeps the first row's payload for equal keys.

SELECT count(), sum(length(payload))
FROM
(
    SELECT DISTINCT
        cityHash64(number) AS k,
        repeat(toString(number % 10), 128) AS payload
    FROM numbers(1900000)
)
SETTINGS
    max_threads = 16,
    max_block_size = 4096,
    max_memory_usage = 4294967296,
    max_untracked_memory = 0,
    max_bytes_before_external_distinct = 33554432,
    prefer_external_sort_block_bytes = 1048576,
    allow_preliminary_distinct_abandoning = 1;
max_threads Time before → after Peak memory before → after
16 703.67 → 701.00 ms 76.75 → 61.78 MiB
64 711.67 → 698.00 ms 76.75 → 61.78 MiB

Both versions return a row count of 1900000 and a total payload length of 243200000 bytes. Peak memory falls by about 20%, while elapsed time is similar at both thread limits. The candidate spills all 48,608 tail rows in this case; total spill files increase from 9 to 13, and compressed spill bytes increase by about 12%. The memory benefit depends on how much tail remains when input ends.

The spill threshold remains a soft limit because the readers alone can exceed it after the whole tail is spilled. Separate correctness tests exercise keeping the entire tail, spilling only a prefix, empty tails, and preserving the first payload and input order.

Improvement 4: Keep constant payloads as a single value

Expanding a constant payload into one copy per row wastes memory and copying work. In the query below, an 8,192-row chunk turns a single 4 KiB string into 32 MiB of data. Large constants can exceed the query memory limit before spilling starts.

When the pipeline header marks a column as constant, DistinctSetFilter keeps it in its compact ColumnConst form. The spill layout already omits these columns from temporary files and restores their values from the header. The shared filter also improves ordinary DISTINCT and the preliminary deduplication on each input stream.

SELECT DISTINCT
    number % 262144 AS k,
    repeat('x', 4096) AS payload
FROM numbers_mt(2097152)
SETTINGS
    max_block_size = 8192,
    max_bytes_before_external_distinct = 0
FORMAT Null;

The query above gives the largest measured timing improvement. For the forced-spill measurements, change max_bytes_before_external_distinct to 16777216.

Mode max_threads Time before → after Peak memory before → after
Ordinary hashing 16 216.67 → 20.00 ms 565.90 → 10.09 MiB
Ordinary hashing 64 159.33 → 26.00 ms 2130.75 → 21.85 MiB
Forced spill 16 70.33 → 67.33 ms 492.75 → 11.08 MiB
Forced spill 64 101.33 → 84.00 ms 908.71 → 23.08 MiB

Ordinary hashing takes about 91% less time at 16 threads and 84% less at 64 threads, with 98–99% lower peak memory. With spilling forced, peak memory falls by about 97–98%. The 64-thread forced-spill timing is variable: baseline runs range from 76 to 126 ms and candidate runs from 78 to 90 ms, so the lower mean does not establish a repeatable timing improvement there. Separate tests with large String and Array(UInt64) constants previously failed with MEMORY_LIMIT_EXCEEDED and now succeed under the same 128 MiB limit.

Improvement 5: Combine input chunks before sorting and deduplication

Sorting and deduplicating each input chunk separately can leave many small sorted chunks to merge. This happens with small inputs, but also with larger inputs containing many duplicates.

ExternalDistinctTransform combines input chunks with Squashing, then sorts and deduplicates the combined batch once. It starts combining only when the target batch and its temporary allocations fit the memory budget. Stable sorting preserves the first row's values for each key. Extraction of keys already returned during hashing also uses larger batches.

SELECT count()
FROM
(
    SELECT DISTINCT cityHash64(number) AS k
    FROM numbers(4000000)
)
SETTINGS
    max_block_size = 4096,
    max_bytes_before_external_distinct = 33554432,
    prefer_external_sort_block_bytes = 1048576,
    allow_preliminary_distinct_abandoning = 1;
max_threads Time before → after Peak memory before → after
16 596.33 → 331.00 ms 36.23 → 26.16 MiB
64 597.33 → 332.33 ms 36.23 → 26.16 MiB

Elapsed time falls by about 44%, and peak memory by 28%, at both thread limits. The complete PR also changes run formation: this query writes two spill files instead of one, and compressed spill data increases from about 32 KiB to 21.28 MiB. The candidate retains the final 1,227,008 buffered rows in memory.

Improvement 6: Keep only the rows needed by LIMIT while restoring order

Spill files are sorted by the DISTINCT keys, so an ordered query must restore its original row order afterward. That sort can buffer or spill many rows beyond those needed for LIMIT.

We enable the existing remerge optimization in MergeSortingTransform: periodically merge buffered chunks and keep only the earliest rows still needed for the result. This runs after duplicates and previously returned keys have been removed. Rows returned before spilling reduce the remaining limit. The sorter stops remerging if it cannot halve retained memory.

SELECT count(), min(k), max(k)
FROM
(
    SELECT DISTINCT number AS k
    FROM numbers(4000000)
    ORDER BY k + 1 DESC
    LIMIT 100000
)
SETTINGS
    max_block_size = 65409,
    max_bytes_before_external_distinct = 33554432,
    prefer_external_sort_block_bytes = 1048576,
    allow_preliminary_distinct_abandoning = 1;
max_threads Time before → after Peak memory before → after
16 208.33 → 200.67 ms 87.40 → 86.31 MiB
64 209.00 → 201.00 ms 87.40 → 86.31 MiB

Elapsed time falls by about 4%. Temporary files fall from 11 to 7, and compressed spill bytes from 50,000,999 to 47,923,933, about 4% less. Peak memory falls by about 1%.

Changelog category (leave one):

  • Performance Improvement

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

Reduce memory usage and improve performance of external DISTINCT by avoiding spills for duplicate-heavy input, writing smaller spill blocks, budgeting tail spilling before the final merge, preserving constant payloads, combining chunks before sorting, and retaining fewer rows while restoring order with LIMIT.


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

Version info

  • Merged into: 26.10.1.1143-master (included in 26.10 and later)

@clickhouse-gh

clickhouse-gh Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a488f66]

Summary: ❌

job_name test_name status info comment
Performance Comparison (amd_release, master_head, 6/6) FAIL Performance dashboard
external_distinct_header_constants #7 FAIL dashboard
array_first_last #10 unstable query history
Performance Comparison (arm_release, master_head, 4/6) FAIL Performance dashboard
external_distinct_spill_blocks #3 FAIL dashboard

AI Review

Summary

This PR substantially reworks external DISTINCT to defer spilling on duplicate-heavy input, shrink spill-file blocks, coalesce run formation, preserve constant payloads, and budget the final in-memory tail. The direction looks good and the coverage is much better, but I do not think the new recovery paths are complete yet: the checked-insertion path still loses the single-key LowCardinality duplicate state that Improvement 1 relies on, and the EOF tail-spill logic still has two memory-budget holes that can turn the “make room before the final merge” path into another avoidable spill or a MEMORY_LIMIT_EXCEEDED exception.

Findings
  • ⚠️ Majors
    • [src/Processors/Transforms/DistinctSetFilter.cpp:591] filterWithInsertionCheck disables the LowCardinality bitmap path for the whole chunk and never records the accepted prefix’s dictionary indices. After a checked-prefix insert, the next duplicate-only chunk with the same dictionary still pays estimateGrowthMemory for a fresh bitmap and misses the “all indices already seen” fast path, so external DISTINCT can still spill even though every incoming key is already in the set. Suggested fix: update the LowCardinality state for the accepted prefix only, instead of bypassing it entirely in the checked path.
    • [src/Processors/Transforms/ExternalDistinctTransform.cpp:686] [dismissed by author -- https://github.com/Reduce unnecessary spilling and memory usage in external DISTINCT #121772#discussion_r4084217428] collectInput only enforces write_budget_exceeded while the buffered run has already reached minBytesInRun(), but prepareTail can later spill a smaller EOF prefix without rechecking the writer workspace. That means a tail that stayed in memory solely because it was below the size floor can still enter the EOF spill path even though writing that prefix never fit the remaining headroom; if max_memory_usage is close to the external threshold, the recovery spill can still fail before freeing any tail memory. Suggested fix: either recheck/batch the tail-prefix writer budget in prepareTail, or make the collection-time reservation strong enough even for underfilled EOF tails.
    • [src/Processors/Transforms/ExternalDistinctTransform.cpp:816] selectTailSpillPrefix returns the whole tail when no prefix satisfies its own fit predicate. In that branch the estimator has already proven that adding another reader does not make the final merge fit, and for wide blocks it can even increase predicted memory because the extra spill-file reader can cost more than the released in-memory tail. Suggested fix: only spill prefixes that satisfy the fit test; otherwise keep the tail in memory, or switch to an explicitly degraded strategy that does not add another reader.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    • Preserve LowCardinality duplicate tracking across checked-prefix insertion.
    • Close the EOF tail-spill budgeting gap so the recovery path cannot write a prefix that never fit.
    • Avoid the “spill the whole tail even when no prefix helps” fallback, or guard it with a strategy that cannot increase the predicted merge footprint.

LLVM Coverage Report

Measured on commit a488f66.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.60% 79.70% +0.10%

Changed lines: Changed C/C++ lines covered: 483/487 (99.18%) · Uncovered code

Full report · Diff report

@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 23, 2026
const size_t new_reader_memory = estimateRunReadMemory(
2 * max_average_row_bytes * block_rows, tmp_data->getSettings().buffer_size);
const size_t released_bytes = prefix_bytes + 2 * prefix_rows;
if (query_memory + merge_memory + new_reader_memory

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.

This fit check only proves the post-spill merge state fits. If it returns true, prepareTail immediately builds another run for prefix, which needs the same write workspace that collectInput reserves with estimateRunWriteMemory while both the prefix and the retained suffix are still resident. With max_memory_usage close to max_bytes_before_external_distinct, the recovery path can still throw before it frees anything. Can we budget the tail-prefix writer here as well, instead of checking only the later reader footprint?

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.

collectInput already includes estimateRunWriteMemory for the entire buffered run when deciding whether to spill, specifically to leave workspace for a possible EOF spill. selectTailSpillPrefix estimates the later merge footprint to choose how much of that buffered run to write.

I will keep the existing collection-time accounting in this PR. It is a conservative estimate, not a protected reservation, so allocations can still fail if other operators consume the remaining headroom. An additional EOF check would need a defined response, such as selecting a smaller write batch when the workspace does not fit. Adding the check alone does not provide that behavior.

@nihalzp
nihalzp requested a review from yariks5s September 23, 2026 15:36
@yariks5s yariks5s self-assigned this Sep 23, 2026
std::optional<IColumn::Filter> lc_mask;

if (key_columns_pos.size() == 1)
if (!can_insert && key_columns_pos.size() == 1)

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.

filterWithInsertionCheck disables lc_filter.buildMaskIfApplicable for the whole chunk, so a chunk that is accepted through the checked path never records the LowCardinality dictionary indices it already consumed. On the next single-key LowCardinality chunk with the same dictionary, estimateGrowthMemory still charges the bitmap allocation and we also lose the "all indices already seen" fast path, so a duplicate-only follow-up chunk can still trip spilling even though every key is already in the set. This needs a prefix-aware update here: record only the indices from the accepted prefix, rather than bypassing the LowCardinality state entirely.

@clickhouse-gh

clickhouse-gh Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 6a43a166-0a79-4b8f-91d8-ae6197f165fa
  • MIRAI run: 2f08a62e-ac6f-4f2a-876b-b97d4dda1946
  • PR check IDs:
    • clickbench_2604577_1790811103
    • clickbench_2604589_1790811103
    • clickbench_2604596_1790811103
    • tpch_adapted_1_official_2604613_1790811104
    • tpch_adapted_1_official_2604633_1790811104
    • tpch_adapted_1_official_2604648_1790811104

@clickhouse-gh

clickhouse-gh Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a488f6668 with master 60cba6ce6 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 484e8f0b4; 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

39 object files changed (+113.25 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Transforms/DistinctSetFilter.cpp.o 353.59 KiB 406.34 KiB +52.75 KiB (+14.92%)
src/CMakeFiles/dbms.dir/Processors/Transforms/ExternalDistinctTransform.cpp.o 726.84 KiB 778.82 KiB +51.98 KiB (+7.15%)

716 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

1236 translation units recompiled, 8964 s compile time in total, 1236 of them have a recent master baseline.

Symbol sizes
Binary Symbol Master PR Δ
programs/clickhouse-keeper ProfileEvents::global_counters_storage 12.62 MiB 12.69 MiB +64.00 KiB (+0.50%)
programs/clickhouse ProfileEvents::global_counters_storage 12.62 MiB 12.69 MiB +64.00 KiB (+0.50%)

Job report

alexey-milovidov and others added 3 commits September 28, 2026 01:44
On macOS `size_t` is `unsigned long` while `UInt64` is `unsigned long long`, so
`std::max` cannot deduce a common type for `Chunk::getNumRows` / `Chunk::allocatedBytes`
mixed with `size_t` values. Use an explicit `std::max<size_t>`. The error about converting
the `can_insert` lambda to `InsertionCheck` was a cascade of the first one.

Private CI build log (arm_darwin):
https://d1k2gkhrlfqv31.cloudfront.net/clickhouse-test-reports-private/PRs/76927/282b26433e4c1f7af82450b3e731d2609b820c16/pr/build_arm_darwin/build_clickhouse/build_clickhouse.log

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

@yariks5s yariks5s 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, understandable and looks good to me. The performance comparison showed the degradation, but I think we can justify it by the memory reduction

return flag_columns_memory + output_memory + write_buffers_memory;
}

size_t ExternalDistinctTransform::selectTailSpillPrefix(const CollectingInput & collecting) const

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.

The problem is interaction between creating smaller spill files and reading all those files during the final merge. during input collection, spilling earlier makes usage memory smaller but creates more merge inputs. Each input subsequently needs decoded columns and read buffers, so final merge can consume more memory

here function searches for a tail prefix whose spill would satisfy the budget. If none qualifies, it still returns the entire tail creating another spill file even if it unable to establish that this makes the merge fit

Repro:

SELECT count()
FROM
(
    SELECT DISTINCT [concat(toString(number), repeat('x', 4096))] AS k
    FROM numbers(16384)
)
SETTINGS
    max_threads = 1,
    max_block_size = 2048,
    max_untracked_memory = 0,
    max_memory_usage = 0,
    max_memory_usage_for_user = 125829120,
    max_bytes_before_external_distinct = 0,
    max_bytes_ratio_before_external_distinct = 0.5,
    optimize_distinct_in_order = 0,
    allow_preliminary_distinct_abandoning = 0

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 think the change in 05220_.._ .sh test is related to this

@nihalzp nihalzp Oct 1, 2026 •

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.

Good finding. The issue of having many spilled files is real one. It is being handled separately in:

which also helps external sorting, join as well.

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.

Additionally, the current behavior of the PR is more preferable for realistic workloads. Even if number of spilled files is big, during merging, the memory they consume is bounded; however, this is not the case for tail, which is unbounded and can become arbitrarily large; so as result, spilling the tail is better default.

@nihalzp

nihalzp commented Oct 1, 2026

Copy link
Copy Markdown
Member Author

The couple of slowdowns are expected since they conservatively spill to decrease the probability of OOM. This PR on the other hand has very good improvements in general:

Runtime

Test Old (s) New (s) Diff Arch # Query
external_distinct_header_constants 0.4396 0.0241 -94.5% amd 2 SELECT DISTINCT number % 262144 AS k, repeat('x', 4096) AS payload FROM numbers_mt(2097152) SETTINGS max_bytes_before_external_distinct = 1099511627776 FORMAT Null
external_distinct_header_constants 0.4536 0.0254 -94.4% amd 0 SELECT DISTINCT number % 262144 AS k, repeat('x', 4096) AS payload FROM numbers_mt(2097152) SETTINGS max_bytes_before_external_distinct = 0 FORMAT Null
external_distinct_header_constants 0.2361 0.0187 -92.1% arm 2 SELECT DISTINCT number % 262144 AS k, repeat('x', 4096) AS payload FROM numbers_mt(2097152) SETTINGS max_bytes_before_external_distinct = 1099511627776 FORMAT Null
external_distinct_header_constants 0.2203 0.0188 -91.5% arm 0 SELECT DISTINCT number % 262144 AS k, repeat('x', 4096) AS payload FROM numbers_mt(2097152) SETTINGS max_bytes_before_external_distinct = 0 FORMAT Null
external_distinct_coalescing 9.2656 0.8966 -90.4% amd 4 SELECT count() FROM (SELECT DISTINCT cityHash64(number) AS k FROM numbers(4000000)) SETTINGS max_block_size = 128, max_bytes_before_external_distinct = 33554432
external_distinct_coalescing 9.0383 1.2952 -85.7% arm 4 SELECT count() FROM (SELECT DISTINCT cityHash64(number) AS k FROM numbers(4000000)) SETTINGS max_block_size = 128, max_bytes_before_external_distinct = 33554432
external_distinct_adaptive_insertion 0.5518 0.1057 -80.9% amd 0 SELECT count() FROM (SELECT DISTINCT toUInt64(number % 2097151) AS k FROM numbers(8000000)) SETTINGS max_bytes_before_external_distinct = 100663296
external_distinct_adaptive_insertion 0.481 0.096 -80.1% amd 1 SELECT count() FROM (SELECT DISTINCT toUInt8((number % 524287) % 251) AS a, toUInt64(number % 524287) AS b FROM numbers(4000000)) SETTINGS max_bytes_before_external_distinct = 100663296
external_distinct_header_constants 0.1274 0.0253 -80.1% amd 3 SELECT DISTINCT number % 262144 AS k, range(512) AS payload FROM numbers_mt(2097152) SETTINGS max_bytes_before_external_distinct = 0 FORMAT Null
external_distinct_header_constants 0.1236 0.0248 -80.0% amd 5 SELECT DISTINCT number % 262144 AS k, range(512) AS payload FROM numbers_mt(2097152) SETTINGS max_bytes_before_external_distinct = 1099511627776 FORMAT Null
external_distinct_header_constants 0.0947 0.0192 -79.8% arm 3 SELECT DISTINCT number % 262144 AS k, range(512) AS payload FROM numbers_mt(2097152) SETTINGS max_bytes_before_external_distinct = 0 FORMAT Null
external_distinct_header_constants 0.0939 0.0191 -79.6% arm 5 SELECT DISTINCT number % 262144 AS k, range(512) AS payload FROM numbers_mt(2097152) SETTINGS max_bytes_before_external_distinct = 1099511627776 FORMAT Null
external_distinct_adaptive_insertion 0.5245 0.13 -75.3% arm 0 SELECT count() FROM (SELECT DISTINCT toUInt64(number % 2097151) AS k FROM numbers(8000000)) SETTINGS max_bytes_before_external_distinct = 100663296
external_distinct_adaptive_insertion 0.4797 0.1292 -73.1% arm 1 SELECT count() FROM (SELECT DISTINCT toUInt8((number % 524287) % 251) AS a, toUInt64(number % 524287) AS b FROM numbers(4000000)) SETTINGS max_bytes_before_external_distinct = 100663296
external_distinct_adaptive_insertion 0.535 0.1446 -73.0% amd 2 SELECT count() FROM (SELECT DISTINCT toFixedString(toString(number % 131071), 64) AS k FROM numbers(4000000)) SETTINGS max_bytes_before_external_distinct = 100663296

Memory

Test Old (MB) New (MB) Diff Arch # Query
external_distinct_header_constants 676.59 14.87 -97.9% amd 2 SELECT DISTINCT number % 262144 AS k, repeat('x', 4096) AS payload FROM numbers_mt(2097152) SETTINGS max_bytes_before_external_distinct = 1099511627776 FORMAT Null
external_distinct_header_constants 649.56 14.32 -97.8% arm 0 SELECT DISTINCT number % 262144 AS k, repeat('x', 4096) AS payload FROM numbers_mt(2097152) SETTINGS max_bytes_before_external_distinct = 0 FORMAT Null
external_distinct_header_constants 681.31 15.06 -97.8% arm 2 SELECT DISTINCT number % 262144 AS k, repeat('x', 4096) AS payload FROM numbers_mt(2097152) SETTINGS max_bytes_before_external_distinct = 1099511627776 FORMAT Null
external_distinct_header_constants 648.6 15.19 -97.7% amd 0 SELECT DISTINCT number % 262144 AS k, repeat('x', 4096) AS payload FROM numbers_mt(2097152) SETTINGS max_bytes_before_external_distinct = 0 FORMAT Null
external_distinct_header_constants 514.3 12.55 -97.6% amd 1 SELECT DISTINCT number % 262144 AS k, repeat('x', 4096) AS payload FROM numbers_mt(2097152) SETTINGS max_bytes_before_external_distinct = 16777216 FORMAT Null
external_distinct_header_constants 514.3 18.07 -96.5% arm 1 SELECT DISTINCT number % 262144 AS k, repeat('x', 4096) AS payload FROM numbers_mt(2097152) SETTINGS max_bytes_before_external_distinct = 16777216 FORMAT Null
external_distinct_header_constants 168.86 14.22 -91.6% amd 3 SELECT DISTINCT number % 262144 AS k, range(512) AS payload FROM numbers_mt(2097152) SETTINGS max_bytes_before_external_distinct = 0 FORMAT Null
external_distinct_header_constants 177.1 16.4 -90.8% amd 5 SELECT DISTINCT number % 262144 AS k, range(512) AS payload FROM numbers_mt(2097152) SETTINGS max_bytes_before_external_distinct = 1099511627776 FORMAT Null
external_distinct_header_constants 172.12 16.55 -90.4% arm 5 SELECT DISTINCT number % 262144 AS k, range(512) AS payload FROM numbers_mt(2097152) SETTINGS max_bytes_before_external_distinct = 1099511627776 FORMAT Null
external_distinct_header_constants 159.94 15.47 -90.4% arm 3 SELECT DISTINCT number % 262144 AS k, range(512) AS payload FROM numbers_mt(2097152) SETTINGS max_bytes_before_external_distinct = 0 FORMAT Null
external_distinct_header_constants 113.53 13.1 -88.5% amd 4 SELECT DISTINCT number % 262144 AS k, range(512) AS payload FROM numbers_mt(2097152) SETTINGS max_bytes_before_external_distinct = 16777216 FORMAT Null
external_distinct_header_constants 129.39 16.66 -87.2% arm 4 SELECT DISTINCT number % 262144 AS k, range(512) AS payload FROM numbers_mt(2097152) SETTINGS max_bytes_before_external_distinct = 16777216 FORMAT Null
external_distinct_spill_blocks 1,517.85 223.63 -85.3% amd 1 SELECT count(), sum(length(payload)) FROM (SELECT DISTINCT cityHash64(number) AS k, repeat('x', if(number % 8 = 0, 8192, 32)) AS payload FROM numbers(524288)) SETTINGS max_block_size = 65536, max_bytes_before_external_distinct = 67108864
external_distinct_spill_blocks 1,517.85 223.63 -85.3% arm 1 SELECT count(), sum(length(payload)) FROM (SELECT DISTINCT cityHash64(number) AS k, repeat('x', if(number % 8 = 0, 8192, 32)) AS payload FROM numbers(524288)) SETTINGS max_block_size = 65536, max_bytes_before_external_distinct = 67108864
external_distinct_tail_spill 1,517.85 223.63 -85.3% amd 2 SELECT count(), sum(length(payload)) FROM (SELECT DISTINCT cityHash64(number) AS k, repeat('x', if(number % 8 = 0, 8192, 32)) AS payload FROM numbers(524288)) SETTINGS max_block_size = 65536, max_bytes_before_external_distinct = 67108864
external_distinct_tail_spill 1,517.85 223.63 -85.3% arm 2 SELECT count(), sum(length(payload)) FROM (SELECT DISTINCT cityHash64(number) AS k, repeat('x', if(number % 8 = 0, 8192, 32)) AS payload FROM numbers(524288)) SETTINGS max_block_size = 65536, max_bytes_before_external_distinct = 67108864
external_distinct_spill_blocks 999.83 262.77 -73.8% amd 0 SELECT count(), sum(length(payload)) FROM (SELECT DISTINCT cityHash64(number) AS k, toFixedString(toString(number), 1024) AS payload FROM numbers(524288)) SETTINGS max_block_size = 65536, max_bytes_before_external_distinct = 67108864
external_distinct_spill_blocks 999.83 262.77 -73.8% arm 0 SELECT count(), sum(length(payload)) FROM (SELECT DISTINCT cityHash64(number) AS k, toFixedString(toString(number), 1024) AS payload FROM numbers(524288)) SETTINGS max_block_size = 65536, max_bytes_before_external_distinct = 67108864
external_distinct_spill_blocks 321.88 100.36 -68.9% arm 2 SELECT count(), sum(length(k)) FROM (SELECT DISTINCT toFixedString(toString(number % 65536), 4096) AS k FROM numbers(131072)) SETTINGS max_block_size = 4096, max_bytes_before_external_distinct = 167772160

@nihalzp
nihalzp added this pull request to the merge queue Oct 1, 2026
Merged via the queue into ClickHouse:master with commit e6097f1 Oct 1, 2026
147 of 149 checks passed
@nihalzp
nihalzp deleted the external-distinct-improvements branch October 1, 2026 05:05
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 1, 2026
alexey-milovidov pushed a commit to amosbird/ClickHouse that referenced this pull request Oct 2, 2026
Since ClickHouse#121772 external DISTINCT sizes its spill blocks by
prefer_external_sort_block_bytes. The test runner draws it from
[0, 1, 100000000]; only 1 changes anything and gives 128-row spill
blocks, so the spilling queries of these two tests create ~500x more
short-lived objects. Under MSan each allocation, free and destructor
records a stack in the sanitizer stack depot, and StackDepot::Put gets
slower as the server ages: on the CI MSan binary the 05077 spilling
query takes 18 s vs 7 s on a fresh server, 41-61 s vs 8 s after
6-18 minutes of the stateless suite, and 600 s vs 17 s on the
two-hour-old CI server (master timeout in amd_msan, parallel, 3/3 at
9edb7a3). 05059 shows the same pattern (MSan max 33 s before, 382 s
after).

Use the default as a lower bound with a per-setting limit, so 0 and 1
map to the default and every other setting stays randomized. Measured
on the CI binaries with a control copy whose limit line is misspelled:
the clamped copies never get 0 or 1, and on an MSan server aged for
21 minutes clamped runs take 10-17 s while control runs that drew 1
take 320 s (05077) and 161-170 s (05059).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robinld pushed a commit to robinld/ClickHouse that referenced this pull request Oct 3, 2026
`05077_external_distinct_memory_limit` timed out in `Stateless tests (amd_msan, parallel, 3/3)`:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=9edb7a39c18e296c3f9767934b9f5ca739001f29&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_msan%2C%20parallel%2C%203%2F3%29

The randomized `prefer_external_sort_block_bytes = 1` was the only culprit. Since
ClickHouse#121772 external `DISTINCT` sizes its spill blocks by
this setting, as external `ORDER BY` does, so the value 1 produces 128-row blocks. Spilling 16 million
rows then reads back tens of thousands of tiny `Native` blocks: the query took 600 seconds in the
MSan build instead of 17. A release build shows the same 7x slowdown for both external `DISTINCT`
and external `ORDER BY`, so this is the cost of the setting, not a defect of `DISTINCT`.

Restore the default in this test and in `05059_external_distinct_order_by`, which has the same
10x slowdown and already reaches 380 seconds under MSan. Neither test depends on the spill block
size, and other tests keep covering the randomized value.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@nihalzp nihalzp mentioned this pull request Nov 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. 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.

4 participants