Skip to content

Skip parts by the dictionaries of LowCardinality columns - #130221

Open
alexey-milovidov wants to merge 18 commits into
masterfrom
lc-dictionary-part-pruning
Open

alexey-milovidov wants to merge 18 commits into
masterfrom
lc-dictionary-part-pruning

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Nov 8, 2026 •

Copy link
Copy Markdown
Member

The dictionaries of a LowCardinality column in a Wide part now work like a skip index of type set for the whole part. The filter of a query is evaluated on the dictionary values, and the part is not read if no value can satisfy the filter. No index has to be defined. For typical LowCardinality columns (fewer than 8192 distinct values per part), each part has one small dictionary. For example, it is 24 KB for 100 million rows with 5000 distinct values.

Format. A part can contain exactly one dictionary and still have values outside it. When a dictionary overflows low_cardinality_max_dictionary_size, the keys that do not fit are written as additional keys next to the granules, in the indexes stream. With low_cardinality_use_single_dictionary_for_part, or when the overflow happens in the last granule, such a part looks exactly like a part with a complete dictionary. So the Wide writer marks complete dictionaries. After the last dictionary of a top-level column, it writes zero as the number of keys of the next dictionary, followed by flags that say whether any row uses NULL or the default value.

  • The zero never occurs otherwise, because every dictionary contains the default value.
  • Readers never read past the last dictionary, so older versions ignore the marker. The existing check for a single dictionary per part is taught to accept it.
  • The flags matter because every dictionary also contains NULL and the default value even when no row has them. The filter is evaluated only on the values the rows use, the same way it is when the column is read. Otherwise a CAST of the NULL placeholder to a non-Nullable type would throw. It also lets s = '' skip parts with no empty values.
  • The marker is written for new parts and merges, controlled by the new MergeTree setting write_low_cardinality_complete_dictionaries_marker (default 1). Parts written by older versions, or with the marker disabled, are not pruned. Each such part is read once per column, and the negative result is remembered in the part.

Gating. The step runs after partition pruning, next to pruning by statistics, and is gated like it:

  • It is disabled with FINAL, with on-the-fly mutations and patch parts, with masking policies and row policies, and per part with pending alter or metadata mutations.
  • It is skipped for columns whose type in the part differs from the metadata.
  • A column is used only if every function of the filter that depends on it cannot throw on any value: comparisons, IN, LIKE and match (only with the column as the haystack and a constant pattern that is known to compile), startsWith/endsWith, position, empty, length, case conversions, NULL checks, and logical functions. The expressions inside indexHint are checked as well. So are the functions that depend on no column and are not folded to a constant (e.g. throwIf(1)), because the condition evaluates every argument of and and or. A filter with a stateful or non-deterministic function (e.g. blockSize, rowNumberInBlock, rand) is not used at all. The filter is evaluated on all values of a part, including the rows the query skips by other indexes, so for example a CAST of a NULL that only exists in a skipped granule would otherwise make the query fail.
  • It is skipped when the primary key leaves fewer than min_marks_per_part_to_load_statistics marks per part.
  • Dictionaries larger than max_low_cardinality_dictionaries_bytes_for_part_pruning (1 MiB compressed, by default) are not read, so high-cardinality columns with many dictionaries cost nothing.

It is controlled by the new setting use_low_cardinality_dictionaries_for_part_pruning (default 1). EXPLAIN indexes = 1 shows it as LowCardinalityDictionary.

Benchmark. Run with clickhouse-local on 100 parts of 1M rows, each part with 50 of 5000 hosts in a LowCardinality(String) column (aarch64, shared host):

query 1 thread, off 1 thread, on 96 threads, off 96 threads, on
host = 'host-123' 0.234 s 0.058 s 0.130 s 0.077 s
host = 'nope' 0.247 s 0.018 s 0.148 s 0.028 s
host LIKE 'host-12_' 0.293 s 0.025 s 0.137 s 0.031 s
host != 'host-1' (cannot prune) 0.228 s 0.235 s 0.029 s 0.030 s

The last row is the overhead of reading 100 dictionaries when nothing can be pruned.

Changelog category (leave one):

  • Performance Improvement

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

Queries skip the parts of MergeTree tables where no value of the dictionary of a LowCardinality column can satisfy the filter, like with a skip index of type set, without defining an index. Controlled by the setting use_low_cardinality_dictionaries_for_part_pruning. It applies to Wide parts written with the new MergeTree setting write_low_cardinality_complete_dictionaries_marker, which is enabled by default.

🤖 Generated with Claude Code


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

alexey-milovidov and others added 2 commits November 8, 2026 20:39
The dictionaries of a `LowCardinality` column in a `Wide` part work as a
skip index of type `set` for the whole part: if no value of them can
satisfy the filter, the part is not read. The part has to have all values
of the column in the dictionaries: when a dictionary overflows, the keys
that do not fit are written next to the granules, and such a part looks
exactly like a part with a complete dictionary. So the writer marks the
complete dictionaries: after the last dictionary of a top-level column it
writes zero as the number of keys of the next dictionary. A dictionary
always contains the default value, so the zero never occurs otherwise,
and readers do not read past the last dictionary.

New settings: `write_low_cardinality_complete_dictionaries_marker`
(MergeTree), `use_low_cardinality_dictionaries_for_part_pruning` and
`max_low_cardinality_dictionaries_bytes_for_part_pruning`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Every dictionary has `NULL` and the default value, even if no row has
them. A function that cannot be executed on the default value (e.g. a
`CAST` of `NULL` to a non-Nullable type) threw on them, while reading the
column evaluates it only on the keys of the rows. The marker of complete
dictionaries is now followed by flags telling whether the rows use `NULL`
and the default value, and the other values are left out. This also skips
the parts without the default value for `s = ''`.

Fix the reference of the dangling `IndexDescription` referred to by the
`set` index, the test of overflowed dictionaries (the `INSERT` settings
`low_cardinality_*` do not apply to `MergeTree`), and do not check the
number of parts for `IS NULL`, which can read the subcolumn `null`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fa2ea27]

Summary: ❌

job_name test_name status info comment
Performance Comparison (amd_release, master_head, 1/6) FAIL Performance dashboard
text_index_build_tokenizers #2 FAIL dashboard
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

PR #130221 uses complete LowCardinality dictionaries as implicit part-level set indexes. Reviewed head fa2ea2754fe3eeecd5a7260893e83e8d875f2c32. Block on a remaining exception-safety violation; the default-on planning cost also needs attention. The six prior inline findings are addressed in the current code and are dropped.

Findings

❌ Blockers

  • MergeTreeDataSelectExecutor.cpp:1363: SafeFunctionsChecker accepts comparisons by name although UInt64 versus Decimal64 can throw DECIMAL_OVERFLOW. For separate marked local Wide parts containing (id, v) = (0, 0) and (100, 18446744073709551615), with v LowCardinality(UInt64), WHERE id = 0 AND v = materialize(toDecimal64(0, 0)) succeeds after primary-key pruning. With dictionary pruning enabled and min_marks_per_part_to_load_statistics = 0, the pass instead evaluates the unsigned maximum in the excluded part. DecimalComparisonHelper::convertOneForCompare rejects its conversion to Int64 with decimal_check_overflow = 1. Use argument-aware exception-safety information, such as canThrow, and add regression coverage.

⚠️ Majors

  • MergeTreeDataSelectExecutor.cpp:1495: every query rereads complete dictionaries before the query condition cache and before a small LIMIT can stop reading. The controlled follow-up benchmark, after removing dictionary copies, reports 6.4 → 21.5 ms for LIMIT 10 and 3.0 → 16.6 ms for a repeated selective query with the default condition cache, on 100 local parts with 8000 keys per part. These are measurements of 9783773483b8; the pruning function remains unchanged at the reviewed head. Avoid unnecessary eager reads, cache their bounded results, or retain opt-in behavior until the cost is addressed.
Tests
  • ⚠️ Add a stateless comparison regression with separate parts, LowCardinality(UInt64), a Decimal64 comparison, decimal_check_overflow = 1, and primary-key exclusion of the overflowing value. Compare pruning enabled and disabled. The current Fast test report passes both new tests, but they do not cover this path.
  • ⚠️ Rerun the warm-cache and small-LIMIT benchmarks on the current head before keeping the optimization enabled by default. The latest available performance dashboard run is a736afa7a831; its inventory has no over-threshold client_time changes and does not settle these focused cases.
Missing context / blind spots
  • ⚠️ No ClickHouse binary is available in this review job. The comparison counterexample is established by source tracing, without a runtime reproduction; the requested regression would close that gap. Current regression results come from the head Fast test report.
Final Verdict

Status: ❌ Block

Fix argument-aware exception safety and cover the skipped-part comparison. Address or bound the eager-read overhead and validate the focused performance cases on the current head.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Nov 8, 2026
@alexey-milovidov
alexey-milovidov marked this pull request as ready for review November 8, 2026 22:59
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Nov 8, 2026
alexey-milovidov and others added 3 commits November 9, 2026 00:14
The filter is evaluated on all values of the dictionaries, including the
values of the rows that the query skips by other indexes (e.g. a `NULL`
in a granule skipped by a `bloom_filter` index, as in
`05338_skip_index_lossless_conversion_drop_nullable`). A function that
throws on such a value (a `CAST` of `NULL` to a non-Nullable type, a
conversion of a string) made the query fail. Now a column is used for
pruning only if every function of the filter that depends on it is from
a list of functions that cannot throw on any value: comparisons, `IN`,
`LIKE`, `match`, `startsWith`, `position`, `empty`, `length`, case
conversions, `NULL` checks and logical functions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… dictionaries marker

