Skip to content

Automatic LowCardinality serialization based on uniq statistics - #107436

Open
alexey-milovidov wants to merge 152 commits into
masterfrom
auto-low-cardinality-serialization
Open

alexey-milovidov wants to merge 152 commits into
masterfrom
auto-low-cardinality-serialization

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 14, 2026 •

Copy link
Copy Markdown
Member

This PR adds automatic LowCardinality serialization for MergeTree, analogous to the existing automatic Sparse serialization.

A String or FixedString column whose declared 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 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

  • A new per-part serialization kind LOW_CARDINALITY (shown as LowCardinality in system.parts_columns.serialization_kind).
  • The decision is made at write time from the existing uniq statistic — there are no changes to statistics serialization. In MergeTreeDataWriter, a String/FixedString column whose uniq estimate does not exceed the new MergeTree setting max_uniq_number_for_low_cardinality (default 0 = disabled), and which was not already chosen for Sparse, is stored with SerializationLowCardinality. The column must therefore have a uniq or uniq_v2 statistic — declared explicitly or added implicitly by auto_statistics_types (whose default includes uniq_v2) — and have materialize_statistics_on_insert enabled.
  • A new is_native flag on ColumnLowCardinality makes getDataType report 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 in removeSpecialRepresentations (aggregation, joins, squashing, blocks), in the merge-input step of IMergingAlgorithm, in the sorting and sparse-removing transforms, in IFunction, and in everything returned by PullingPipelineExecutor/PullingAsyncPipelineExecutor (the boundary for internal queries such as dictionary loads, schema queries and EXPLAIN WHATIF; only the query result path of TCPHandler/LocalConnection and the merge/mutation pipelines keep the encoding). The optimize_functions_to_subcolumns pass skips columns stored as non-native LowCardinality, since the dictionary encoding does not expose the data type's regular subcolumns.
  • The kind is independent of sparse serialization: SerializationInfo entries for eligible columns are created in the writer, in merges, in mutations and in the per-table serialization hints even when ratio_of_defaults_for_sparse_serialization = 1 disables Sparse entirely.

Notes

  • Opt-in: disabled by default, so existing tables are unaffected. Once enabled, it applies to every String/FixedString column with a cardinality statistic, including the implicit uniq_v2 statistic added by the default auto_statistics_types; remove uniq_v2 from auto_statistics_types to restrict it to explicitly declared statistics.
  • Reading a subcolumn of an encoded column (for example s.size) is not supported and reports NOT_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.
  • Extracts and reimplements the automatic LowCardinality part of the draft Serializations and Statistics Refactoring #85145 against current master, 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 Wide and Compact parts, String and FixedString, query correctness, functions, GROUP BY/ORDER BY/DISTINCT/LIMIT BY/window functions, joins, IN subqueries, INSERT SELECT, UNION ALL, OPTIMIZE FINAL (LowCardinality preserved through merges), mutations, ALTER RENAME/MODIFY COLUMN, DETACH/ATTACH, PREWHERE, input/output formats with and without allow_special_serialization_kinds_in_output_formats, and tables with mixed Default and LowCardinality active parts. The three tests also pass with ratio_of_defaults_for_sparse_serialization forced to 0.0 and 1.0, with enable_block_offset_column/enable_block_number_column, with compact parts, and over repeated fully randomized runs.

Changelog category (leave one):

  • Experimental Feature

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

Added automatic LowCardinality serialization: a String/FixedString column that has a uniq statistic and low cardinality can be stored in dictionary-encoded form on disk while keeping its declared data type. Controlled by the new MergeTree setting max_uniq_number_for_low_cardinality (disabled by default). Closes #107436

