Repository navigation
External DISTINCT - #116569
Merged
Merged
External DISTINCT#116569
DISTINCT#116569Conversation
Merged
via the queue into
ClickHouse:master
with commit Sep 17, 2026
718e603
347 of 351 checks passed
clickhouse-gh Bot
added a commit
that referenced
this pull request
Sep 17, 2026
Backport #116569 to 26.9: External `DISTINCT`
This was referenced Sep 17, 2026
alexey-milovidov
added a commit
that referenced
this pull request
Sep 18, 2026
…ality` a plain `DistinctTransform` Master added external `DISTINCT` (#116569): with the default non-zero `max_bytes_ratio_before_external_distinct` the final hash `DISTINCT` is an `ExternalDistinctTransform`, so the test's list of processor names lost one `DistinctTransform`. Both are the hash variant; the test only checks that no `DistinctSortedStreamTransform` runs over a float key. Disable the external variant, as `02317_distinct_in_order_optimization_explain` does, so the names stay stable. Co-Authored-By: Claude Fable 5.1 <[email protected]>
clickgapai
pushed a commit
to clickgapai/ClickHouse
that referenced
this pull request
Sep 18, 2026
On MSan builds the three tests in test_max_bytes_ratio_before_external_order_group_by_for_server fail at their own skip guard rather than at an assertion. ClickHouseInstance.is_built_with_sanitizer answers by issuing a live query to the running node (SELECT value FROM system.build_options WHERE name = 'CXX_FLAGS'), uncached, on every call. The three tests share one module-scoped cluster and run in declaration order. test_..._sort guards TSan only, so on an MSan build it runs, and its second phase deliberately drives the node to MEMORY_LIMIT_EXCEEDED on a ~12 GiB-peak ORDER BY. Sanitizer builds other than UBSan have no jemalloc (contrib/jemalloc-cmake/CMakeLists.txt:1-10), so no arena purge returns those pages and RSS stays tens of MiB above the cap. MemoryTracker::allocImpl enforces the total limit against RSS rather than tracked bytes (src/Common/MemoryTracker.cpp:348), so while RSS is above the cap the server rejects every allocation, including the tiny one in TCPHandler::receiveHello(), i.e. the connection handshake. The first statement of test_..._distinct is its own skip-guard probe; that probe is refused with Code: 241, and the QueryRuntimeException escapes as a FAIL two lines before the MSan pytest.skip() can run. The guard is unreachable on exactly the builds it exists for. Read the flavour once in the module fixture, immediately after cluster.start(), while both nodes are still at their floor RSS, into a module-level dict the three tests consult. No test has allocated at that point, so the probe can no longer be defeated by state a later test creates. test_keeper_profiler and test_trace_collector_serverwide already probe the build flavour at this same point. Note that cluster.start() only waits for the TCP port (9000 by default) to accept a connection (ClickHouseInstance.wait_until_port_is_ready), so "the port is open" never implied "a query will be answered": Code: 241 is raised in TCPHandler::receiveHello(), after the socket has been accepted. Skip semantics are preserved case for case and message for message: group_by and distinct keep their TSan and MSan skips, sort keeps its TSan-only skip. sort is deliberately not given an MSan skip: it passes 110/110 on MSan and has never failed there, so adding one would delete real coverage to silence a failure that is not its fault. The fix is deliberately not in helpers/cluster.py either: 27 upgrade-test modules swap the binary mid-module (restart_with_latest_version, with_installed_binary), so caching CXX_FLAGS there would need invalidation on every one of them, a harness-wide change across 161 call sites in 69 files to close a defect with exactly one instance in the tree. Of the integration modules that cap server/user memory and probe the build flavour, exactly one has more than one test function, and it is this one, so group_by and sort were latent carriers of the same pattern and are converted too. Measured (CIDB, 30 days, memory-limit failures of this module): 7 failures on 7 distinct PRs, all on 2026-09-17 between 06:06Z and 14:20Z, 0 on master, all in Integration tests (amd_msan, 1/8), hitting both the [server] and [user] arms. Exposure opened when ClickHouse#116569 merged, adding the distinct case after sort in the file. Validated with a fault-injected probe oracle: 6/6 FAIL and 6 test-body probe calls before, 0 test-body probe calls after, across 3 MSan runs plus TSan and -k-filtered arms. On a plain debug build the full file is 6 passed, 0 skipped.
This was referenced Sep 18, 2026
This was referenced Sep 19, 2026
47 of 72 tasks
This was referenced Sep 23, 2026
groeneai
added a commit
to groeneai/ClickHouse
that referenced
this pull request
Sep 24, 2026
GitHub could not compute a merge ref for the previous head, so praktika never dispatched any CI for it. The only conflict is in `AggregationCommon.h`: ClickHouse#116569 (External `DISTINCT`) added `unpackFixedKeyIntoColumns` at the same anchor where this branch adds its range packing helpers. Both blocks are kept, with master's first so that its "the inverse of the fixed-size key packing above" keeps referring to `packFixedBatch`. That pull request also factored `packedKeysOrder` out of `shuffleKeyColumns`. It keeps the descending-size order that this branch's `packFixedLongestFirst` reproduces, so the per-row and the batched key layouts still agree. The branch delta against master is byte-identical before and after the merge, apart from one context line moved by the resolution above.
Merged
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
DISTINCTkeeps a hash set of all the distinct keys, so its memory usage grows with cardinality: a query with many distinct values can fail withMEMORY_LIMIT_EXCEEDED. This PR lets the finalDISTINCTspill to disk, the same way external aggregation and external sort already do.Settings.
max_bytes_before_external_distinct(absolute,0= unset) andmax_bytes_ratio_before_external_distinct(a ratio of the available memory,0.5by default — enabled by default). Both thresholds combine by minimum, mirroringAggregator::Params::getMaxBytesBeforeExternalGroupBy. The thresholds are compared with the tracked memory usage of the whole query. The available memory is what remains, when the execution pipeline is built, under the strictest applicable server or user memory limit; when neither supplies a limit, the ratio has no effect and only the absolute threshold applies.max_memory_usagedoes not participate in this calculation. Setting both thresholds to0disables externalDISTINCTand its associated preliminary memory shedding.How the spill works (
ExternalDistinctTransform). The spill reuses the external sort components used byMergeSortingTransform. Sorted chunks are accumulated, merged into runs that are written to temporary files, and merged back at the end. The pipeline is expanded at runtime, and the file sink/source pair is extracted into the sharedBufferingFileTransforms. For ordinary input, each of the three sorting stages also deduplicates. Duplicates within a chunk or an accumulated run are removed before writing, reducing disk I/O on skewed input. Duplicates across runs are removed during the final merge.DistinctTransform.DistinctSetFilter::prepareForInsertnormalizes its columns and initializes the set.DistinctSetFilter::estimateGrowthMemorythen estimates additional hash-table buffers and arena allocations, treating every input row as a potential new key. The transform compares this estimate, together with the memory needed to prepare a spill, against available server/user memory. If there is insufficient room, spilling starts before insertion, and the pending chunk is processed through the external path. The estimate follows the actual hash-table grower and uses total string bytes to bound arena growth without scanning individual rows. FixedUInt8andUInt16tables report no growth.DistinctSetFilter::extractKeys. A resumable extractor prepares sorted suppression runs with an approximately 16 MiB byte target. Each of them carries an “already emitted” flag. Extraction waits for each run to finish writing before preparing another, and the set is freed after its last keys are extracted. The extractor returns typed comparison keys for the specialized set methods, or the retainedUInt128fingerprints for thehashedmethod. Suppression rows need no payload because they are never emitted again. They are sorted withsortBlockand merged withMergeSorter::Mode::PreserveRows: typed keys that the hash set distinguishes may compare equal in the sort order, and their binary representatives are retained.hashedmethod,DistinctSpillLayout::prepareInputChunkcomputes the same fingerprint for each incoming row and carries it alongside the original typed payload. The spill runssortBlockAndDeduplicateon every incoming chunk: it builds a stable sorting permutation, identifies equal key ranges, retains the first row of each range in that permutation, and applies the compacted permutation to all columns. A chunk therefore carries no duplicates into the accumulated chunks. The chunks are accumulated and written out as further runs when memory exceeds the threshold. Ordinary runs have a minimum accumulated size to avoid writing a file for every small chunk.MergeSorter. The spill usesMergeSorter::Mode::MergeUniqueChunks, which relies on the chunks being sorted and unique within themselves. When switching input chunks, only the first row of a batch can repeat the last emitted key; continuing the same cursor needs no duplicate comparison. The surviving ranges are copied directly. Every ordinary run on disk is unique on the comparison keys. The final in-memory tail is merged the same way. Ordinary runs carry the non-constant input columns and service columns; constants are re-attached from the header after the merge.MergingSortedTransform. The spill usesDistinctSortedTransform, which fuses merging, deduplication, and suppression in one stage. Runs are ordered by distinct keys followed by the already-emitted flag descending, so suppression rows precede equal ordinary rows independently of their input position. Ordinary runs retain arrival precedence through the input-index tie-break, which preserves the first payload among equal keys. Surviving ranges are copied together, and whole chunks are forwarded when possible.ORDER BYis preserved across the spill. The finalDISTINCTof a query withORDER BYat the same level runs above the sort, so it has to return the rows in the sorted order. When it spills, every row carries its arrival number into the runs, and after the merge and deduplication the rows are sorted back by it (PartialSortingTransform+MergeSortingTransform, which can use the disk as well, under the same thresholds).DistinctStepcarries this requirement as a flag: the planners set it for the query’s ownORDER BY, and theapplyOrderoptimization sets it whenever it propagates a global sort order through the step, because the steps above may rely on that order. The flag is serialized with the query plan under the plan version that also carries the externalDISTINCTsettings (and omitted from the hash-table cache key), so a remote server executing a serialized plan preserves the order too;EXPLAIN PLAN actions = 1shows it asPreserve input order: 1.The preliminary
DISTINCTnever spills. It is best-effort, so under the same threshold it frees its hash set and switches to pass-through, leaving deduplication to the downstream step. It can also release the set before projected hash-table and string-arena growth exceeds available server/user memory. This policy is independent of whether the downstream step uses hashing or sorted input; the switch is counted by theDistinctTransformsSwitchedToPassThroughprofile event.Shared deduplication core. The hash-set filtering, the
LowCardinalityfast path, and size-limit enforcement are extracted fromDistinctTransformintoDistinctSetFilter, shared by both transforms, so a semantic change to hashing is a change in one place.DistinctSpillLayoutowns the comparison-key representation, headers, and service-column positions, whileExternalDistinctTransformschedules extraction, writing, and merging. The layout’sSortDescriptionmakessortBlockAndDeduplicate,MergeSorter, andDistinctSortedTransformcompare only the fingerprint for thehashedmethod, and typed key columns for the other methods. The sorting helpers do not need to know which set method was selected. Fingerprints are computed before writing and carried through disk round trips without recomputing them from reconstructed values. Equality uses the fingerprint alone, as in the in-memoryhashedmethod. Already-emitted flags remain constant columns during run preparation and local sorting.Scope and semantics:
DISTINCT, and only when at least one key column is non-constant. Every key type is supported. Non-comparable keys, including aggregate states nested inVariantorDynamic, use fingerprints for spill comparisons; the original typed columns remain the output payload. The existing sorted-streamDISTINCTpaths remain unchanged.0.and-0.,NaNpayloads) may be deduplicated as one value once the data is spilled — the same equalityDISTINCTover sorted data uses; a value class fully processed in memory keeps the binary distinction. Thehashedmethod retains the same fingerprint equality before and after spilling.DISTINCT ... LIMITover an unbounded stream no longer terminates early once a spill happened: after the spill nothing can be emitted until the input is exhausted, so the limit cannot short-circuit reading, as with external sort.max_bytes_in_distinctalso counts the bitmaps of theLowCardinalityfast path. Size limits are checked even when a chunk adds no new keys.LIMIThint, including when both are crossed in the same chunk.BREAKretains chunk-level behavior.ExternalDistinctWritePart,ExternalDistinctMerge,ExternalDistinctCompressedBytes,ExternalDistinctUncompressedBytesandDistinctTransformsSwitchedToPassThroughprofile events and theTemporaryFilesForDistinctmetric; temporary files inherit the query’s temporary-data scope and respect query, user, and server temporary-data size limits,min_free_disk_space_for_temporary_data,temporary_files_codec,temporary_files_buffer_size, and temporary data disk policies.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
DISTINCTcan now spill data to disk, like external aggregation and external sort: the new settingsmax_bytes_before_external_distinctandmax_bytes_ratio_before_external_distinctset the threshold; by default, spilling starts once query memory usage exceeds half the available memory under the applicable server or user memory limits, or as soon as the next hash table allocation would exceed it.Workflow [PR]
Sync PR [sync-upstream/pr/116569]
Version info
26.10.1.11(included in26.10and later)26.9.1.1594