Repository navigation
Automatic LowCardinality serialization based on uniq statistics - #107436
alexey-milovidov wants to merge 152 commits into
Conversation
Adds a new per-part serialization kind `LOW_CARDINALITY`, analogous to the existing automatic `Sparse` serialization. A `String` or `FixedString` column whose declared data type is not `LowCardinality` can now be stored on disk in dictionary-encoded form when it has a `uniq` statistic with a low cardinality estimate. The decision is made at write time from the existing `uniq` statistic, without any change to statistics serialization. In `MergeTreeDataWriter`, after the sparse decision, a `String`/`FixedString` column that has a `uniq` statistic with an estimate not exceeding the new MergeTree setting `max_uniq_number_for_low_cardinality` (default `0`, i.e. disabled), and that was not already chosen for `Sparse`, is stored with `SerializationLowCardinality`. Such a column flows through the query pipeline as a non-native `ColumnLowCardinality` carried under its non-`LowCardinality` data type. A new `is_native` flag on `ColumnLowCardinality` makes `getDataType` report the nested type, so the "column class matches data type" invariant holds. The column is materialized to a full column at the boundaries that require it: `removeSpecialRepresentations` (aggregation, joins, squashing, blocks), the merge-input materialization in `IMergingAlgorithm`, and functions that do not handle `LowCardinality` themselves (`IFunction`). The `optimize_functions_to_subcolumns` pass skips columns stored as non-native `LowCardinality`, since their dictionary encoding does not expose the data type's regular subcolumns. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [67881f3] Summary: ❌
AI ReviewSummaryAdds opt-in experimental automatic Consumers traced for the new representation: column lifecycle operations preserve Findings❌ Blockers
Missing context / blind spots
Final VerdictStatus: ❌ Block Normalize automatic encoding before insert deduplication hashing and cover an identical retry across a source merge that changes its serialization. |
|
Thanks for the continuation, but I think it still will be better to implement refactoring first. This will be more sustainable in the long term. Don't you mind if I continue refactoring of serializations and enabling automatic low cardinality this week? |
Fixes the `02995_new_settings_history` failure: a newly added MergeTree setting must be recorded in `SettingsChangesHistory.cpp`. Added `max_uniq_number_for_low_cardinality` under version 26.6. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107436&sha=c56f25e715f0a1d4172aa8f476f321caf34e939e&name_0=PR&name_1=Fast%20test PR: #107436 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… writes A column selected for automatic `LowCardinality` serialization is stored with `SerializationLowCardinality`, which requires a `ColumnLowCardinality` on the write path. `MergedBlockOutputStream` builds that representation in `convertToSerializations`, but `MergedColumnOnlyOutputStream` (used by vertical merges and by mutations that rewrite some columns) wrote the incoming block directly. The merge/mutation pipeline materializes such columns back to full columns, so `serializeBinaryBulkWithMultipleStreams` received a `ColumnString` and raised `Bad cast from type DB::ColumnString to DB::ColumnLowCardinality` (the part serialization still says `LOW_CARDINALITY`). Route column-only writes through the same `convertToSerializations`, using the part's serialization infos, and record `new_serialization_infos` from the converted block. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…y or skip indexes When a column selected for automatic `LowCardinality` serialization is part of the primary key or a skip index, `MergeTreeDataPartWriterWide::write` reused the materialized full column from `primary_key_block`/`skip_indexes_block` (built for index calculation by `getIndexBlockAndPermute`) to write the data stream. `SerializationLowCardinality` cannot serialize that full column, so writing such a column with unsorted input (e.g. `ORDER BY` on the encoded column) raised `Bad cast from type DB::ColumnString to DB::ColumnLowCardinality`. Skip the key/index column reuse for columns with the `LOW_CARDINALITY` kind and write the data stream from the permuted, dictionary-encoded `block_to_write` column instead. The materialized column is still used for index calculation. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…le hints Two related issues in `SerializationInfo`: - `createWithType` (used by `ALTER ... MODIFY COLUMN` that changes a column's type) preserved every non-`SPARSE` kind. An automatic `LowCardinality` `String` column altered to a non-String type kept the `LOW_CARDINALITY` kind without re-checking the `uniq` statistic, building a dictionary-encoded column for a type that may not even be able to be inside a `LowCardinality`. Drop the kind unless the new type is still a `String`/`FixedString`. - The per-table serialization hint kept `LOW_CARDINALITY` sticky: `remove` decided the kind from the current aggregate, so removing the last contributing part left the hint as `LOW_CARDINALITY` until a full reset, needlessly disabling subcolumn rewrites in `FunctionToSubcolumnsPass`. Track the number of contributing infos in `Data` and stop reporting `LOW_CARDINALITY` once it reaches zero. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ations and ALTER Covers the write paths beyond the initial INSERT that previously raised `Bad cast from type DB::ColumnString to DB::ColumnLowCardinality` or kept the encoding incorrectly: a vertical merge of a non-key encoded column, the encoded column as the sort key with unsorted input, an `ALTER ... MODIFY COLUMN` that changes the type away from `String` (the `LowCardinality` kind must be dropped), and a mutation that rewrites the encoded column. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
@CurtizJ, yes, that will be fantastic! |
|
Interesting if the refactoring has been done. I don't see the link and don't remember it. |
…y-serialization # Conflicts: # src/Storages/MergeTree/MergeTreeSettings.cpp # src/Storages/MergeTree/MergedColumnOnlyOutputStream.cpp
|
I tried to do the refactoring here. But I don't like the result. The idea was to move inlined data from serializations into statistics and calculate fast sampled statistics when no regular statistics are available ( If we simplify it and add a switch with format setting (use either the old format with inlined data for sparse serialization or the new one with statistics), it will be much better. But users may accidentally lose sparse serialization if they disable statistics. Also, sparse serialization will be lost for zero-level parts if the materialization of statistics is disabled for inserts (the current default). Maybe that's ok, and we should proceed with this solution. |
…ialization `SerializationInfoByName` creates entries only for the columns eligible for sparse serialization, and no entries at all when sparse serialization is disabled with `ratio_of_defaults_for_sparse_serialization = 1`. Automatic `LowCardinality` serialization piggybacked on those entries, so the whole feature silently stopped working in that case: `MergeTreeDataWriter` skipped every eligible column, and `MergeTask` and `MutateTask` dropped the kind, so a merge or a mutation would silently decode an already encoded column. The per-table serialization hints were affected too, which made `FunctionToSubcolumnsPass` rewrite `length(s)` to `s.size` for a column that has no `.size` stream on disk. Create the missing `SerializationInfo` entries for eligible `String`/`FixedString` columns in all four places, and aggregate the source parts' kinds on merge regardless of the sparse settings. `FunctionToSubcolumnsPass` consulted the hints on every rewrite candidate, and `MergeTreeData::getSerializationHints` takes the parts lock and clones the whole map. Guard it with a cheap flag maintained next to the hints, so that queries against tables without such a column do not pay for the lookup. This is the reason for the CI failure of `04340_auto_low_cardinality_serialization_merges`, whose randomized settings included `ratio_of_defaults_for_sparse_serialization = 1.0`.
…aries Parts of the same table can be stored with and without automatic `LowCardinality` serialization, so chunks of the same column arrive with different in-memory representations, exactly like they do for `Sparse`. Every boundary that combines chunks therefore has to materialize the non-native representation, and several were missing: - `MergeSorter` only called `convertToFullIfSparse`, so a cursor could compare a `ColumnString` against a non-native `ColumnLowCardinality`, and the merged output was built by inserting ranges of one into the other. - `RemovingSparseTransform` declares a materialized output header but left the encoding in place. - `IExecutableFunction::executeWithoutSparseColumns` handled the encoding only for functions that opt out of the default `LowCardinality` implementation. The common path detects low cardinality from the argument *types*, and the data type of such a column is not `LowCardinality`, so the raw `ColumnLowCardinality` reached `executeImpl`. Replaced both with a single guard at the top of the function. - `NativeWriter` materializes for clients too old for custom serializations, but only `Sparse`. Also restrict the new full-column source handling in `ColumnLowCardinality::insertFrom` and `insertRangeFrom` to non-native columns: for a genuine `LowCardinality(T)` column a full source is still a bug, and silently converting it would hide that.
…umns A column stored with automatic `LowCardinality` serialization is dictionary-encoded, so the substreams of its declared data type do not exist in the part. `FunctionToSubcolumnsPass` no longer rewrites `length(s)` to `s.size` for such a column, but a user can still write `s.size` directly, because the declared `String` type exposes the subcolumn. That failed deep inside the substream lookup with `There is no subcolumn size in type String`. Reject it in `IMergeTreeReader` with a message that names the column and the part, and document the limitation on `max_uniq_number_for_low_cardinality`. Reading the subcolumn by materializing the full column needs a serialization that reads the dictionary and the indexes and then extracts the subcolumn in memory, which is left for a separate change.
`convertToSerializations` runs for every block written to a part and asked `SerializationInfoByName` for the kind stack of each column by value, which allocates. Look the kinds up in place instead, and let `SerializationInfo::getKindStack` return a reference.
`04338_auto_low_cardinality_serialization` listed all of `system.parts_columns`, so the randomized `enable_block_offset_column` and `enable_block_number_column` added `_block_offset` and `_block_number` rows to the output. Filter the persistent virtual columns out. Add `04869_auto_low_cardinality_serialization_transparency` covering the cases that were broken: the setting taking effect with `ratio_of_defaults_for_sparse_serialization = 1` (including the optimizer still skipping the subcolumn rewrite), an explicit `lc.size` read being rejected, and a table with mixed `Default` and `LowCardinality` active parts being sorted, aggregated, joined and merged.
…LowCardinality `recursiveRemoveLowCardinality` converts the future result of a short circuit argument through `ColumnFunction::recursivelyConvertResultToFullColumnIfLowCardinality`, which cannot distinguish native from non-native `LowCardinality`. Sharing that branch with `recursiveRemoveNonNativeLowCardinality` would materialize genuine `LowCardinality(T)` results at boundaries such as `removeSpecialRepresentations`, which previously left them alone.
…ng transforms `PartialSortingTransform` keeps the threshold row of a previous chunk and compares the next chunk against it, and `FinishSortingTransform` compares the tail of the previous chunk against the next one. With a table whose active parts are partly stored with automatic `LowCardinality` serialization, the two sides can have different in-memory representations, and `ColumnLowCardinality::compareAt` used to `assert_cast` its right hand side, so the server crashed with a null dereference. It reproduced through the top-k threshold tracker in `04869_auto_low_cardinality_serialization_transparency` under randomized settings. Materialize in both transforms, and let `ColumnLowCardinality::compareAt` of a non-native column accept a full column of the same data type instead of reading past a bad cast. Such a column is never `Nullable`, so comparing against the dictionary's nested column is exact. For a genuine `LowCardinality(T)` column the strict check stays. Cover the two transforms explicitly in the test: the partial sorting threshold needs either a limit of at least `min_limit_for_partial_sort_optimization` rows or the top-k tracker, and the finish sorting path needs a read-in-order sort key prefix.
With `enable_parsing_to_custom_serialization = 1`, input formats parse into the representation given by the table-level serialization hints, so after a part is stored with automatic `LowCardinality` serialization, later blocks that are stored as plain `String`/`FixedString` (high cardinality, or the threshold lowered to zero) arrive as `ColumnLowCardinality`. `MergedBlockOutputStream::writeImpl` already materializes them through `convertToSerializations`; the test pins this down for `TSV`, `CSV` and `JSONEachRow` inserts, wide parts, a sorting key and a skip index. Address review: #107436 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged current |
|
The merge does not clear the The red stops once a release that carries #125293 is the previous release: a 26.10 stable with its backport, or the first 26.11 stable. #125293 has no |
The test relies on `uniq` statistics built on insert to choose automatic `LowCardinality` serialization, but `materialize_statistics_on_insert` is randomized in CI. With it disabled, the first part was stored as `Default`. Set it explicitly for the inserts, like the other tests of the feature do. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=107436&sha=latest&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20flaky%20check%29 #107436 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…invalidation results `readInvalidateQuery` serialized the result with the default serialization of the declared type, so an `INVALIDATE_QUERY` reading a `String` column stored with automatic `LowCardinality` serialization passed a non-native `ColumnLowCardinality` to `SerializationString::serializeTextQuoted`, and the periodic invalidation check crashed the server with `SIGSEGV`. The local pipeline of the invalidation query now runs through `DictionaryPipelineExecutor`, the same normalization boundary as dictionary loads, and the result column is passed through `removeSpecialRepresentations` before serialization, which also covers remote sources and `Sparse` columns. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Pushed 933e01d:
|
# Conflicts: # src/DataTypes/Serializations/SerializationInfo.cpp
|
🕵 Merged current |
…y-serialization Resolve the conflict with the atomic ALTER serialization hints refactoring: add the entries for automatically encoded columns in `buildSerializationHints`, and refresh `has_automatic_low_cardinality` after every assignment of `serialization_hints`, including `setPropertiesAndResetSerializationHints`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address review: internal consumers that run their own pipeline with `PullingPipelineExecutor` or `PullingAsyncPipelineExecutor` received the non-native `ColumnLowCardinality` of columns stored with automatic `LowCardinality` serialization, while expecting a column that matches its `String` or `FixedString` type. `FormatSchemaInfo::querySchema` rejected a schema stored in such a column with `BAD_ARGUMENTS`, and an empirical `EXPLAIN WHATIF` with a hypothetical `set` index read the encoded column as a `ColumnString` (`INCORRECT_DATA` from `ColumnString::insertRangeFrom`). Instead of fixing each consumer, the pulling executors now materialize the encoding in everything they return (`PullingOutputFormat` and `LazyOutputFormat`, including totals and extremes). Consumers that handle the encoded representation keep it with `keep_automatic_low_cardinality_ = true`: the query result path of `TCPHandler` and `LocalConnection` (`NativeWriter` sends the encoding to peers that know it) and the merge and mutation pipelines (the part writer builds the encoding from either representation). The dictionary-specific materialization in `DictionaryPipelineExecutor` is now redundant and removed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…IN WHATIF` `05812`: an empirical `EXPLAIN WHATIF` with a hypothetical `set` index over an automatically encoded column gives the same estimate as for the default serialization. `05813`: `format_schema_source = 'query'` accepts a Protobuf schema stored in an automatically encoded `String` column. Both failed on the previous head c6e9217 (`INCORRECT_DATA` / `MEMORY_LIMIT_EXCEEDED` from the misread offsets, and `BAD_ARGUMENTS`), checked with its CI `arm_binary`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…y-serialization # Conflicts: # src/DataTypes/Serializations/SerializationInfo.h
Fixes the style check. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…y-serialization Conflicts: - `master` took protocol revision 54497 for `CURRENT_AGGREGATION_VARIANT_SELECTION_METHOD`, so `DBMS_MIN_REVISION_WITH_AUTOMATIC_LOW_CARDINALITY_SERIALIZATION` and `DBMS_TCP_PROTOCOL_VERSION` move to 54498 (spec tables in `protocol.mdx` and `format.mdx`, and the revisions probed by test `05044`, updated accordingly). - `BlockNestedLoopJoinTransform.cpp`: keep `master`'s `JoinCommon::totalsColumnToSingleRow` and strip non-native `LowCardinality` from its result, as the PR did. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`master` (#127859) replaced `ISerialization::wrapColumnForDeserialization` with `createColumnForDeserialization`, which takes the data type instead of an already created column. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged current
|
|
The idea is interesting. I spent quite a bit of time on it, and my understanding is that it will be very difficult to make it the default without accepting real trade-offs, as it is not clear what a good default would be. There are a few problems. Reading I checked it on ClickBench with That's why I propose an alternative direction in #133397: a dictionary serialization of |
…y-serialization Conflicts: - `ColumnLowCardinality.h`: keep the `const_cast` + `getPtr` variant of `create` from `master` and pass `is_native` through. - `SerializationInfoTuple`: take the `SerializationInfoNamed` refactoring from `master`. `checkKindStacks` moves to `SerializationInfoNamed`, so it also covers the typed paths of `SerializationInfoObject`; `checkKindStackForType` is re-added to `SerializationInfoTuple` and added to `SerializationInfoObject`. - `NativeWriter.cpp`: keep both the materialization of non-native `LowCardinality` for old peers and `materializeObjectTypedPaths`. - `MutateTask.cpp`: use `shouldCollectSerializationInfo` from `master` and still keep an info that carries the `LowCardinality` kind. Co-Authored-By: Claude Fable 5.2 <[email protected]>
…based parallel replicas The test reads from a `UNIQUE KEY` table, and such a read cannot be serialized into a distributed query plan (`SUPPORT_IS_DISABLED`, #128534), so it failed in `Stateless tests (arm_binary, ParallelReplicas, plan-based, s3 storage, parallel)`. Add it to the same group of `tests/parallel_replicas_plan_based_blacklist.txt` as the other `UNIQUE KEY` tests. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=107436&sha=936339324428719b0c5f0d947b7e8bda399617f7&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20ParallelReplicas%2C%20plan-based%2C%20s3%20storage%2C%20parallel%29 #107436 Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
🕵 Merged current Conflicts:
CI failures on 9363393, both in
Checked locally: The comment above from @nihalzp about read overhead and the alternative in #133397 is a design question, and I left it for a human decision. |
…y-serialization Conflict resolution: - `master` reverted the sparse serialization of `JSON` typed paths (#133486 reverting #111429), which removed `SerializationInfoNamed` and `SerializationInfoObject`. The `checkKindStacks` and `checkKindStackForType` overrides move back to `SerializationInfoTuple`, the ones of `SerializationInfoObject` are dropped together with the class, and `MutateTask` uses `canUseSparseSerialization` again instead of the removed `shouldCollectSerializationInfo`. - `NativeWriter::getSerializationAndColumn`: keep the materialization of non-native `LowCardinality` columns for old peers on top of the reverted code. - `tryGetSerializationHints` now takes the metadata snapshot (#133300): pass it through in the overrides this branch adds for the wrapper storages. - `tests/parallel_replicas_plan_based_blacklist.txt`: `master` removed the whole `UNIQUE KEY` section, because plan-based parallel replicas now keep such reads local (#133744), so `05449_auto_low_cardinality_serialization_unique_key` is not listed anymore. Co-Authored-By: Claude Fable 5.2 <[email protected]>
…ngs history The current version on `master` is 26.12, and the style check `settings_changes_history` requires a new setting to be recorded under it: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=107436&sha=e84fdfcb620b3a3efa08c0512da831e9e7a7490a&name_0=PR&name_1=Style%20check #107436 Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
🕵 Merged current Conflicts:
CI: the only failure was the style check Local check on the merged tree: Not addressed: the comment by nihalzp of 2026-11-21 proposes an alternative direction (#133397). That is a design decision for a human. |
This PR adds automatic
LowCardinalityserialization forMergeTree, analogous to the existing automaticSparseserialization.A
StringorFixedStringcolumn whose declared type is notLowCardinalitycan now be stored on disk in dictionary-encoded form when it has auniqstatistic with a low cardinality estimate. The encoding is transparent: the column keeps its declared data type, flows through the query pipeline as a (non-native)ColumnLowCardinality, and is materialized to a full column at the boundaries that require it.Motivation: save disk space and read I/O for low-cardinality string columns without requiring users to declare the column type as
LowCardinality(...).How it works
LOW_CARDINALITY(shown asLowCardinalityinsystem.parts_columns.serialization_kind).uniqstatistic — there are no changes to statistics serialization. InMergeTreeDataWriter, aString/FixedStringcolumn whoseuniqestimate does not exceed the newMergeTreesettingmax_uniq_number_for_low_cardinality(default0= disabled), and which was not already chosen forSparse, is stored withSerializationLowCardinality. The column must therefore have auniqoruniq_v2statistic — declared explicitly or added implicitly byauto_statistics_types(whose default includesuniq_v2) — and havematerialize_statistics_on_insertenabled.is_nativeflag onColumnLowCardinalitymakesgetDataTypereport the nested type, so the "column class matches data type" invariant holds while such a column flows through the pipeline. It is materialized to a full column inremoveSpecialRepresentations(aggregation, joins, squashing, blocks), in the merge-input step ofIMergingAlgorithm, in the sorting and sparse-removing transforms, inIFunction, and in everything returned byPullingPipelineExecutor/PullingAsyncPipelineExecutor(the boundary for internal queries such as dictionary loads, schema queries andEXPLAIN WHATIF; only the query result path ofTCPHandler/LocalConnectionand the merge/mutation pipelines keep the encoding). Theoptimize_functions_to_subcolumnspass skips columns stored as non-nativeLowCardinality, since the dictionary encoding does not expose the data type's regular subcolumns.SerializationInfoentries for eligible columns are created in the writer, in merges, in mutations and in the per-table serialization hints even whenratio_of_defaults_for_sparse_serialization = 1disablesSparseentirely.Notes
String/FixedStringcolumn with a cardinality statistic, including the implicituniq_v2statistic added by the defaultauto_statistics_types; removeuniq_v2fromauto_statistics_typesto restrict it to explicitly declared statistics.s.size) is not supported and reportsNOT_IMPLEMENTED: the subcolumn's streams do not exist in a dictionary-encoded part. Making it read the full column and extract the subcolumn in memory needs a dedicated serialization and is left for a separate change.LowCardinalitypart of the draft Serializations and Statistics Refactoring #85145 against currentmaster, without the statistics-serialization refactoring. That refactoring is still unmerged (Serializations and Statistics Refactoring #85145 and Allow to use external statistics for serialization infos #109128 are open drafts).Validated locally with a server built from this branch: kind selection for
WideandCompactparts,StringandFixedString, query correctness, functions,GROUP BY/ORDER BY/DISTINCT/LIMIT BY/window functions, joins,INsubqueries,INSERT SELECT,UNION ALL,OPTIMIZE FINAL(LowCardinality preserved through merges), mutations,ALTER RENAME/MODIFY COLUMN,DETACH/ATTACH,PREWHERE, input/output formats with and withoutallow_special_serialization_kinds_in_output_formats, and tables with mixedDefaultandLowCardinalityactive parts. The three tests also pass withratio_of_defaults_for_sparse_serializationforced to0.0and1.0, withenable_block_offset_column/enable_block_number_column, with compact parts, and over repeated fully randomized runs.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added automatic
LowCardinalityserialization: aString/FixedStringcolumn that has auniqstatistic and low cardinality can be stored in dictionary-encoded form on disk while keeping its declared data type. Controlled by the newMergeTreesettingmax_uniq_number_for_low_cardinality(disabled by default). Closes #107436🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/107436]