🤖 Generated with Claude Code


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

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]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [67881f3]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, ParallelReplicas, plan-based, s3 storage, parallel) FAIL
05182_compress_per_substream_in_compact_parts FAIL cidb
05332_promql_set_operator_empty_on NOT_FAILED cidb
03892_grouping_sets_force_aggregation_in_order NOT_FAILED cidb
04891_timeseries_lowcardinality_id NOT_FAILED cidb
01710_projection_with_mixed_pipeline NOT_FAILED cidb
05234_promql_result_timestamp_scale NOT_FAILED cidb
05293_promql_constant_scalar_arithmetic NOT_FAILED cidb
05137_join_fixed_string_zero_bytes_runtime_filter NOT_FAILED cidb
05234_promql_result_timestamp_type NOT_FAILED cidb
04353_text_index_explicit_tokenizer_argument NOT_FAILED cidb
18 more test cases not shown
Stress test (amd_debug) FAIL
Cannot start clickhouse-server FAIL cidb
Check failed FAIL cidb
Performance Comparison (arm_release, master_head, 4/6) FAIL Performance dashboard
nested_tuple_small_blocks #0 FAIL dashboard

AI Review

Summary

Adds opt-in experimental automatic LowCardinality serialization for String/FixedString columns using cardinality statistics, including storage selection, pipeline materialization and versioned Native exchange. No genuinely new inline findings; one previously dismissed correctness finding remains after checking the current code.

Consumers traced for the new representation: column lifecycle operations preserve is_native; recursive materialization handles Const, Nullable, Array, Tuple, Map, Sparse and Replicated; functions, aggregation, joins, sorting, filling, windows, DISTINCT, LIMIT BY and chunk concatenation normalize at their relevant boundaries. Pulling executors normalize main results, totals and extremes for dictionaries, invalidation queries, schema queries and hypothetical-index scans. Output formats select the actual serialization or materialize; Native handles older revisions, tuple elements, blobs and header conversion; Buffers materializes. Part output streams convert to the chosen encoding, wide writers avoid materialized-index reuse, and Memory/Buffer normalize stored blocks. Insert deduplication remains the exception described below.

Findings

❌ Blockers

  • src/Interpreters/InsertDeduplication.cpp:434: Identical inserted rows can acquire different deduplication hashes after a source merge. [dismissed by author -- https://github.com/Automatic LowCardinality serialization based on uniq statistics #107436#discussion_r4354549776] The dismissal assumes identical settings preserve determinism, but a merge can change this representation without any settings change. For example, with threshold 100, two source parts each containing 80 disjoint distinct strings are encoded; their merged cardinality of 160 makes the result Default. Retry the same single-row INSERT INTO dst SELECT id, s FROM src WHERE id = 0 before and after that merge, with deduplication enabled on dst and identical query/table settings. Filtering preserves the encoded payload, and the single-chunk insert path reaches hashing before part-writer normalization. convertToFullIfWrapped preserves LowCardinality: its inherited range hash feeds per-row length/value/terminator bytes, whereas ColumnString::updateHashWithValueRange feeds characters and relative offsets. The changed hash admits the retry as new data. Materialize non-native LowCardinality before deduplication hashing, preserving semantic LowCardinality types, and add a regression for this unchanged-settings merge case. The thread was left resolved and received no new reply.
Missing context / blind spots
  • ⚠️ No local runtime reproduction was performed: this review job has no ClickHouse binary and prohibits nested Praktika runs. The deduplication finding is supported by tracing the current code. The PR-head Fast test report reports 30 passing feature tests and two skipped; the fetched workflow reports contain zero failed tests. A focused retry regression would provide runtime evidence for the remaining concern.
Final Verdict

Status: ❌ Block

Normalize automatic encoding before insert deduplication hashing and cover an identical retry across a source merge that changes its serialization.

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Jun 14, 2026
Comment thread src/DataTypes/IDataType.cpp Resolved
@CurtizJ

CurtizJ commented Jun 14, 2026

Copy link
Copy Markdown
Member

@alexey-milovidov

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]>
alexey-milovidov and others added 5 commits June 16, 2026 11:14
… 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]>
Comment thread src/Processors/Chunk.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

@CurtizJ, yes, that will be fantastic!

@alexey-milovidov

Copy link
Copy Markdown
Member Author

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
@CurtizJ

CurtizJ commented Aug 12, 2026 •

Copy link
Copy Markdown
Member

@alexey-milovidov

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 (basic for sparse, and uniq for low cardinality). I wanted to do this to allow choosing serialization even without regular statistics. But it forces us to support mixed formats and causes some difficulties in corner cases.

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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged current master and pushed 854b365. The only CI failure was Upgrade check (amd_release), which logged UNKNOWN_IDENTIFIER errors from the MutatePlainMergeTreeTask of the DETACH PART tombstone left by 04653_mutation_rewrite_stale_part_column_type. This PR did not cause it. It is tracked in #120975 and fixed on master by #125293, which the merge now brings in. Also answered the open review thread about enable_parsing_to_custom_serialization and added a regression test for it. @groeneai, thanks for #130757 (the vectorize_aggregation_combinators perf query).

@groeneai

Copy link
Copy Markdown
Collaborator

The merge does not clear the Upgrade check (amd_release) red from #120975 yet. The check's stress phase runs the previous release's copy of the tests (tests/docker_scripts/upgrade_runner.sh clones --branch=$previous_release_tag), today v26.10.2.103-stable, and its 04653_mutation_rewrite_stale_part_column_type does not have the old_parts_lifetime = 0 that #125293 added on master. A run whose head already contains #125293 still failed the check at 17:45 UTC with 159 lines of the same MutatePlainMergeTreeTask UNKNOWN_IDENTIFIER error on all_1_1_1_2 (report). 3 runs have failed this way since the merge.

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 v26.10-must-backport label, and no 26.10 release has been published since v26.10.2.103-stable on 2026-10-24. The two files it changes are byte-identical on 26.10 and on its master parent, so the cherry-pick is clean.

alexey-milovidov and others added 2 commits November 14, 2026 10:59
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 933e01d:

  • Fixed 05627_auto_low_cardinality_serialization_parsing_hints, which failed in every flaky check. CI randomizes materialize_statistics_on_insert. With it off, the first part had no uniq statistics and was stored as Default. The test now sets it explicitly for its inserts, like the other tests of this feature.
  • Addressed the review thread on dictionary invalidation queries. Details are in the thread. Regression test: 05628_auto_low_cardinality_serialization_invalidate_query.
  • The Performance Comparison (arm_release, master_head, */6) jobs failed before any test ran, because test selection hit a GitHub API rate limit (403 Client Error: rate limit exceeded). This push reruns them.
  • @groeneai, thanks for the analysis of Upgrade check (amd_release). It needs a backport of Fix Upgrade check errors from the empty part left by DETACH PART in 04653 #125293 to 26.10, or the first 26.11 stable release, and it is not caused by this PR.

# Conflicts:
#	src/DataTypes/Serializations/SerializationInfo.cpp
@alexey-milovidov

alexey-milovidov commented Nov 15, 2026 •

Copy link
Copy Markdown
Member Author

🕵 Merged current master and pushed c6e9217. The conflict was in SerializationInfo::checkKindStack. master commit 1fa96f5 reorders it to validate the stack shape first and then the allowed kinds from the outermost one. The resolution keeps that order and checks the LowCardinality + Sparse exclusivity as part of the shape check, before the allowed-kinds loop. The new Default-only gate for data a peer sends to the server does not affect this PR: scalars (materializeBlock) and external tables (MaterializingTransform) go through removeSpecialRepresentations, which materializes non-native LowCardinality. Protocol revisions do not collide (master 54496, this PR 54497). The previous CI failures were on 854b365: the 05627 flaky check, fixed in 933e01d, and the ARM performance shards, which did not run because test selection hit a GitHub API rate limit. The one unresolved review thread (dictionary INVALIDATE_QUERY) was answered with the fix in 933e01d and only needs resolving.

alexey-milovidov and others added 8 commits November 15, 2026 23:39
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged current master and pushed 9363393:

  • Protocol revision collision: master took 54497 for CURRENT_AGGREGATION_VARIANT_SELECTION_METHOD, so DBMS_MIN_REVISION_WITH_AUTOMATIC_LOW_CARDINALITY_SERIALIZATION and DBMS_TCP_PROTOCOL_VERSION are now 54498. The spec tables in protocol.mdx and format.mdx and the revisions that test 05044 probes are updated to match.
  • BlockNestedLoopJoinTransform.cpp now uses master's JoinCommon::totalsColumnToSingleRow and still strips non-native LowCardinality from the totals column.
  • Adapted SerializationLowCardinality to createColumnForDeserialization, which replaced wrapColumnForDeserialization in Do not re-create nested Tuple elements when creating a column for deserialization #127859.

clickhouse builds. The join/wrapper/rechoose tests for this feature pass locally.

@nihalzp

nihalzp commented Nov 21, 2026

Copy link
Copy Markdown
Member

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 LowCardinality data from disk has a lot of overhead, especially for short strings: a plain read of SearchPhrase (7 bytes on average) takes 1.73x longer as LowCardinality(String) than as String, and of URL (90 bytes) 1.32x longer. A high-cardinality column overflows the dictionary, so nearly every granule carries additional keys, and every read hashes the keys of each granule into a new reverse index for the block and remaps the indexes of its rows. It also needs statistics to be enabled, which may not always be the case.

I checked it on ClickBench with URL, Title, Referer and SearchPhrase declared as LowCardinality(String): the 9 queries that read URL, Title or Referer got 1.22x slower at 16 threads and 1.37x at 64 (geometric mean).

That's why I propose an alternative direction in #133397: a dictionary serialization of String per granule. It does not need statistics. Each granule is stored plain or as a sorted dictionary, whichever is smaller, and is read as ColumnReplicated, so a block joins the dictionaries of its granules without hashing and operators work once per value of the block. It also has no problem with short strings: the same plain read is 1.14x faster than String for SearchPhrase and 1.39x faster for URL. On ClickBench the string columns take 14% less space on disk, and the 26 queries that read them are 1.13x faster at 16 threads, 1.11x at 64 and 1.13x at 192 (geometric mean).

alexey-milovidov and others added 2 commits November 22, 2026 08:40
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged current master and pushed e84fdfc.

Conflicts:

  • SerializationInfoTuple: master moved the shared code into the new SerializationInfoNamed base, which also serves SerializationInfoObject. The resolution takes that refactoring. checkKindStacks now lives in SerializationInfoNamed, so it also covers the typed paths of JSON. checkKindStackForType is re-added to SerializationInfoTuple and added to SerializationInfoObject.
  • MutateTask.cpp: uses shouldCollectSerializationInfo from master and still keeps an info that carries the LowCardinality kind when sparse serialization is disabled.
  • NativeWriter.cpp: keeps both the materialization of non-native LowCardinality for old peers and materializeObjectTypedPaths from master.
  • ColumnLowCardinality.h: keeps master's const_cast + getPtr variant of create and passes is_native through.

CI failures on 9363393, both in Stateless tests (arm_binary, ParallelReplicas, plan-based, s3 storage, parallel):

Checked locally: clickhouse builds, gtest_native_automatic_low_cardinality.cpp compiles, and all 32 *auto_low_cardinality_serialization* tests pass, with and without randomized settings. The unit tests were only compiled, not run.

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.

alexey-milovidov and others added 2 commits November 24, 2026 23:34
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged current master and pushed 67881f3.

Conflicts:

CI: the only failure was the style check settings_changes_history. The history record of max_uniq_number_for_low_cardinality is moved from 26.11 to 26.12.

Local check on the merged tree: clickhouse builds, and the 32 auto_low_cardinality_serialization stateless tests plus the two serialization hints tests (04840, 05839) pass. The gtest target was not rebuilt.

Not addressed: the comment by nihalzp of 2026-11-21 proposes an alternative direction (#133397). That is a design decision for a human.

This branch was successfully deployed

1 active deployment
staging - docs — 67881f3b Deployed Nov 25, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-datatype-wrapper Type modifiers/wrappers (Nullable, LowCardinality, etc.). pr-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants