Skip to content

Allow to use external statistics for serialization infos - #109128

Draft
CurtizJ wants to merge 17 commits into
ClickHouse:masterfrom
CurtizJ:serializations-3
Draft

CurtizJ wants to merge 17 commits into
ClickHouse:masterfrom
CurtizJ:serializations-3

Conversation

@CurtizJ

@CurtizJ CurtizJ commented Jul 2, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Improvement

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

Use exact counts of default values from the explicit column statistics (the basic statistics type), when they are available, to choose the serialization kind (full or sparse) of columns in MergeTree parts, instead of sampling the written data.

CurtizJ and others added 8 commits June 21, 2026 20:22
Extract the lightweight per-column serialization statistics out of
`SerializationInfo::Data` into a standalone `SerializationStatistics`
class. These statistics are sampled from the data and are always
available, so the serialization kind (currently sparse) is chosen
independently of the statistics framework, e.g. with
`materialize_statistics_on_insert = 0`.

Add a new `serialization_info_version` `with_external_statistics`. Under
this version each column also stores a `has_internal_statistics` flag in
`serialization.json`. When a column already carries the default count in
external statistics (a materialized `basic` statistic), the inline counts
are omitted and recovered from the external statistics when the part is
loaded, so merges and mutations can still re-decide the serialization kind
from complete counts.

Port the `num_defaults` extension of the `basic` statistic
(`StatisticsBasic`), used as the external source of the default count.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Remove the building and updating of the lightweight per-column
serialization statistics (number of rows and sampled number of default
values, used to choose sparse serialization) from `SerializationInfo`,
`SerializationInfoTuple` and `SerializationInfoByName` into a standalone
`SerializationStatisticsBuilder`.

The builder is created on every insert, merge and mutation regardless of
the `materialize_statistics_*` settings and the merge type. It mirrors the
tuple tree so the kind is still chosen independently for each tuple
element. `SerializationInfo` now only carries the chosen kind and a passive
copy of the counts for persistence; it no longer builds, updates or
chooses anything.

The per-table serialization hints (`MergeTreeData::serialization_hints`)
remain an additive aggregate: insertions add a part's counts incrementally,
while merges and mutations recompute the hints from the active parts
(removing a part's contribution would require subtracting its sampled
counts).

The on-disk `serialization.json` format is unchanged.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…der`

Replace the per-column `SampledStatistics` used to choose the serialization
kind with the shared `Estimate` type (`Storages/Statistics/Statistics.h`),
which now also carries `num_defaults`, filled by `ColumnStatistics::getEstimate`
from `Basic` statistics when available.

- Rename `SampledStatisticsBuilder` to `EstimatesBuilder`. It keeps a flat map
  of every column and subcolumn keyed by its subcolumn path (`t`, `t.a`);
  `chooseKinds` and `chooseKindStack` are driven by the serialization info tree
  and shared with the per-table serialization hints.
- `SerializationInfo` no longer stores counts. `writeJSON` and `fromJSON` carry
  a flat set of `Estimates` keyed by subcolumn path, and the counts are always
  written inline into `serialization.json`. The `WITH_EXTERNAL_STATISTICS`
  omit-and-backfill path (`has_internal_statistics`, `countsAreExternal`,
  `backfillStatistics`) is removed.
- At write time the counts of the actually-written data are sampled and
  reconciled with the exact counts from the explicit statistics (the exact
  counts win). A part carries these serialization counts in memory and merges
  them with the explicit-statistics estimates in `getEstimates`, so merges and
  mutations re-choose the kind from complete counts (including subcolumns).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
- Vertical merges: accumulate the sampled counts of the gathered columns
  (written through separate column-only streams) into
  `GatheredData::serialization_estimates` and combine them when writing
  `serialization.json`; previously they were persisted as zeros and sparse
  serialization silently degraded to full on the next merge.
- Column-only mutations: carry the counts of hardlinked columns over from
  the source part (rename-aware) and overlay the sampled counts of the
  rewritten columns; previously all hardlinked columns (or all columns, for
  mutations that rewrite nothing, such as `MATERIALIZE INDEX` or
  `DROP COLUMN`) were persisted with zero counts.
- Create serialization infos for rewritten columns whose type changed from
  one that cannot use sparse serialization to one that can (e.g.
  `Nullable(String)` back to `String`), so that their counts are persisted
  and a later merge can choose sparse again.
- `StatisticsBasic`: do not report an authoritative default count of zero
  for statistics files written before default-count tracking existed, and
  count defaults exactly (via `getNumberOfDefaultRows`) instead of sampling.
- Serialization hints: update incrementally again (saturating subtraction
  on part removal) and use the new IO-free
  `IMergeTreeDataPart::getSerializationEstimates`, so that no statistics
  are loaded from disk under the parts lock inside `NOEXCEPT_SCOPE`.
- Inserts: hand the estimates sampled by `MergeTreeDataWriter` over to the
  output stream instead of sampling every inserted block twice.
- Choose the serialization kind of `Tuple` elements independently of the
  tuple's own estimate in `EstimatesBuilder::chooseKinds`.
- Drop the estimates of columns removed from the part after being written
  (e.g. fully expired by a column TTL).
- Key subcolumn estimates via `subcolumnEstimateKey` so that a column
  literally named `t.a` cannot alias element `a` of a tuple column `t`.
- Move `Estimate` into the leaf header `Storages/Statistics/Estimate.h`, so
  the serialization headers do not depend on the statistics subsystem.
- Rework test 04401 for the removed `with_external_statistics` version and
  add `04490_sparse_serialization_counts_preserved`.

Co-Authored-By: Claude Fable 5 <[email protected]>
Replace the three per-part maps (the lazily-computed merged cache, the
estimates from the explicit statistics and the counts from
`serialization.json`) with a single `estimates` field that is populated
once — by `loadEstimates` when the part is loaded (after the checksums,
which loading the statistics requires) or by `setEstimates` when it is
written — and is immutable afterwards.

`getEstimates` becomes a trivial locked copy that can never read from
disk, so the per-table serialization hints can use it directly with exact
add/subtract symmetry, and the statistics pruner no longer pays a lazy
statistics load on the first query. The merge rule (statistics provide
min/max/cardinality and the exact default counts, the serialization
counts fill in subcolumns and the rest) lives in one place,
`buildEstimates`.

Co-Authored-By: Claude Fable 5 <[email protected]>
On inserts, `EstimatesBuilder` now takes the estimates of the explicit
statistics built by `MergeTreeDataWriter`: a column whose default count
they provide is not sampled at all — its node is initialized from the
exact statistics counts and it is excluded from the sampling roots. This
skips the redundant `getRatioOfDefaultRows` scan and chooses the
serialization kind from the exact count instead of a sample (which can
alias with the data pattern, since the sampling is stride-based).
Columns without such statistics are sampled as before; merges and
mutations are unchanged.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e4e6d9f]

Summary: ❌

job_name test_name status info comment
Stress test (amd_tsan) FAIL
Logical error: Block structure mismatch in A stream: different number of columns: (STID: 0993-308a) FAIL cidb

AI Review

Summary

This PR moves sparse/full serialization decisions onto explicit per-column Estimate data and lets basic statistics supply exact default counts. The overall direction is sound, but the current head still has three correctness gaps: legacy basic statistics are merged as if a missing defaults count were an exact zero, and both merge and mutation finalization can leave removed columns in the in-memory estimates map. The latter means the active part can continue advertising statistics for a column that is no longer in the final part layout until the part is reloaded.

Findings

❌ Blockers

  • [src/Storages/MergeTree/IMergeTreeDataPart.cpp:1246-1255, src/Storages/MergeTree/MergedBlockOutputStream.cpp:374-392] buildEstimates starts from the full statistics_estimates map after the merge path has already filtered serialization_counts to the final serialization_infos. If a merge drops a column from the part layout but that column still has explicit basic statistics, setEstimates recreates the top-level estimate entry in memory. The active part then exposes stale min/max/default-count data for a column that no longer exists physically, so later merges can treat it as present and statistics pruning can reason about the wrong value range until the part is reloaded. Suggested fix: filter statistics_estimates to the final info tree before calling setEstimates, or make buildEstimates drop keys that are absent from the final SerializationInfoByName.

⚠️ Majors

  • [src/Storages/MergeTree/MutateTask.cpp:1413-1426] The mutation finalization path never filters serialization_counts against the final serialization_infos after fillChecksums. When CLEAR COLUMN, TTL materialization, or a similar path removes a rewritten column from the part, its sampled row/default counts survive in new_data_part->getEstimates() until reload. The next merge can then count the same column twice: once via the stale estimate entry and again via the "column absent means all-default" path. Suggested fix: mirror MergedBlockOutputStream::finalizePartOnDisk and call EstimatesBuilder::filterEstimates(serialization_counts, serialization_infos) before writing serialization.json and before setEstimates.
  • [src/Storages/Statistics/StatisticsBasic.cpp:171-172] StatisticsBasic::merge treats a source statistic that was deserialized without DefaultsCount as if it carried an exact count of zero. New accumulators still start with tracks_defaults = true, so merging any legacy basic statistic turns an "unknown" default-count into an authoritative partial count. That exact count then overrides the sampled data when Estimate::num_defaults is chosen for sparse/full serialization, so mixed old/new tables can silently flip to the wrong serialization kind after a merge. Suggested fix: if either side lacks default-count tracking, clear tracks_defaults on the merged result instead of accumulating num_defaults.
Tests
  • ⚠️ Add a regression that merges a part whose basic statistic predates DefaultsCount with a freshly written part and verifies that the merged part still falls back to sampled counts instead of exposing a partial exact count.
  • ⚠️ Add a regression for a merge or mutation path that removes a column with explicit basic statistics before the part is reloaded, then exercises getEstimates()/statistics pruning or a subsequent merge to prove that removed columns cannot survive in the in-memory estimates map.
Final Verdict

Status: ❌ Block

Minimum required actions:

  1. Stop setEstimates from resurrecting removed columns, including the explicit-statistics side of the merge.
  2. Filter mutation-time serialization_counts to the final serialization_infos before they are exposed in memory.
  3. Preserve "default count unknown" when merging legacy basic statistics instead of converting it to zero, and add focused regression coverage for these paths.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 2, 2026
The early return for compact parts passed a bare {} for the
ColumnsSubstreams element of the returned std::tuple. A braced
initializer cannot participate in template argument deduction, so the
tuple's perfect-forwarding constructor was not viable and overload
resolution fell back to tuple(const Types&...), where the std::move of
new_serialization_estimates bound to a const reference and was a no-op.
Spell the element as ColumnsSubstreams{} so deduction succeeds and the
move is real.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109128&sha=3966be550cfd4624c116338d6a77cd9e5723fa4b&name_0=PR&name_1=Build%20%28arm_tidy%29
PR: ClickHouse#109128

Co-Authored-By: Claude Fable 5 <[email protected]>
string_total_bytes += other->string_total_bytes;
if (tracks_null)
null_count += other->null_count;
if (tracks_defaults)

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.

Here merge treats a legacy basic statistic that was deserialized without DefaultsCount as if it had an exact default-count of zero. deserialize intentionally clears tracks_defaults for those files, but this merge path only checks this->tracks_defaults, so a merge between one new part and one old part keeps tracks_defaults = true and undercounts num_defaults.

That partial count is then exposed as authoritative by ColumnStatistics::getEstimate and wins over the sampled top-level count when the merged part writes serialization.json, so a mixed old/new table can pick the wrong sparse/full kind on the next merge. The merged StatisticsBasic needs to keep num_defaults as "unknown" unless both inputs carried a real defaults count.

The builder kept a Node{Estimate, DataTypePtr} per (sub)column plus the
list of top-level names (roots): the type was used only to enumerate a
Tuple's element names during traversals, and roots doubled as the
exclusion list for columns whose exact counts come from the explicit
statistics.

Store a plain ordered std::map<String, Estimate> instead. With the '\0'
path joiner (see subcolumnEstimateKey) a column's entry and the entries
of all its subcolumns form the contiguous key range [key, key + '\x01'),
so addDefaults and the per-part accumulation scan key ranges instead of
walking a tree, and sampling takes the tuple structure from the block's
own type. The exclusion of the columns with exact counts is now an
explicit columns_with_exact_counts set checked uniformly by all
accumulation methods (previously addDefaults did not check it).

Also drop the default argument of the constructor's external_estimates
parameter, so every call site states it explicitly.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Storages/MergeTree/MutateTask.cpp Outdated

/// Overlay the sampled counts of the rewritten columns, reconciled with the counts from
/// the explicit statistics, on top of the carried-over ones.
auto written_estimates = out_mut->getSerializationEstimates(ctx->all_gathered_data.statistics.getEstimates());

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.

After fillChecksums runs, new_data_part->getSerializationInfos() may no longer contain a rewritten column (for example when a MATERIALIZE TTL / CLEAR COLUMN path removes it from the part). Unlike MergedBlockOutputStream::finalizePartOnDisk, this mutation path never filters serialization_estimates against that final info set, so the removed column's sampled counts survive in memory and are passed to setEstimates.

On the next merge that stale entry is counted once by EstimatesBuilder::add(part->getEstimates()), and then the same rows are counted again as all-default by addMissedColumnsToEstimatesBuilder because the column is absent from part->getColumns(). Please mirror the filterEstimates step here before the estimates are persisted/exposed.

CurtizJ and others added 2 commits July 2, 2026 12:11
MergeTask::prepare orchestrated three pieces: the per-part loop,
addMissedColumnsToEstimatesBuilder and the per-part accumulation in
EstimatesBuilder::add. Consolidate them: chooseSerializationInfosForMerge
receives the source parts and returns SerializationInfoByName with the
kinds chosen for the new part from the combined estimates of all source
parts, and the builder gets a single addPart method that absorbs add and
addDefaults. A column absent from a part contributes all-default rows
only when its values are implicitly default (an ordinary column without
a DEFAULT expression, precomputed by the caller into
absent_default_columns, so the metadata semantics stay out of the
builder); a column without estimates in a part contributes nothing.

Co-Authored-By: Claude Fable 5 <[email protected]>
A clone that contains only the statistics of the required types; a
required type missing from the object is also missing from the clone.
The per-type statistics objects are shared, not recreated: recreating
them (e.g. via cloneEmpty plus merge) would reset their internal state,
such as the feature flags of Basic statistics read from an old file,
and merge gates on the flags of the destination. The clone is a
read-only source for merge and must not be mutated.

Co-Authored-By: Claude Fable 5 <[email protected]>
/// The explicit statistics provide min/max/cardinality and the exact default counts for the columns
/// that have them; the serialization counts cover every column and subcolumn and fill in what the
/// statistics do not provide (subcolumns, and columns without a default-count statistic).
Estimates result = statistics_estimates;

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.

filterEstimates on serialization_counts is not enough once setEstimates comes through here. In the merge path we now drop fully expired columns from the sampled counts before persisting serialization.json, but buildEstimates starts from the full statistics_estimates map again. If a fully expired column still has explicit basic statistics, this line recreates the top-level key in part->getEstimates() even though the column was removed from the final part layout.

That makes the next merge treat the column as present instead of taking the absent-default path until the part is reloaded. loadStatistics ignores stats files for columns missing from columns.txt, so this also recreates the in-memory vs reloaded divergence the new filter is trying to avoid. Please filter statistics_estimates to the final column/info set as well, or teach buildEstimates to drop keys that are not present in the part.

CurtizJ and others added 4 commits July 2, 2026 15:14
- Key the estimates of tuple elements by `subcolumnEstimateKey` paths, as
  all consumers of the estimates do (`chooseKinds`, `copyColumnEstimate`);
  they were keyed by `Nested::concatenateName`, so the kinds of the
  elements were never chosen and their counts were persisted with zeros.
- Walk the tuple structure directly instead of `IDataType::forEachSubcolumn`:
  the latter materializes every virtual subcolumn of the sampled column, and
  the lazy size subcolumn of `SerializationString` casts the block column
  to `ColumnString`, which crashes on the `ColumnSparse` columns gathered
  by a vertical merge.
- Accumulate the default counts of multiple source parts in `addNumDefaults`
  instead of replacing them, and count a column physically absent from a
  part as all-default in `chooseSerializationInfosForMerge` (the previous
  call passed the estimates of a part that does not contain the column and
  was always a no-op).

Also port the `EstimatesBuilder` unit tests from the removed `addPart` to
the current accumulation methods and remove the unused helpers of
`SerializationInfoTuple`.

Co-Authored-By: Claude Fable 5 <[email protected]>
All output streams of a part being written now sample the blocks they
write into a single `EstimatesBuilder` owned by `GatheredData`: a
vertical merge samples the merging columns through the horizontal stream
and each gathered column through its own column-only stream, all into the
same builder. The owner of the part constructs the builder over the
columns the streams will write, next to the choice of the serialization
infos. `GatheredData` is held by `shared_ptr`, because the streams of
projection parts outlive the temporary part that created them.

This removes the per-stream builders and the re-uniting of their counts:
`GatheredData::serialization_estimates`, `getSerializationEstimates`,
`setSerializationEstimatesBuilder` and the static `addEstimates` and
`mergeEstimates` of `EstimatesBuilder` are gone, and `finalizePart`
does not take `GatheredData` anymore. A column-only mutation adds the
counts carried over from the source part for the hardlinked columns into
the same builder; their keys are disjoint from the sampled ones, because
a column is either hardlinked or rewritten, never both (the builder spans
only the written columns — the mutation pipeline blocks also carry
hardlinked columns for projection recalculation, which must not be
sampled).

Co-Authored-By: Claude Fable 5 <[email protected]>
…reams

The output streams no longer know about the estimates: `GatheredData` is
owned by the creator of the part again and is passed to `finalizePart`
as before, and every write call site samples the block into
`GatheredData::estimates_builder` right before writing it (the
horizontal merge loop, the vertical merge of one column, the mutation
writer; inserts sample the whole block upfront to choose the
serialization kinds and do not sample it again). This removes the shared
ownership of `GatheredData` and the `sample_written_blocks` flag,
which existed only to suppress the autonomous sampling of the streams.

Co-Authored-By: Claude Fable 5 <[email protected]>
If the merge cannot reduce rows, the explicit statistics of the new part
are merged from the source parts before any data is written and their
counts are already exact. Pass them to the builder of estimates, so the
covered columns take the exact counts as-is and skip the sampling of the
written blocks, like inserts already do. A statistic that is even
partially rebuilt by the merge pipeline does not have final counts at
that point, so its column is sampled as usual.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.50% 85.50% +0.00%
Functions 92.70% 92.60% -0.10%
Branches 77.70% 77.70% +0.00%

Changed lines: Changed C/C++ lines covered: 725/795 (91.19%) · Uncovered code

Full report · Diff report

@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

Dear @CurtizJ, this PR hasn't been updated for a while. Will you continue working on it? If not, please close it. Otherwise, ignore this message.

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

Dear @CurtizJ, this PR hasn't been updated for a while. Will you continue working on it? If not, please close it. Otherwise, ignore this message.

@clickhouse-gh clickhouse-gh Bot added the comp-part-formats Formats of MergeTree data parts in the public repository, that is how a part is laid out on disk ... label Nov 19, 2026
@clickhouse-gh clickhouse-gh Bot removed the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Nov 19, 2026

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-part-formats Formats of MergeTree data parts in the public repository, that is how a part is laid out on disk ... pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant