Skip to content

External DISTINCT - #116569

Merged
nihalzp merged 148 commits into
ClickHouse:masterfrom
nihalzp:external-distinct
Sep 17, 2026
Merged

nihalzp merged 148 commits into
ClickHouse:masterfrom
nihalzp:external-distinct

Conversation

@nihalzp

@nihalzp nihalzp commented Aug 26, 2026 •

Copy link
Copy Markdown
Member

DISTINCT keeps a hash set of all the distinct keys, so its memory usage grows with cardinality: a query with many distinct values can fail with MEMORY_LIMIT_EXCEEDED. This PR lets the final DISTINCT spill to disk, the same way external aggregation and external sort already do.

Settings. max_bytes_before_external_distinct (absolute, 0 = unset) and max_bytes_ratio_before_external_distinct (a ratio of the available memory, 0.5 by default — enabled by default). Both thresholds combine by minimum, mirroring Aggregator::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_usage does not participate in this calculation. Setting both thresholds to 0 disables external DISTINCT and its associated preliminary memory shedding.

How the spill works (ExternalDistinctTransform). The spill reuses the external sort components used by MergeSortingTransform. 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 shared BufferingFileTransforms. 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.

  • Before spilling, the first occurrence of every key streams downstream immediately. This uses the same filtering core as DistinctTransform.
  • Before inserting each chunk, DistinctSetFilter::prepareForInsert normalizes its columns and initializes the set. DistinctSetFilter::estimateGrowthMemory then 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. Fixed UInt8 and UInt16 tables report no growth.
  • When spilling starts, the keys emitted so far are recovered incrementally from the hash set through 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 retained UInt128 fingerprints for the hashed method. Suppression rows need no payload because they are never emitted again. They are sorted with sortBlock and merged with MergeSorter::Mode::PreserveRows: typed keys that the hash set distinguishes may compare equal in the sort order, and their binary representatives are retained.
  • From that point nothing is emitted until the input is exhausted. For the hashed method, DistinctSpillLayout::prepareInputChunk computes the same fingerprint for each incoming row and carries it alongside the original typed payload. The spill runs sortBlockAndDeduplicate on 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.
  • External sort merges the accumulated chunks into a run with MergeSorter. The spill uses MergeSorter::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.
  • External sort reads the runs back through MergingSortedTransform. The spill uses DistinctSortedTransform, 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 BY is preserved across the spill. The final DISTINCT of a query with ORDER BY at 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). DistinctStep carries this requirement as a flag: the planners set it for the query’s own ORDER BY, and the applyOrder optimization 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 external DISTINCT settings (and omitted from the hash-table cache key), so a remote server executing a serialized plan preserves the order too; EXPLAIN PLAN actions = 1 shows it as Preserve input order: 1.

The preliminary DISTINCT never 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 the DistinctTransformsSwitchedToPassThrough profile event.

Shared deduplication core. The hash-set filtering, the LowCardinality fast path, and size-limit enforcement are extracted from DistinctTransform into DistinctSetFilter, shared by both transforms, so a semantic change to hashing is a change in one place. DistinctSpillLayout owns the comparison-key representation, headers, and service-column positions, while ExternalDistinctTransform schedules extraction, writing, and merging. The layout’s SortDescription makes sortBlockAndDeduplicate, MergeSorter, and DistinctSortedTransform compare only the fingerprint for the hashed method, 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-memory hashed method. Already-emitted flags remain constant columns during run preparation and local sorting.

Scope and semantics:

  • The external path is used only for the final hash-based DISTINCT, and only when at least one key column is non-constant. Every key type is supported. Non-comparable keys, including aggregate states nested in Variant or Dynamic, use fingerprints for spill comparisons; the original typed columns remain the output payload. The existing sorted-stream DISTINCT paths remain unchanged.
  • For methods that spill typed comparison keys, values that compare equal in the sort order but differ in the binary representation (0. and -0., NaN payloads) may be deduplicated as one value once the data is spilled — the same equality DISTINCT over sorted data uses; a value class fully processed in memory keeps the binary distinction. The hashed method retains the same fingerprint equality before and after spilling.
  • DISTINCT ... LIMIT over 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.
  • The byte size checked against max_bytes_in_distinct also counts the bitmaps of the LowCardinality fast path. Size limits are checked even when a chunk adds no new keys.
  • The final merge checks the row limit before applying the LIMIT hint, including when both are crossed in the same chunk. BREAK retains chunk-level behavior.
  • Introspection: ExternalDistinctWritePart, ExternalDistinctMerge, ExternalDistinctCompressedBytes, ExternalDistinctUncompressedBytes and DistinctTransformsSwitchedToPassThrough profile events and the TemporaryFilesForDistinct metric; 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):

  • New Feature

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

DISTINCT can now spill data to disk, like external aggregation and external sort: the new settings max_bytes_before_external_distinct and max_bytes_ratio_before_external_distinct set 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

  • Merged into: 26.10.1.11 (included in 26.10 and later)
  • Backported to: 26.9.1.1594

nihalzp added 30 commits July 12, 2026 16:20
Merged via the queue into ClickHouse:master with commit 718e603 Sep 17, 2026
347 of 351 checks passed
@nihalzp
nihalzp deleted the external-distinct branch September 17, 2026 01:54
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 17, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 17, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Sep 17, 2026
clickhouse-gh Bot added a commit that referenced this pull request 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.
@alexey-milovidov alexey-milovidov mentioned this pull request Sep 20, 2026
47 of 72 tasks
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.
@nihalzp nihalzp mentioned this pull request Oct 4, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 7, 2026
@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-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-feature Pull request with new product feature pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.8-must-backport v26.9-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants