Repository navigation
Skip parts by the dictionaries of LowCardinality columns - #130221
alexey-milovidov wants to merge 18 commits into
Conversation
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]>
|
Workflow [PR], commit [fa2ea27] Summary: ❌
AI ReviewSummaryPR #130221 uses complete Findings❌ Blockers
Tests
Missing context / blind spots
Final VerdictStatus: ❌ 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. |
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]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes146 object files changed (+192.60 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units2401 translation units recompiled, 11721 s compile time in total, 2401 of them have a recent master baseline. |
…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]>
|
@snelheidai, please review. |
|
I reviewed 9482374 using the PR's CI build (x86_64) and compared 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:
Performance: the cost is paid on every query, and on S3 it is large. When the filter uses a The table has 100 Wide parts of 1M rows (124 marks each) and a column
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
The dictionaries are read through Where the time goes. I profiled planning only, with K = 8000 (
Suggestions
ReproductionRun with 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 |
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]>
|
🕵 Thanks for the thorough measurements (#130221 (comment)). Pushed 9783773 (after merging master), addressing part of it:
Both new stateless tests still match their references. Not done in this change, left for a follow-up:
Until the cache exists, the remaining cost on local disks for non-selective filters, and especially for |
|
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
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. On S3, parts on the remote disk are no longer read for pruning. I used an Value filters on I made a copy of the K = 8000 table with Where the rest of the time goes, from
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 ReproductionBinaries: CI Latency is taken from
For Parts with several dictionaries: The 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 |
…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]>
|
🕵 Thanks for the rerun. Pushed a736afa (after merging master):
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 |
|
I checked a736afa with its CI build. The default-value flag.
--- 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
The values are now evaluated, so planning takes 5 ms more per 100 parts than with 9783773. That is close to 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 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
ReproductionBinaries: the CI The flags are the last 8 bytes of the decompressed 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) |
…` 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]>
|
🕵 @snelheidai, thank you, the default-value flag is fixed in c1797cd exactly as you proposed: both the writer and the reader use Also in this update (02b540b): the remaining review blocker. |
…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", |
There was a problem hiding this comment.
[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); |
There was a problem hiding this comment.
[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.
|
I checked fa2ea27 with its CI build (x86_64, 4 vCPU). The Reproduction with default query settingsSET 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 defaultThe first part has 135 granules, which passes 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.
All values are within 1.3 ms of those for 9783773. Both fixes from your last update work. |
The dictionaries of a
LowCardinalitycolumn in aWidepart now work like a skip index of typesetfor 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 typicalLowCardinalitycolumns (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. Withlow_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 theWidewriter 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 usesNULLor the default value.NULLand 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 aCASTof theNULLplaceholder to a non-Nullabletype would throw. It also letss = ''skip parts with no empty values.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:
FINAL, with on-the-fly mutations and patch parts, with masking policies and row policies, and per part with pending alter or metadata mutations.IN,LIKEandmatch(only with the column as the haystack and a constant pattern that is known to compile),startsWith/endsWith,position,empty,length, case conversions,NULLchecks, and logical functions. The expressions insideindexHintare 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 ofandandor. 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 aCASTof aNULLthat only exists in a skipped granule would otherwise make the query fail.min_marks_per_part_to_load_statisticsmarks per part.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 = 1shows it asLowCardinalityDictionary.Benchmark. Run with
clickhouse-localon 100 parts of 1M rows, each part with 50 of 5000 hosts in aLowCardinality(String)column (aarch64, shared host):host = 'host-123'host = 'nope'host LIKE 'host-12_'host != 'host-1'(cannot prune)The last row is the overhead of reading 100 dictionaries when nothing can be pruned.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Queries skip the parts of
MergeTreetables where no value of the dictionary of aLowCardinalitycolumn can satisfy the filter, like with a skip index of typeset, without defining an index. Controlled by the settinguse_low_cardinality_dictionaries_for_part_pruning. It applies toWideparts written with the new MergeTree settingwrite_low_cardinality_complete_dictionaries_marker, which is enabled by default.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/130221]