Skip to content

External IN: Optimized Disk Set (2/2) - #124907

Merged
nihalzp merged 100 commits into
ClickHouse:masterfrom
nihalzp:external-in-faster-disk-set
Oct 18, 2026
Merged

nihalzp merged 100 commits into
ClickHouse:masterfrom
nihalzp:external-in-faster-disk-set

Conversation

@nihalzp

@nihalzp nihalzp commented Oct 9, 2026 •

Copy link
Copy Markdown
Member

Related: #123860

#123860 added the set of IN on disk in a basic form which was very slow. This PR optimizes the disk set for common workloads. Spilling is enabled by default: max_bytes_ratio_before_external_set defaults to 0.5, so a set spills once query memory exceeds half of the memory that the server or user memory limits leave.

Building the set: a sorter of plain keys

On master, the build sorts the keys with MergeSortingTransform, the external sort of blocks of columns. It sorts every block as it arrives, merges sorted blocks into runs and runs into the result, and compares rows of columns at each step, while the keys of a set are plain unsigned integers. Now the builder sorts a whole run of plain keys at once, by radix sort for keys of up to 64 bits, and merges the runs with a tournament over chains of runs that do not overlap.

A set of 30M tuples of UInt64 and UInt32 from rows in key order and a single probe, so the query time is the build of the set.

SELECT count() FROM numbers(1) WHERE (intDiv(number, 1000), toUInt32(number % 1000)) IN (SELECT intDiv(number, 1000), toUInt32(number % 1000) FROM numbers(30000000))
In memory This PR master (basic disk set)
1.16 s 0.815 s 1.89 s

Keys that the set does not have: Bloom filters

On master, a lookup of a key that the set does not have still reads and decompresses the block where the key would be, so absent keys cost as much as the keys of the set. Now the set keeps a Bloom filter of each block, with 8 bits per key, which lets about 3% of the absent keys pass. A lookup checks the filter of a block before it reads the block, so most lookups of absent keys read nothing. The builder counts the distinct keys with HyperLogLog as they arrive, so it sizes the filters before it writes the first block. max_bytes_for_external_set_bloom_filter, 128 MiB by default, limits their memory.

A set of 5M random 64-bit hashes, probed with 30M random hashes that it does not have.

SELECT count() FROM numbers_mt(30000000) WHERE cityHash64(number * 2 + 1) IN (SELECT cityHash64(number * 2) FROM numbers(5000000))
In memory This PR master (basic disk set)
0.175 s 0.345 s 1.77 s

Lookups that need the same blocks again: a cache of blocks

On master, each lookup call reads the blocks that it needs from the file, even when other calls have just read them. Random lookups need most of the blocks in every chunk, so they read most of the file again for each chunk. Now the set caches the blocks that lookups read, as they are in the file, so later lookups of keys in these blocks do not read the file again. The cache evicts blocks by SLRU, so blocks that lookups need once do not evict blocks that they keep needing, and it is split into shards with locks of their own, so the lookups of many threads do not wait for each other. A lookup prefetches the next cached block while it searches the current one. max_bytes_for_external_set_cache, 128 MiB by default, limits the memory of the cache.

A set of 5M String keys, probed with 10M strings in random order, about half of which it has.

SELECT count() FROM numbers_mt(10000000) WHERE toString(cityHash64(number) % 10000000) IN (SELECT toString(number) FROM numbers(5000000))
In memory This PR master (basic disk set)
0.414 s 0.596 s 1.77 s

Lookups in key order: disk keys in the order of the keys

On master, a packed tuple keeps the byte order of the hash table on disk, and a string becomes a 128-bit hash, so disk keys do not follow the order of the values. Even sorted lookups then scatter over the whole file. Now numbers, dates, short FixedString values and tuples of them become disk keys of the same width that keep their order, with the first element of a tuple first and NULL after the values. A string becomes its first 4 bytes, which keep their order, above 96 bits of its hash. Values that arrive sorted, such as the columns of a table read in the order of its sorting key, then fall into a few neighboring blocks, and a chunk of lookups reads only those. A set built from sorted rows gets its keys already sorted, too.

A set of 5M tuples of UInt64 and UInt32, probed with 10M tuples in key order, half of which it has.

SELECT count() FROM numbers_mt(10000000) WHERE (intDiv(number, 1000000), toUInt32(number % 1000000)) IN (SELECT intDiv(number, 1000000), toUInt32(number % 1000000) FROM numbers(5000000))
In memory This PR master (basic disk set)
0.206 s 0.182 s 0.456 s

Dense keys: packed blocks

On master, every block holds 4 KiB of keys as they are, however close the keys are, so a set of 5M 64-bit keys takes about 9,800 blocks, and random lookups need most of them in every chunk. Now a block keeps the offsets of its keys from its first key, packed by PFor with a delta transform. Dense and slowly changing keys then take several times fewer blocks, so lookups read fewer blocks, and the cache holds a larger part of the set. Other blocks keep their keys as they are.

A set of the 5M numbers below 5M, probed with 10M random numbers below 10M, about half of which it has.

SELECT count() FROM numbers_mt(10000000) WHERE cityHash64(number) % 10000000 IN (SELECT number FROM numbers(5000000))
In memory This PR master (basic disk set)
0.112 s 0.187 s 0.657 s

The set takes 79 KiB on disk in 1,221 blocks with this PR, and 19.4 MiB in 9,766 blocks on master.

Random lookups of many keys: neighboring blocks read together

On master, a chunk of random lookups needs most of the blocks of the set, and it seeks to each block and reads it with a read of its own. Now a chunk of lookups first finds all the blocks that its keys need. A chunk that needs most of the blocks in a part of the file reads neighboring frames together with TemporaryFileFrameReader: one read takes up to 128 KiB and joins frames that at most 32 KiB separate. A chunk that needs few blocks reads them one at a time.

A set of 5M random 64-bit hashes, probed with 10M random hashes, half of which it has, in chunks of 65,409 rows.

SELECT count() FROM numbers_mt(10000000) WHERE cityHash64(number) IN (SELECT cityHash64(number * 2) FROM numbers(5000000))
In memory This PR master (basic disk set)
0.146 s 0.338 s 1.04 s

Every block read: one uncompressed frame

On master, every block is compressed, so a lookup reads it through a buffer of compressed data and decompresses it. When the set does not fit its cache, lookups read most of their blocks from the file, so the cost of reading each block decides the time of the query. The keys of a set are distinct, so they compress little: hashes do not compress at all, and close keys are packed already. Now the file of the set is not compressed, and each block is one frame of its own. A lookup reads a block with one read of its frame, checks its checksum and decodes it where it lies, without decompression.

A set of 10M tuples of four 64-bit hashes, which take 320 MB, more than its cache of 128 MiB, probed with 10M random tuples, half of which it has.

SELECT count() FROM numbers_mt(10000000) WHERE (cityHash64(number), cityHash64(number + 1), cityHash64(number + 2), cityHash64(number + 3)) IN (SELECT cityHash64(number * 2), cityHash64(number * 2 + 1), cityHash64(number * 2 + 2), cityHash64(number * 2 + 3) FROM numbers(10000000))
In memory This PR master (basic disk set)
1.28 s 2.36 s 5.57 s

Repeated keys: one probe per distinct key

On master, every row of a chunk is a probe of its own, so a chunk with few distinct keys searches the same keys again and again. Now a chunk of lookups sorts its probes by key, so each distinct key of the chunk takes one probe. A row that repeats the key of the previous row takes the answer of that row without a probe.

A set of 5M random 64-bit hashes, probed with 100M rows that repeat 1,000 hashes, half of which it has.

SELECT count() FROM numbers_mt(100000000) WHERE cityHash64(number % 1000) IN (SELECT cityHash64(number * 2) FROM numbers(5000000))
In memory This PR master (basic disk set)
0.146 s 0.273 s 0.952 s

Changelog category (leave one):

  • Performance Improvement

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

Sets of IN with a subquery spill to disk by default: max_bytes_ratio_before_external_set now defaults to 0.5, so a set spills once query memory exceeds half of the memory that the server or user memory limits leave. Set it to 0 to keep such sets in memory. Sets on disk are built and looked up several times faster: they keep numbers, dates, short FixedString values and tuples of them in order, pack close keys, read neighboring blocks together without decompression, skip blocks with Bloom filters, cache the blocks that lookups read, and look up each distinct key of a block of rows once. The new settings max_bytes_for_external_set_bloom_filter and max_bytes_for_external_set_cache, 128 MiB each by default, limit the memory of the Bloom filters and of the cache.


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

Version info

  • Merged into: 26.11.1.147-master (included in 26.11 and later)
  • Backported to: 26.10.2.23

@clickhouse-gh