The `_part` column of a patch part is `LowCardinality`, so its `.dict` stream now
ends with the marker of complete dictionaries: a zero number of keys and the
flags, 16 more uncompressed bytes.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=130221&sha=latest&name_0=PR&name_1=Fast%20test
#130221

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing fa2ea2754 with master c7e7995d9 (stripped binary size, per-symbol sizes and ThinLTO time; 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

146 object files changed (+192.60 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp.o 1.26 MiB 1.38 MiB +127.03 KiB (+9.86%)
src/CMakeFiles/dbms.dir/DataTypes/Serializations/SerializationLowCardinality.cpp.o 229.80 KiB 249.70 KiB +19.89 KiB (+8.66%)

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

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

Job report

alexey-milovidov and others added 3 commits November 11, 2026 09:12
…r more filters

- Reject the filter if it has a stateful or non-deterministic function (`blockSize`,
  `rowNumberInBlock`, `rand`), even if it does not depend on the column: the `set`
  condition evaluates it on the block of dictionary values.
- `like`, `match` and similar are safe only if the pattern does not depend on the
  column, because an invalid pattern from a skipped part throws.
- Check the expressions stored inside `indexHint`, which the `set` condition evaluates.
- Read the dictionaries with `allow_different_codecs`, like the normal reader, because
  adaptive codec selection can compress blocks of one stream with different codecs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…aries

Keep the set of columns with incomplete dictionaries behind a pointer guarded by the
existing `estimates_mutex` instead of a separate mutex and set in every part. The
`Storage memory check` reported +512 KB for `07_many_parts.sql` (1000 parts).

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=130221&sha=519aa18c755dd53d508c51f53652e923a9619d0c&name_0=PR&name_1=Storage%20memory%20check
#130221

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

@snelheidai, please review.

@snelheidai

Copy link
Copy Markdown

I reviewed 9482374 using the PR's CI build (x86_64) and compared use_low_cardinality_dictionaries_for_part_pruning off and on, on the same data.

Correctness: no problems found. I ran 52 filters where some parts are skipped by the primary key. Each gave the same result or the same error with pruning off and on. They covered:

  • String compared with numbers, dates, UUID, IPv4/IPv6, Enum and subquery sets (the type errors are the same either way);
  • LowCardinality(Nullable(String)) with IS NULL, NOT, coalesce, ifNull, assumeNotNull, nullIn and transform_null_in;
  • conditions that mix in another column, such as NOT (s = 'b' AND id > 5), (s = 'a') = (id > 5) and xor;
  • indexHint and FixedString.

Performance: the cost is paid on every query, and on S3 it is large. When the filter uses a LowCardinality column and enough marks are left to read (min_marks_per_part_to_load_statistics), each query reads, decompresses and rebuilds the dictionaries of every Wide part before reading starts. Only the negative result (incomplete dictionaries) is remembered between queries.

The table has 100 Wide parts of 1M rows (124 marks each) and a column s LowCardinality(String) with K distinct values per part. The machine is x86_64 with 4 vCPU. Times are medians in ms for pruning off → on. The number in brackets is the geometric mean of the paired on/off ratios. On local disk I ran 10 interleaved pairs (6 for LIMIT 10, 4 for the repeated query), with the query condition cache off unless noted.

query K = 50 K = 1000 K = 8000
count() WHERE s = 'rare' (1 of 100 parts matches) 39.7 → 7.1 (0.18) 72.0 → 12.4 (0.18) 111.6 → 48.2 (0.44)
count() WHERE s != 'nope' (no part can be skipped) 44.3 → 47.1 (1.05) 85.7 → 94.1 (1.11) 203.8 → 255.0 (1.25)
EXPLAIN ESTIMATE of the previous query (planning only) 3.3 → 6.9 3.5 → 12.5 3.8 → 52.4
SELECT id … WHERE s != 'nope' LIMIT 10, default settings – 7.7 → 16.1 (2.0) 7.5 → 54.2 (7.3)
s = 'rare' repeated, default query condition cache – 3.8 → 10.5 3.7 → 43.9

The last row shows that the query condition cache already makes a repeated selective query cheap without this step. The step then only adds its cost, because it reads the dictionaries again for every query.

On S3 I used an s3 disk without a filesystem cache, a local S3 endpoint with 20 ms to the first byte, and K = 1000. I ran 6 pairs with max_threads = 4 and 4 pairs with 16:

query max_threads = 4 max_threads = 16
count() WHERE s = 'rare' 176 → 603 (3.4) 209 → 213 (1.03)
count() WHERE s != 'nope' 188 → 750 (4.1) 225 → 389 (1.53)
planning only 3.4 → 565 4.8 → 174
LIMIT 10 423 → 766 (2.1) –

The dictionaries are read through loadStatisticsOfPartsInParallel. It makes max_threads synchronous reads at a time, in windows, before the pipeline starts. The normal read makes the same requests with prefetching, overlapped with the data. So with 4 threads, even the query that skips 99 of 100 parts became slower.

Where the time goes. I profiled planning only, with K = 8000 (trace_log and perf):

  • About half of the step is ColumnLowCardinality::insertRangeFrom in deserializeCompleteDictionaries. It hashes every key again into a new dictionary.
  • About a sixth is mayBeTrueOnGranule. Most of that is building the LowCardinality(UInt8) result and running fillHyperrectangle, which materializes the values to compute min and max.
  • The string comparison itself is about 1%.
  • The rest is reading, decompression and deserialization.

Suggestions

  1. Keep the result between queries. Parts are immutable, so the values of complete dictionaries, or the whole MergeTreeIndexGranuleSet, can be cached per part and column with a size limit, as the statistics estimates are. A smaller step: filterPartsByQueryConditionCache already runs in selectRangesToRead, but after this step. Running it first would drop the parts the cache already excludes before their dictionaries are read.
  2. Avoid the copy. Use each deserialized dictionary with its positions as the ColumnLowCardinality it already is, and evaluate the condition on each dictionary separately: the part can match if any dictionary can. With the default of one dictionary per part, this is one call, and the keys are not hashed again. Min and max can be computed from the keys without materializing them, or the pre-check can be skipped, since every value is evaluated anyway.
  3. On remote disks, do not make planning wait for round trips max_threads at a time. Either read with I/O concurrency, or use only dictionaries that are already in memory or in the filesystem cache. As it is, the setting is on by default and makes scans on S3 without a filesystem cache slower.
Reproduction

Run with use_query_condition_cache = 0, except for the LIMIT 10 row and the repeated row. The ratios are geometric means of paired runs. 95% bootstrap intervals: local K = 1000 != 1.11 [1.09, 1.13]; K = 8000 != 1.25 [1.21, 1.28]; = 'rare' K = 1000 0.18 [0.17, 0.19]; S3 != with 4 threads 4.1 [3.7, 4.6]. Latency is taken from system.query_log (query_start_time_microseconds to event_time_microseconds), and the arm order was randomized in each pair.

CREATE TABLE b.t1k (id UInt64, s LowCardinality(String), v UInt32)
ENGINE = MergeTree ORDER BY id
SETTINGS index_granularity = 8192, min_bytes_for_wide_part = 0;  -- storage_policy = 's3_bench' for S3
SYSTEM STOP MERGES b.t1k;
-- for p in 0..99 (K = 50, 1000 or 8000):
INSERT INTO b.t1k SELECT p * 1000000 + number,
    if(p = 37 AND number = 500000, 'rare', concat('svc-', hex(cityHash64(number % K)))), number
FROM numbers(1000000) SETTINGS max_block_size = 1048576, min_insert_block_size_rows = 2000000, min_insert_block_size_bytes = 0;

Dictionary files per part: 1.0 KB (K = 50), 17 KB (K = 1000) and 142 KB (K = 8000), all below max_low_cardinality_dictionaries_bytes_for_part_pruning.

alexey-milovidov and others added 2 commits November 13, 2026 17:50
Following the measurements in the review
#130221 (comment):

- `deserializeCompleteDictionaries` returns each dictionary as a `ColumnLowCardinality`
  that refers to it as it is, instead of copying all of them into one column with
  `insertRangeFrom`, which hashed every key again (about half of the time of the step).
  The condition is evaluated on each dictionary, and the part can match if any can.
- The range of values is not computed before evaluating the condition: it materialized
  every value, while the condition is evaluated on every value anyway.
  `MergeTreeIndexGranuleSet::fillHyperrectangle` is not needed any more and is removed.
- The parts on remote disks are not pruned by the dictionaries: they are read before the
  pipeline starts, a few at a time and without prefetching, so on S3 the round trips cost
  more than the pruning saves.
- The tests use `storage_policy = 'default'`, so they do not depend on the randomized storage.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks for the thorough measurements (#130221 (comment)). Pushed 9783773 (after merging master), addressing part of it:

  • Avoid the copy (suggestion 2). deserializeCompleteDictionaries now returns each dictionary as a ColumnLowCardinality over the deserialized dictionary itself, with no insertRangeFrom and no re-hashing. The condition is evaluated on each dictionary, and the part can match if any of them can. With the default single dictionary per part, that is one call.
  • No min/max pre-check. set_hyperrectangle is set to the whole universe instead of running fillHyperrectangle, which materialized every value. Every value is evaluated anyway. MergeTreeIndexGranuleSet::fillHyperrectangle is gone, so MergeTreeIndexSet is the same as on master again.
  • Remote disks (suggestion 3). Parts with isStoredOnRemoteDisk are no longer pruned by dictionaries, so scans on S3 don't pay the synchronous round trips during planning. The setting's description says so. The tests now pin storage_policy = 'default'.

Both new stateless tests still match their references.

Not done in this change, left for a follow-up:

  • A cross-query cache of the dictionary values per part and column, with a size limit like StatisticsCache. It needs a new server-level cache and settings.
  • Running filterPartsByQueryConditionCache before this step. It currently runs after sampling and is tied to the range-analysis path in selectRangesToRead, so reordering it needs a closer look.

Until the cache exists, the remaining cost on local disks for non-selective filters, and especially for LIMIT queries, is the open question. Whether use_low_cardinality_dictionaries_for_part_pruning should stay on by default is a decision for the author.

@snelheidai

Copy link
Copy Markdown

I reran the benchmark from #130221 (comment) with the CI builds of 9783773 and 9482374, today, on the same machine and data. Times are medians in ms with use_low_cardinality_dictionaries_for_part_pruning off → on. Each table has 100 Wide parts of 1M rows on local disk, with K distinct values per part. The query condition cache is off unless noted.

query K 9482374 9783773
count() WHERE s != 'nope' (no part can be skipped) 50 33.3 → 36.1 32.1 → 34.5
1000 62.2 → 69.6 61.9 → 65.5
8000 148.0 → 182.1 147.1 → 162.6
EXPLAIN ESTIMATE of that query (planning only) 50 3.0 → 5.5 2.9 → 5.1
1000 3.1 → 9.7 2.9 → 6.8
8000 3.0 → 38.8 2.9 → 18.0
SELECT id … WHERE s != 'nope' LIMIT 10, default settings 1000 5.9 → 12.1 5.9 → 9.7
8000 6.5 → 40.1 6.4 → 21.5
s = 'rare' repeated, default query condition cache 1000 2.8 → 8.4 2.8 → 6.2
8000 3.1 → 31.3 3.0 → 16.6
count() WHERE s = 'rare' (1 of 100 parts matches) 50 30.1 → 5.6 29.2 → 5.4
1000 52.6 → 9.4 51.7 → 7.2
8000 80.2 → 32.7 79.6 → 17.4

The step now adds 2.2, 3.9 and 15.1 ms of planning per 100 parts at K = 50, 1000 and 8000; it was 2.6, 6.6 and 35.8 ms. A scan that cannot skip parts is 1.07× slower at K = 1000 and 1.11× at K = 8000 (it was 1.13× and 1.24×). Queries that read little after planning still pay the whole cost. LIMIT 10 is 1.6× slower at K = 1000 and 3.4× at K = 8000, and the repeated selective query is still faster without the step.

On S3, parts on the remote disk are no longer read for pruning. I used an s3 disk without a filesystem cache, 20 ms to the first byte, K = 1000, max_threads = 4 and 12 pairs. count() takes 141 → 143 ms, s = 'rare' 131 → 135 ms (all 100 parts are read) and planning 3.2 → 4.0 ms. With 9482374 these were 188 → 750, 176 → 603 and 3.4 → 565 ms in my previous run.

Value filters on LowCardinality(Nullable(...)) columns no longer skip parts, but the dictionaries are still read. With 9783773, none of s = 'y', s LIKE 'y%', s > 'w', coalesce(s, 'z') = 'z' or ifNull(s, 'z') = 'x' skips a part. Only isNull(s), assumeNotNull(s) = 'y' and transform_null_in filters still do. In 9482374 those filters skipped parts only through the min/max pre-check: for s = 'x' it kept a part holding 'w' and 'y'.

I made a copy of the K = 8000 table with s LowCardinality(Nullable(String)) and no NULLs. On it, count() WHERE s = 'rare' takes 87.0 → 99.2 ms, and all 100 parts are read either way. Planning takes 3.1 → 15.2 ms and reads 14.2 MB of dictionaries. For comparisons, the per-value evaluation can't help: MergeTreeIndexConditionSet::traverseDAG computes is_integer_atom after removing LowCardinality but not Nullable. So an atom of type LowCardinality(Nullable(UInt8)), such as s = 'y', becomes UNKNOWN_FIELD. All results are correct.

Where the rest of the time goes, from trace_log while planning at K = 8000:

  • reading and LZ4-decompressing the dictionaries: about 27%;
  • deserializing the keys: about 15%;
  • building the LowCardinality(UInt8) result of the comparison (ColumnUnique::uniqueInsertRangeFrom and ReverseIndex::insert, one hash insert per key): about 35%;
  • the string comparison itself: about 3%.

So a cache of the dictionary values alone would remove about half of the step.

Correctness: the 52 filters from the previous comment give the same results as with 9482374, with pruning off and on. I also made parts with two and three complete dictionaries. On them, 33 filters on LowCardinality(String) and LowCardinality(Nullable(String)) give the same results off and on, and a value that is only in a part's third dictionary keeps that part.

Reproduction

Binaries: CI amd_release builds of 9783773 (584572eb, merged into master d457c08) and 9482374 (ba73688a), x86_64, 4 vCPU. The tables are those of the previous comment, with max_bytes_to_merge_at_max_space_in_pool = 1 and max_bytes_to_merge_at_min_space_in_pool = 1 added, because SYSTEM STOP MERGES does not survive the restart needed to switch binaries. Both binaries ran on the same data one after the other, and their "off" times agree within 4%.

Latency is taken from system.query_log, and the arm order is randomized in each pair. I ran 10 pairs, 6 for LIMIT 10 and the repeated query. Paired on/off ratios (geometric mean, 95% bootstrap interval) for the scan that can't skip parts:

  • K = 1000: 1.131 [1.073, 1.193] → 1.069 [1.053, 1.096];
  • K = 8000: 1.238 [1.218, 1.266] → 1.113 [1.093, 1.134].

For LIMIT 10 the ratios were 2.07 → 1.63 at K = 1000 and 6.33 → 3.35 at K = 8000.

Parts with several dictionaries: MergeTree writes take low_cardinality_max_dictionary_size from the server profile, not from the INSERT. So I set it to 4 there and used index_granularity_bytes = 0 with index_granularity = 3 (LowCardinality(String)) or 2 (LowCardinality(Nullable(String))). Each granule then fills one dictionary exactly, and no keys overflow.

The Nullable case in clickhouse-local:

SET min_marks_per_part_to_load_statistics = 0, optimize_use_implicit_projections = 0, use_query_condition_cache = 0;
CREATE TABLE tn (id UInt64, s LowCardinality(Nullable(String))) ENGINE = MergeTree ORDER BY id
SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0,
    max_bytes_to_merge_at_max_space_in_pool = 1, max_bytes_to_merge_at_min_space_in_pool = 1;
INSERT INTO tn VALUES (0, NULL), (1, 'x');
INSERT INTO tn VALUES (2, 'y'), (3, 'w');
INSERT INTO tn VALUES (4, ''), (5, 'v');
SELECT sum(parts) FROM (EXPLAIN ESTIMATE SELECT id FROM tn WHERE s = 'y');  -- 94823743: 2, 9783773: 3

alexey-milovidov and others added 3 commits November 18, 2026 05:39
…pruning

Master moved `ReadFromMergeTree::IndexType` and its `toString` to `PlanIndexType` in
`PlanIndexStats.h`, so `LowCardinalityDictionary` is added there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…lity(Nullable)` by values

The `set` index condition evaluates every argument of `and` and `or` (as `__bitBoolMaskAnd` and
`__bitBoolMaskOr`), including subtrees that do not depend on any column, such as `throwIf(1)`. So
`s = 'a' OR throwIf(1)` failed with `use_low_cardinality_dictionaries_for_part_pruning = 1`,
although the row filter short-circuits it. `SafeFunctionsChecker` now applies the exception-safety
check to every function that the `set` index evaluates: those that depend on the column, and those
that depend on no column at all and are not folded to a constant. Subtrees that depend on another
column are replaced by an unknown value by the `set` index and are not evaluated.

Also, an atom over a `LowCardinality(Nullable(...))` column has the type
`LowCardinality(Nullable(UInt8))`, which `MergeTreeIndexConditionSet::traverseDAG` did not recognize
as an integer, so it became `UNKNOWN_FIELD`. The dictionaries of such columns were read and then not
used. Now `Nullable` is removed after `LowCardinality`, so `s = 'y'` prunes parts (and granules of a
`set` skip index) for such columns. The NULL mask is handled by the existing `ifNull` wrapper.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…_analysis_reuse_partition`

With `min_marks_per_part_to_load_statistics = 0` and Wide parts (randomized in CI), the part with only
`'AAP'` is now skipped by its dictionary, which changes the numbers the test pins about the reuse of
partition pruning by projection analysis.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=130221&sha=9783773483b8abb3d03985ea05d8fb9b0533bccd&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29
#130221

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks for the rerun. Pushed a736afa (after merging master):

  • LowCardinality(Nullable(...)) filters now prune by values. As you found, MergeTreeIndexConditionSet::traverseDAG removed LowCardinality but not Nullable when checking whether an atom is an integer, so LowCardinality(Nullable(UInt8)) atoms such as s = 'y' became UNKNOWN_FIELD, and the dictionaries were read for nothing. It now removes both, and the NULL mask goes through the existing ifNull wrapper. On your reproduction, s = 'y' reads 1 part out of 3 (it was 3). LIKE 'y%' and s > 'w' prune too. The results are the same as with the pruning off, also with != and NOT. The same applies to a set skip index on such a column, which now skips granules for these filters. The existing set-index tests pass.
  • The blocker from the review thread (s = 'a' OR throwIf(1)) is fixed: column-independent functions that the set index evaluates are checked too.
  • 01710_projection_analysis_reuse_partition failed in CI because, with randomized min_marks_per_part_to_load_statistics = 0 and Wide parts, the 'AAP' part is now skipped by its dictionary. The test pins the numbers of the projection analysis, so the pruning is disabled there.

Not done here: the cross-query cache of dictionary values, which would remove the cost of reading and decompressing (about half of the step according to your trace_log), and the cost of building the LowCardinality(UInt8) result. These are left for a follow-up. The planning overhead on queries that read little remains until then.

@snelheidai

Copy link
Copy Markdown

I checked a736afa with its CI build. LowCardinality(Nullable(...)) value filters now skip parts, and I found no wrong results. One problem remains: for these columns, the complete-dictionaries marker records the default value incorrectly.

The default-value flag. uses_default is set from getDefaultValueIndex(). For a Nullable dictionary, that is the index of NULL (0). The empty string is at getNestedTypeDefaultValueIndex() (1). So a LowCardinality(Nullable(String)) part gets COMPLETE_DICTIONARIES_HAS_DEFAULT when it has NULLs, and not when it has empty strings. Parts holding ('d', 'e'), ('', 'f') and (NULL, 'g') are written with flags 0, 0 and 3 instead of 0, 2 and 1.

deserializeCompleteDictionaries checks the same index, so it always keeps '', and the results are correct. But filters that are true for '', such as s = '', empty(s), s < 'c' or s IN ('', 'zz'), never skip a part on these columns. For s = '' all 3 parts above are read; with LowCardinality(String), only the second one is. The flags are stored in the parts. If only the reader were fixed later, it would skip parts written by this version that hold '' but no NULL, and s = '' would miss their rows. So both sides should change together. I have not built this:

--- a/src/DataTypes/Serializations/SerializationLowCardinality.cpp
+++ b/src/DataTypes/Serializations/SerializationLowCardinality.cpp
@@ -448,7 +448,7 @@
         {
             if (dictionary_type->isNullable() && i == dictionary->getNullValueIndex() && !(flags & COMPLETE_DICTIONARIES_HAS_NULL))
                 continue;
-            if (i == dictionary->getDefaultValueIndex() && !(flags & COMPLETE_DICTIONARIES_HAS_DEFAULT))
+            if (i == dictionary->getNestedTypeDefaultValueIndex() && !(flags & COMPLETE_DICTIONARIES_HAS_DEFAULT))
                 continue;
             positions_data.push_back(i);
         }
@@ -768,7 +768,7 @@
         if (!low_cardinality_state->uses_null && dictionary_type->isNullable())
             low_cardinality_state->uses_null = containsIndex(*positions, global_dictionary->getNullValueIndex());
         if (!low_cardinality_state->uses_default)
-            low_cardinality_state->uses_default = containsIndex(*positions, global_dictionary->getDefaultValueIndex());
+            low_cardinality_state->uses_default = containsIndex(*positions, global_dictionary->getNestedTypeDefaultValueIndex());
     }
 
     bool need_additional_keys = !keys->empty();

Timings. These are medians in ms with use_low_cardinality_dictionaries_for_part_pruning off → on, from 10 pairs (6 for 9783773). The table is the K = 8000 one from my last comment, with s LowCardinality(Nullable(String)) and no NULLs:

query 9783773 a736afa
count() WHERE s = 'rare' 87.0 → 99.2 (100 parts read) 90.4 → 20.4 (1 part read)
count() WHERE s != 'nope' 154.5 → 168.6 159.0 → 176.9
EXPLAIN ESTIMATE of that query (planning only) 3.1 → 15.2 3.3 → 20.9

The values are now evaluated, so planning takes 5 ms more per 100 parts than with 9783773. That is close to LowCardinality(String) with the same K in the same run: 3.2 → 18.6 ms.

Correctness. I ran 80 filter shapes on a table with 12 parts and 8-row granules. Some granules hold only NULLs, some are mixed, and some have no NULLs; some parts have no NULLs or no empty strings. The table has set skip indexes on a LowCardinality(Nullable(String)) and a LowCardinality(Nullable(UInt32)) column. As controls, it also has Nullable(String), Nullable(UInt32) and LowCardinality(String) columns with the same values and indexes. The shapes include =, !=, NOT, comparisons, IN and NOT IN with NULL and with transform_null_in, LIKE, ILIKE, match, isNull, coalesce, ifNull, assumeNotNull, nullIf, if, multiIf, xor, and AND or OR with another column.

Each query ran with the skip index (bulk and non-bulk filtering) and the dictionary pruning on and off. In all 981 queries, the result (or error) matches the one with both off. With the skip index, the LowCardinality(Nullable) columns now select exactly the same granules as the Nullable columns, for every filter. Over the string filters they read 11343 of 22619 marks; master read 19874.

s = 'a' OR throwIf(1) on a table where every row is 'a' now succeeds with the pruning. With an explicit set index on the column it still fails, as it does on master.

Reproduction

Binaries: the CI amd_release build of a736afa (bfe11eac, merged into master e87f099), and master c3ec2bd for the master numbers; x86_64, 4 vCPU. The timings use the method of my previous comment, with randomized arm order and the query condition cache off.

The flags are the last 8 bytes of the decompressed s.dict.bin (clickhouse compressor --decompress). In clickhouse-local:

SET min_marks_per_part_to_load_statistics = 0, optimize_use_implicit_projections = 0, use_query_condition_cache = 0;
CREATE TABLE tn (id UInt64, s LowCardinality(Nullable(String))) ENGINE = MergeTree ORDER BY id
SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0,
    max_bytes_to_merge_at_max_space_in_pool = 1, max_bytes_to_merge_at_min_space_in_pool = 1;
INSERT INTO tn VALUES (0, 'd'), (1, 'e');
INSERT INTO tn VALUES (2, ''), (3, 'f');
INSERT INTO tn VALUES (4, NULL), (5, 'g');
SELECT sum(parts) FROM (EXPLAIN ESTIMATE SELECT id FROM tn WHERE s = '');  -- 3; 1 with LowCardinality(String)

alexey-milovidov and others added 2 commits November 21, 2026 09:58
…` in the complete dictionaries marker

The flag of the default value was set from `getDefaultValueIndex`, which is the index of `NULL` for a `Nullable`
dictionary, so a part was marked as having the default value when it had `NULL`, and not when it had the default value
of the nested type. The reader used the same index and always kept the default value, so the results were correct,
but filters that are true for the default value (`s = ''`, `empty(s)`) never skipped a part.
Both sides now use `getNestedTypeDefaultValueIndex`.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…t pattern

Pruning by `LowCardinality` dictionaries evaluates every argument of `and` and `or`, and the expressions inside of
`indexHint`. A pattern that is not folded to a constant, such as `materialize('[')`, is compiled by the row filter
only for the rows that reach the function, and a constant pattern inside of `indexHint` is not compiled at all,
so a query with an invalid pattern that succeeds without the pruning failed with `CANNOT_COMPILE_REGEXP` or
`CANNOT_PARSE_ESCAPE_SEQUENCE`. Now the pattern must be a constant that is known to compile.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @snelheidai, thank you, the default-value flag is fixed in c1797cd exactly as you proposed: both the writer and the reader use getNestedTypeDefaultValueIndex, so the flag means the default value of the nested type and NULL has only its own flag. No version with the old meaning was released, so the format does not need a transition. With the three parts of 05617_low_cardinality_dictionary_part_pruning_safety ((NULL, x), (y, w), ('', v)), s = '', empty(s), s IN ('', 'zz') and s < 'c' now read 1 part instead of 3, and NOT (s = 'x') reads 2 instead of 3; these are added to the test.

Also in this update (02b540b): the remaining review blocker. like and match are used for pruning only with a constant pattern that is known to compile, so s = 'a' OR match(s, materialize('[')) and invalid patterns inside of indexHint no longer fail with the pruning enabled. Master is merged in. The only red check on the previous commit was the unresolved review thread gate.

alexey-milovidov and others added 2 commits November 24, 2026 08:34
…nder version `26.12`

The `settings_changes_history` style check requires the records of the settings added by this change
to be under the current version, which is `26.12` after the merge of master:
`use_low_cardinality_dictionaries_for_part_pruning`, `max_low_cardinality_dictionaries_bytes_for_part_pruning`
and the MergeTree setting `write_low_cardinality_complete_dictionaries_marker`.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=130221&sha=02b540bb0c804e4f680eb3de7e2de09a97a34c31&name_0=PR&name_1=Style%20check
#130221

Co-Authored-By: Claude Fable 5.2 <[email protected]>
}

static inline const std::unordered_set<std::string_view> safe_functions = {
"equals", "notEquals", "less", "greater", "lessOrEquals", "greaterOrEquals",

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.

[Blocker] Check comparison argument types before declaring them exception-safe

The comparison names here are not sufficient to establish exception safety. With decimal_check_overflow = 1, comparing UInt64 with Decimal64 can throw: DecimalComparisonHelper::convertOneForCompare converts the unsigned value to Int64 and rejects values above INT64_MAX. FunctionComparison::canThrowIfKnown already reports this type combination as throwing, but this checker ignores it.

For example, take a local marked Wide table (id UInt64, v LowCardinality(UInt64)) ORDER BY id, with merges stopped and (0, 0) and (100, 18446744073709551615) inserted into separate parts. Enable allow_suspicious_low_cardinality_types when creating it. Trace this query with dictionary pruning off and on:

SELECT count() FROM t
WHERE id = 0 AND v = materialize(toDecimal64(0, 0))
SETTINGS min_marks_per_part_to_load_statistics = 0,
         optimize_move_to_prewhere = 0,
         optimize_use_implicit_projections = 0,
         use_statistics_for_part_pruning = 0,
         decimal_check_overflow = 1,
         use_low_cardinality_dictionaries_for_part_pruning = 1;

Without this pass the primary key excludes the second part and the result is 1. This pass evaluates its dictionary before primary-key pruning, so the accepted equals reaches DECIMAL_OVERFLOW on the unsigned maximum. This is a source-derived counterexample; no binary was run in this review job.

Use argument-aware exception-safety information for the accepted functions, including comparisons, rather than adding another name exception. Add a focused regression for this skipped-part path.

if (file_size > max_dictionaries_bytes)
continue;

auto file = part->getDataPartStorage().readFile(file_name, context->getReadSettings().adjustBufferSize(file_size), file_size);

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.

[Major] Avoid reading every dictionary before cache hits and small LIMIT reads

Complete dictionaries are read and evaluated again on every query here. Only incomplete dictionaries are remembered, and selectRangesToRead calls this pass before filterPartsByQueryConditionCache. The marks threshold considers the primary key, so it also admits a query that will actually read very little because of a warm condition cache or a small LIMIT.

The repeat benchmark after the dictionary-copy optimization still measured SELECT id ... WHERE s != 'nope' LIMIT 10 at 6.4 → 21.5 ms, and a repeated selective query with the default condition cache at 3.0 → 16.6 ms, on 100 local parts with 8000 keys per part. Those measurements are for 9783773483b8, not the current head; however, filterPartsByLowCardinalityDictionaries is unchanged from that revision, including this unconditional read and its position before the cache.

Please avoid this work for already-excluded or early-terminating reads, reuse bounded cached dictionary data, or keep the optimization opt-in until these cases are addressed. Rerun the focused warm-cache and small-LIMIT cases on the current head to establish the default-on cost.

@snelheidai

Copy link
Copy Markdown

I checked fa2ea27 with its CI build (x86_64, 4 vCPU).

The Decimal blocker in #130221 (comment) reproduces. The query in that review comment returns 1 with use_low_cardinality_dictionaries_for_part_pruning = 0 and fails with DECIMAL_OVERFLOW when the setting is enabled. A plain constant (v = toDecimal64(0, 0), without materialize) and v < toDecimal64(5, 0) fail the same way, also with optimize_move_to_prewhere = 1. With default query settings, it fails on a table without column statistics. With the default auto_statistics_types, statistics pruning skipped the part with the large value first in my tests, so the query succeeded.

Reproduction with default query settings
SET allow_suspicious_low_cardinality_types = 1;
CREATE TABLE t (id UInt64, v LowCardinality(UInt64)) ENGINE = MergeTree ORDER BY id
SETTINGS auto_statistics_types = '', min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0,
    max_bytes_to_merge_at_max_space_in_pool = 1, max_bytes_to_merge_at_min_space_in_pool = 1;
INSERT INTO t SELECT number, number % 10 FROM numbers(1100000);
INSERT INTO t VALUES (1000000000, 0), (1000000001, 18446744073709551615);
SELECT count() FROM t WHERE id < 100000000 AND v = toDecimal64(0, 0);
-- 110000 with use_low_cardinality_dictionaries_for_part_pruning = 0, DECIMAL_OVERFLOW with the default

The first part has 135 granules, which passes min_marks_per_part_to_load_statistics = 64 for 2 parts.

The planning cost in #130221 (comment) is unchanged. Medians in ms with the pruning off → on, from 10 pairs in random order. The tables were rebuilt as in #130221 (comment): 100 Wide parts of 1M rows, with K distinct values per part.

query K = 1000 K = 8000
SELECT id … WHERE s != 'nope' LIMIT 10, default settings 5.7 → 9.6 6.6 → 22.3
s = 'rare' repeated, default query condition cache 2.6 → 6.1 2.9 → 16.5
EXPLAIN ESTIMATE (planning only) 2.9 → 6.7 3.0 → 18.6
count() WHERE s = 'rare', cache off (1 of 100 parts matches) 53.0 → 7.0 80.5 → 17.9

All values are within 1.3 ms of those for 9783773.

Both fixes from your last update work. LowCardinality(Nullable(String)) parts holding ('d', 'e'), ('', 'f') and (NULL, 'g') now get flags 0, 2 and 1. On the three parts of 05617, the filters you listed read 1 part (2 for NOT (s = 'x')), with the same results as with the pruning off. The like and match cases with materialize('['), a trailing escape, and invalid patterns in indexHint now give the same results with the pruning on, and valid patterns still prune. The 981 queries from #130221 (comment) show no mismatches.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants