Repository navigation
Reduce unnecessary spilling and memory usage in external DISTINCT - #121772
Conversation
|
Workflow [PR], commit [a488f66] Summary: ❌
AI ReviewSummaryThis PR substantially reworks external Findings
Final Verdict
LLVM Coverage ReportMeasured on commit a488f66.
Changed lines: Changed C/C++ lines covered: 483/487 (99.18%) · Uncovered code |
| 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 |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
| std::optional<IColumn::Filter> lc_mask; | ||
|
|
||
| if (key_columns_pos.size() == 1) | ||
| if (!can_insert && key_columns_pos.size() == 1) |
There was a problem hiding this comment.
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.
|
📊 Cloud Performance Report ✅ AI verdict: 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
|
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes39 object files changed (+113.25 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units1236 translation units recompiled, 8964 s compile time in total, 1236 of them have a recent master baseline. Symbol sizes
|
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
left a comment
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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 = 0There was a problem hiding this comment.
I think the change in 05220_.._ .sh test is related to this
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
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
Memory
|
e6097f1
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]>
`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]>
Related: #116569
Use these common settings for the queries below.
Improvement 1: Avoid spilling when incoming rows are already in the set
DISTINCTestimates 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.
max_threadsElapsed 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.
MergeSorternow usesprefer_external_sort_block_bytesand 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.max_threadsPeak 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
DISTINCTcan 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.max_threadsBoth versions return a row count of
1900000and a total payload length of243200000bytes. 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,
DistinctSetFilterkeeps it in its compactColumnConstform. The spill layout already omits these columns from temporary files and restores their values from the header. The shared filter also improves ordinaryDISTINCTand the preliminary deduplication on each input stream.The query above gives the largest measured timing improvement. For the forced-spill measurements, change
max_bytes_before_external_distinctto16777216.max_threadsOrdinary 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
StringandArray(UInt64)constants previously failed withMEMORY_LIMIT_EXCEEDEDand 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.
ExternalDistinctTransformcombines input chunks withSquashing, 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.max_threadsElapsed 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
LIMITwhile restoring orderSpill files are sorted by the
DISTINCTkeys, so an ordered query must restore its original row order afterward. That sort can buffer or spill many rows beyond those needed forLIMIT.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.max_threadsElapsed 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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Reduce memory usage and improve performance of external
DISTINCTby 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 withLIMIT.Workflow [PR]
Sync PR [sync-upstream/pr/121772]
Version info
26.10.1.1143-master(included in26.10and later)