clickhouse-gh Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [02caf07]

Summary: ✅


AI Review

Summary

The PR accelerates spilled IN sets with ordered keys, a dedicated sorter, packed blocks, Bloom filters, batched reads, and a block cache, and enables spilling by default through max_bytes_ratio_before_external_set = 0.5. No unresolved actionable findings remain at commit 02caf07e819092851d593d5ac221e30fa81bcd13. Prior findings were reassessed against the current code and all thread replies; the remaining bot thread about merge-buffer allocation is fixed and has focused regression coverage.

The review used source inspection, regression tests, the reported before/after benchmarks, and the existing CI reports. No tests were run locally.

Final Verdict

Status: ✅ Approve

@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 Oct 9, 2026
Comment thread src/Interpreters/DiskSetKeys.cpp Resolved
Comment thread src/Interpreters/DiskSetKeys.h Resolved
Comment thread src/Interpreters/DiskSetRunMerge.h Resolved
@nihalzp
nihalzp added this pull request to the merge queue Oct 18, 2026
Merged via the queue into ClickHouse:master with commit 1d76716 Oct 18, 2026
178 checks passed
@nihalzp
nihalzp deleted the external-in-faster-disk-set branch October 18, 2026 08:50
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 18, 2026
PedroTadim added a commit that referenced this pull request Oct 18, 2026
Resolve the conflict with #124907, which replaced
`randomize_external_sort_group_by` with `randomize_external_thresholds(operations)` and draws
the `IN` set spill separately: take master's function and settings, and keep this branch's
`distinct` spill in the sort/group by draw.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 19, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 19, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 19, 2026
Backport #124907 to 26.10: External `IN`: Optimized Disk Set (2/2)
alexey-milovidov pushed a commit to scanhex12/ClickHouse that referenced this pull request Oct 20, 2026
Since ClickHouse#124907 the test runner randomizes `max_bytes_before_external_set`
and `max_bytes_ratio_before_external_set`. When the threshold is below
what the set collects before the test's 0.1 s limit, the set goes to
disk, and the disk set builder throws `QUERY_WAS_CANCELLED` in the
`break` mode by design (`05401_external_set_cancellation`). The test
checks the quiet stop of the in-memory set, so clamp both thresholds to
0 for it with `Random settings limits`; every other setting stays
random.

