Repository navigation
Conversation
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]>
|
Workflow [PR], commit [e4e6d9f] Summary: ❌
AI ReviewSummaryThis PR moves sparse/full serialization decisions onto explicit per-column Findings❌ Blockers
Tests
Final VerdictStatus: ❌ Block Minimum required actions:
|
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) |
There was a problem hiding this comment.
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]>
|
|
||
| /// 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()); |
There was a problem hiding this comment.
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.
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; |
There was a problem hiding this comment.
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.
- 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]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 725/795 (91.19%) · Uncovered code |
|
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. |
|
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. |
Changelog category (leave one):
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
basicstatistics type), when they are available, to choose the serialization kind (full or sparse) of columns inMergeTreeparts, instead of sampling the written data.