Failed in "Stateless tests (arm_binary, AsyncInsert, s3 storage,
parallel)" on PR ClickHouse#126476 with `--max_bytes_before_external_set 8556090`
(127/128 reruns with the same settings failed).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit to scanhex12/ClickHouse that referenced this pull request Oct 20, 2026
Since ClickHouse#124907 the test runner randomizes max_bytes_before_external_set and
max_bytes_ratio_before_external_set. A threshold below the memory of the
1M-key set makes the set spill while it is built, and such a set keeps no
explicit elements, so the primary key cannot use it and force_primary_key = 1
throws INDEX_NOT_USED. This is documented (docs/reference/statements/in.mdx:
"A set written to disk while it is built cannot be used by the primary key or
data skipping indexes"). CI hit it with --max_bytes_before_external_set 29596895.

Clamp both thresholds to 0 on the existing Random settings limits line (the
runner reads only the first such line); other settings stay random. Same fix
as ClickHouse#126623 for 02844_subquery_timeout_with_break.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 15, 2026
Master gained two key encoders that read a `Nullable` null-map byte as a
value, and both must agree with the rest of this PR:

- `HashedJoinKey::buildRows` (ClickHouse#129328) copies the bytes that `hash128`
  hashes, and its own contract is that every way of building a key gives
  exactly `hash128`. This PR makes `ColumnNullable::updateHashWithValue`
  hash `byte != 0`, so after the merge the copied raw byte broke that
  contract: on the merged tree `SELECT count() FROM t l JOIN t r ON l.s <=> r.s`
  over a Native null map with bytes 0, 1 and 2 aborts on the debug check
  in `buildRange` (AVX2 and NEON builds). It now copies `byte != 0`: 500
  rows, where master gives 300.
- `encodeFixedSizeKeys` (ClickHouse#124907) packs NULL into a one-bit field, so a
  byte 2 set the lowest bit of the column before it. With
  `transform_null_in = 1` and a set spilled to disk, `(0, NULL)` was found
  in `{(1, 0)}`: master 10 rows, 0 in memory. The right side is read back
  from the canonical in-memory keys, so only the probe side carried the
  raw byte.

Both are bit-identical on 0/1 maps. 05210 covers both cases, and gains
a `groupUniqArray(tuple(s))` case for the arena key encoder
(`serializeValueIntoArena`), which no case reached: reverting it left
05210 green, now it gives 3 keys where 2 are correct.

05210 also pins `optimize_if_transform_const_strings_to_lowcardinality`
to 0: the runner randomizes it since ClickHouse#80263, and with it `if` returns
`LowCardinality(Nullable(String))`, which has no `.null` subcolumn, so
the `if` case failed with UNKNOWN_IDENTIFIER on half the runs.

05211 is removed: ClickHouse#129812 made the Iceberg null count use
`countBytesInFilter`, so that reader is master's now and the merge drops
it from this PR (05211 passes on master).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
nihalzp pushed a commit to nihalzp/ClickHouse that referenced this pull request Nov 16, 2026
Query 13 of external_set.xml (a set of 10M tuples of four hashes,
32-byte keys) takes 3.43 s on MasterCI amd and 2.83 s on arm, above
report.py's 2 s single-run limit. About 2 s is the single-threaded build
of the set; the lookups read most of their blocks from the file because
the set is 2.4 times its 128 MiB cache, which is what the query measures.

No existing query number or text changes: 1 query is disabled and 1
smaller copy appended as 14. The copy is the same text at a quarter of
its scale: a set of 2.5M tuples with max_bytes_for_external_set_cache =
33554432 (a quarter of the default), 2.5M lookups in chunks of
max_block_size = 16352 (a quarter of 65409). Measured with perf.py on the
official MasterCI build, L3 capped to one way: the cache hit share
(0.393), block accesses per key (0.419), bytes per block read (11.7 KB),
Bloom skip share (0.485) equal the original's, and the build share of
the query time is 0.467 vs 0.453. On the MasterCI builds before and
after ClickHouse#124907 (70906e3 -> 1d76716), which CI shows moving query 13
1.9-2.1x, the copy keeps 95% of the original's speedup (2.13x vs 2.19x,
both seat orders); the build before ClickHouse#124907 gets the cache setting as an
inert custom setting through the rig's config only.

Query 2 (1.34 s amd, 1.39 s arm) stays: a copy on 15M rows writes 16
parts of 15.0 MB instead of 30 of 16.0 MB, outside the +-5% bound for
bytes per part.

The copy is projected at 0.81 s on amd and 0.67 s on arm: about 32 s
(amd) and 27 s (arm) less query time per master perf job.

Related: ClickHouse#129258

Co-Authored-By: Claude Opus 5.5 <[email protected]>
zoomxi pushed a commit to zoomxi/ClickHouse that referenced this pull request Nov 19, 2026
Since ClickHouse#124907 the runner randomizes max_bytes_before_external_set and
max_bytes_ratio_before_external_set. A draw below the memory of an IN set
(CI: 1215 bytes) makes the set spill while it is built. A spilled set keeps
no explicit elements, so KeyCondition does not use it, partition pruning
keeps all 3 partitions, and EXPLAIN ESTIMATE reports 3 parts instead of 2 in
the "Non-safe cast" section (results stay correct; documented in
docs/reference/statements/in.mdx). The LowCardinality, Nullable and
LowCardinality(Nullable) set sections lose pruning the same way for a
smaller draw.

The test checks pruning by the in-memory set, so clamp both thresholds to 0
with a Random settings limits line; every other setting stays random. Same
fix as ClickHouse#126681 (00673) and ClickHouse#126623 (02844).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Nov 24, 2026
Two cases where a copied bullet was wrong, from the review of
#134278:

- A bullet merged from several entries was copied for any of its pull
  requests. The bullet of #121325 (`cctz` 2026d) and #124249 (2026e) would be
  copied for the backport of the former into `v26.9.3.38-stable` and announce
  the latter, which is not in that release.
- A pull request with an entry in two releases got both of them: #124907 is
  under `Performance Improvement` in 26.11 and under `New Feature` in 26.10,
  with different wording.

The bullets and the pull requests they attribute now make groups, connected by
the attributions. The bullets of a group are copied only if they are all in one
release and every pull request of the group is merged in the changelog
interval; for a backport, the group has to be the original pull request alone.
All other pull requests are requested from GitHub as before.

On `v26.11.1.2942-stable` this leaves 1789 of the 5313 pull requests copied
instead of 1796.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
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-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants