Repository navigation
Track provenance of relation statistics - #125809
Conversation
Column statistics now carry independent provenance for their distinct-value count and their value range (min/max and NULL fraction): the origin of the fact (part statistics, synthetic fallback, synthetic override, ...) plus the set of transformations applied while it was propagated through the plan. The relation-statistics estimator records filtering and other row subsets, non-uniform row subsets (limits, TopN, GROUP BY limits), exact and estimated row-count clamps, partial part coverage, value-preserving and NDV-bounding expressions, and unsupported steps or read modes (FINAL, on-the-fly mutations, masking policies, generic row-preserving transforms, grouping sets, overflow rows, sub-joins). Values are kept as diagnostic facts instead of being erased; consumers ask for the guarantee they need through `isExactDistinctCount`, `isDistinctCountUpperBound`, `isExactValueRange`, `isValueRangeSuperset` and `isRepresentativeValueRange`. `RelationStats::rows_exact` tracks whether a row count is exact, which lets limits and sorting limits that provably do not truncate their input preserve statistics. IEJoin key selection now requires representative value ranges, so it keeps using statistics through GROUP BY and non-truncating limits and falls back to syntax order for filtered or otherwise transformed inputs. Optimizer trace diagnostics include the provenance of every column statistic.
|
Workflow [PR], commit [11bef88] Summary: ✅
AI ReviewSummaryReviewed #125809 at Consumer coverage for the newly preserved ranges:
The focused unit and stateless tests cover provenance composition, expression lineage, limits, grouping, deletes, pending renames, incomplete Iceberg metrics, and the existing DPsub consumer. Available Praktika reports show 15,060 passed, zero failed, and 4,433 skipped tests; the storage-memory check is green. No local build or tests were run during this review. Final VerdictStatus: ✅ Approve |
A read stamped by the top-K optimization (`ORDER BY ... LIMIT n`, by default for n up to `query_plan_max_limit_for_top_k_optimization`) was always treated as a row subset, so its value ranges were rejected even when the input holds at most n rows and the read returns all of them. An inequality join over such an input fell back to syntax order for small n under default settings, while the same query with a larger n kept using statistics. A top-K read keeps every row of the final top n: range analysis drops only granules and parts that cannot hold one, and the running boundary drops rows only once n have been seen. A read whose selected parts hold at most n rows is therefore not marked. Otherwise it is marked as a non-uniform row subset, which describes it better than a predicate filter. The row count compared is the one the estimate is based on: the rows of the selected parts, which the statistics describe, or the selected rows when the estimate comes from the primary index. A `__topKFilter` PREWHERE, installed later in the second optimization pass, still counts as a filter; IEJoin collects its statistics before that.
`isDistinctCountUpperBound` documented that the true distinct count cannot exceed the value. Part statistics are approximate sketches, though: `uniq` and `uniq_v2` return point estimates that can be below the distinct count of the rows they cover (`uniq_v2` above 256 distinct values), and NULLs are not counted. So even an untransformed `PartStatistics` NDV is not a proven numerical bound. Like "exact" in `isExactDistinctCount`, "upper bound" refers to row coverage: the distinct count was measured on a superset of the produced rows (or derived from an exact row count), so rows dropped afterwards cannot make it too small. Document that, and that it is not a numerical bound. The predicate is not consumed in production yet; a stronger, certified predicate can be added with a consumer that needs it.
A limit with a non-throwing overflow mode ends a read or a sort early instead of failing the query, and no plan step shows it. An unfiltered read was still reported with an exact row count and representative value ranges, and a sort whose `LIMIT` exceeds its exact input passed them on, although the input could have been cut short. IEJoin then picked its key conditions from ranges that did not describe the rows being joined. A read now records a non-uniform row subset and an inexact row count when any of the limits its sources enforce has a non-throwing overflow mode: `max_rows_to_read` / `max_bytes_to_read`, their leaf variants, or `max_execution_time`. These are checked against the progress of the whole query, so they can stop a read however few rows it selects. A sort does the same when `max_rows_to_sort` or `max_bytes_to_sort` has a non-throwing overflow mode, with or without a `LIMIT`.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes33 object files changed (+110.05 KiB total), 2 added.
711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units348 translation units recompiled, 4201 s compile time in total, 346 of them have a recent master baseline. |
The merge with master added a min_bytes_before_external_group_by_ parameter to the full Aggregator::Params constructor, so the call in makeAggregationStepWithGroupLimit no longer compiled. Pass 0 (no lower bound) for it and annotate the arguments with their parameter names.
The option kept the row estimate and column statistics of an already optimized `JoinStepLogical` from reaching its parents unless a caller opted in. It was added because moving the sub-join case into `estimateDirectRelationStats` made it reachable for the first time; before, it sat behind the single-child check and never ran, so the option preserved the state after #99957 reverted #97114. #120110 then deliberately restored that propagation for every caller of `estimateReadRowsCount`. The merge with master kept the option and only opted in for join reordering, so this branch still diverged from master for all other consumers. For example, the distributed plan shuffled the right side of a join that was a small optimized sub-join instead of broadcasting it, because its row count was unknown. Drop the option so sub-join estimates propagate as on master. The `Unsupported` (and for semi/anti joins `RowSubset`) provenance stays, so consumers that gate on `ColumnStatsProvenance` still fail closed on a sub-join's column statistics.
…tistics A `UNIQUE KEY` read drops the rows superseded by later inserts through the delete bitmaps of its snapshot, which `MergeTreeReaderIndex` applies while reading. They are not lightweight deletes (`hasLightweightDelete` looks for `_row_exists`) and leave no mutation, and range analysis drops only granules whose rows are all dead. The part statistics still cover the superseded rows, but an unfiltered read was reported with an exact row count and exact value ranges, so IEJoin could pick its key conditions from the min/max of rows the read does not return. A read whose selected parts have a non-empty delete bitmap now records a row subset and an inexact row count, as a read with lightweight-deleted rows does. The bitmaps are asked for per part, as the reader does, so a unique-key table without superseded rows keeps its exact statistics. The analysis has already resolved them to drop fully dead granules, and the snapshot memoizes them for the read.
Statistics hints labelled the distinct counts they set as `SyntheticOverride`, but left the value ranges from `key_ranges` with the origin `Unknown`, which means "no statistic". Label them `SyntheticOverride` too. The value-range guarantees still require `MeasuredStatistics`, so planning does not change: DPsub still reads hinted ranges directly, and the estimator still clears them where it keeps only enclosing ranges. Only the optimizer trace shows the new origin.
A column statistic covers only part of a relation when it counts fewer rows than the relation's parts or files hold, and the estimator then marks both the distinct count and the value range `PartialStatisticsCoverage`. On the Iceberg path the comparison used the row count after `ManifestColumnStatistics::subtractDeletedRows`, while the statistics still count the deleted rows. A position delete of as many rows as the files without metrics hold hid those files: the bounds of the other files kept only `RowSubset`, `valueRange(Superset)` accepted them, and they survived `GROUP BY` and limits for DPsub's range costing although the live values lay outside them. The estimator now keeps the rows the statistics have to cover apart from the rows selectivities are shares of: `incrementRowCount` adds to both, the new `ConditionSelectivityEstimatorBuilder::subtractDeletedRows` lowers only the latter. `ManifestColumnStatistics` passes the rows of the files and the deleted rows instead of their difference. MergeTree never subtracts deleted rows, so its estimates are unchanged. Row estimates and selectivities still use the rows left after the deletes. Covered by `05509_iceberg_manifest_stats_deletes_file_without_metrics`, which deletes every row of the only file with bounds of a column, and by a unit test of the estimator. Review: #125809 (comment) Related: #125809
# Conflicts: # src/Processors/QueryPlan/JoinStepLogical.cpp # src/Processors/QueryPlan/Optimizations/RelationStatistics.h # src/Processors/QueryPlan/Optimizations/RelationStatisticsEstimator.cpp # src/Storages/Statistics/RelationProfile.h
…s` to match `column_stats` after #129617 Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01DFFRj3kqWUsA1C3A8DapeT
|
🕵 Merged |
A data lake file with bounds but without a NULL count was summarized with a NULL count of 0, so `valueRange(Exact)` and `valueRange(Representative)` returned an invented NULL fraction, also after merging with files that have a count. `StatisticsBasic` now records whether its NULL count covers every row, as it does for its bounds, and the relation profile leaves the NULL fraction unset when it does not, while the bounds keep their guarantees.
|
@groeneai Please review the CI Failure: PR / Storage memory check (pull_request) in https://github.com/ClickHouse/ClickHouse/actions/runs/44157235835/job/134684328057?pr=125809 |
|
The only red scenario is The report's cross-version diff for scenario 7 puts +640,000 B (master 3,296,000 B, PR 3,936,000 B) under The two new
That matches the CI numbers exactly: 10,000 x 320 + 1,000 x 96 (bucket arrays) = 3,296,000 B on master, 10,000 x 384 + 96,000 = 3,936,000 B on the PR. Suggested fix: move |
`ColumnStatsProvenance.DistinctFillingAndUnionAreUnsupportedBoundaries` (ClickHouse#125809) asserts that the estimator never reaches the children of a `DISTINCT`, `WITH FILL` or `UNION` step. This PR looks below such steps for an unestimated filter (`unknownRowsOf`), so that join reordering keeps the written order for them, as `05816` checks. The estimate itself is unchanged: no rows and no column statistics. The test now expects that single lookup per child. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…-size Conflicts with the provenance of column statistics from #125809 in `RelationStatisticsEstimator.cpp`, `ManifestColumnStatistics.cpp`, `ConditionSelectivityEstimator.cpp` and `RelationProfile.h`. `ColumnStats` has a provenance of its number of distinct values now, so the flag `num_distinct_values_from_metadata` of this branch becomes an origin of that provenance, `ColumnStatsOrigin::EstimatedFromMetadata`, instead of a second field next to it. Such a number gives no guarantee (`distinctCount`), as an estimate of the effective number of distinct values should not, and `KeyDistinctValues` reads the origin where it read the flag. A grouping key keeps it through `makeGroupingKeyStats`, and the reads record their coverage (`ReadCoverage::recordIn`) after the estimate from metadata is added. The Iceberg rule of the sizes takes the live rows, as the other rules do after the merge. `05509_iceberg_manifest_stats_deletes_file_without_metrics`, added in master, prints the provenance of a guessed number of distinct values, which the estimate from the sizes of the columns replaces. It pins `estimate_distinct_values_from_metadata` to 0, as the other tests of the Iceberg rules do. Co-Authored-By: Claude Fable 5.2 <[email protected]>
Extracted from #121736 as prep for #96779 (MinMaxRuntimeFilter), #97501 (statistics based disabling of RuntimeFilters) and #129186 (DenseBitsetRuntimeFilter), which consume estimates and can later ask for qualified ones.
Required for: #114755 (Fix NDV and column width propagation through expressions), #101398 (Fix cardinality underestimation when join column NDVs are unknown).
Prod changes: +795 -165 lines.
Test changes: +1911 -6 lines.
Changelog category
Changelog entry
join_algorithm = 'ie_join') now uses column statistics to pick its most selective conditions only when those statistics actually describe the rows being joined. Otherwise it uses its conditions in the order they are written, so misleading estimates no longer drive the choice.GROUP BY, which removes duplicate rows but keeps every key value.ORDER BY … LIMIT n, including reads that use the top-K optimization, when the input is known to have at mostnrows.PREWHEREand row policies),FINAL,SAMPLE, any otherLIMIT,ARRAY JOIN, or another join;UNIQUE KEY;RENAME COLUMN/DROP COLUMN, or masking policies;GROUPING SETSandWITH TOTALSoverflow rows;GROUP BYlimit has a non-throwing overflow mode;ALTER TABLE … MODIFY COLUMNare no longer used for queries without a filter, matching the existing behavior for filtered queries.Motivation
The relation statistics that the planner derives for a subtree (
RelationStats/ColumnStats) hold NDVs, min/max ranges and NULL fractions. They do not record how those values were obtained. So a consumer cannot tell whether an NDV was measured on exactly the produced rows, on a superset of them, or is just a guess. It also cannot tell whether a min/max range describes the produced rows.Until now the estimator dealt with this case by case:
LIMIT, even when the limit could not drop rows.WHEREorPREWHERE, and after reads that skip deleted rows, apply mutations on the fly or stop early, even though those ranges no longer describe the relation.This PR makes the derivation explicit. Each fact records its provenance, and consumers ask for the guarantee they need. Facts are kept as measured, with one exception: where the estimator used to erase value ranges (value-changing expressions, limits, sorts with a limit and grouping keys), a range survives only while it still encloses the produced values, because the join-order optimizer reads ranges without consulting their provenance (see Consumers).
Provenance model
ColumnStatsProvenance(new,src/Storages/Statistics/ColumnStatsProvenance.h) holds an origin and a set of transformation flags.ColumnStatscarries two independent instances:ndv_provenancefornum_distinct_values.range_provenanceformin_value/max_value.null_fractionis a fact about the same rows, so it follows the range.The two are independent for two reasons.
basicstatistics can provide a range without a distinct-count sketch. Some transformations affect only one of them: a clamp to the row count changes only the NDV.UnknownMeasuredStatisticsSyntheticFallbackbasic).SyntheticOverrideRowSubset• filters,
PREWHERE, row policies and deferred filters; filtered estimator profiles•
FINAL,SAMPLE,STREAM, a trivialLIMIT, vector search• lightweight deletes, rows superseded by a
UNIQUE KEY, on-the-fly mutations and patch parts• read limits with a non-throwing overflow mode (
max_rows_to_read,max_bytes_to_read, their leaf variants,max_execution_time)• a top-K read that selects more than
nrows•
LIMITand sorting limits that may drop rows; sorts with a non-throwingmax_rows_to_sort/max_bytes_to_sort• a non-throwing
max_rows_to_group_by•
ARRAY JOIN• Iceberg delete files and filters
EstimatedRowCountClamp(NDV only)NDVBoundExpressionCAST,roundToExp2). Value-preserving lineage (aliases,materialize,toNullable) records nothing.PartialStatisticsCoverageUnmodeled•
FINAL, on-the-fly mutations and patch parts, a pending metadata-onlyRENAME COLUMN/DROP COLUMN, masking policies• the outputs of an optimized sub-join
•
GROUPING SETS, overflow rows• row-preserving steps that are not on the pass-through allow-list
Guarantees
Consumers name the guarantee they need through
ColumnStats(RelationProfile.h):distinctCount(DistinctCountGuarantee::Exact | UpperBound)returnsstd::optional<UInt64>.valueRange(ValueRangeGuarantee::Exact | Superset | Representative)returnsstd::optional<ColumnValueRange>, which holdsmin,maxandnull_fraction. ASupersetrange has no NULL fraction, because the NULL fraction of a subset is unknown.A fact is returned only if none of the recorded transformations can have broken the requested guarantee.
Unmodeledbreaks every guarantee, so estimation fails closed:ExactUpperBoundExactSupersetRepresentativeRowSubsetEstimatedRowCountClampNDVBoundExpressionPartialStatisticsCoverageUnmodeledThe NDV guarantees also require the origin
MeasuredStatisticsorSyntheticOverride. The range guarantees requireMeasuredStatistics.The NDV guarantees describe row coverage, not numerical accuracy.
UpperBoundmeans the NDV was measured on a superset of the produced rows, so the rows dropped since then cannot make it too small. A sketch can still underestimate the NDV of the rows it covers (e.g.uniq_v2above 256 distinct values), and NULLs are not counted.Representativemeans that the values are plausibly spread over the range, as uniform interpolation needs. Today only an exact range qualifies. Consumers still name it separately so the two can diverge later (e.g. for a uniform sample).Estimator changes
RelationStats::rows_exact/exactRows()track whether a row count is exact. This is independent ofimprecise_estimate, which describes the estimator path. Row counts are exact forsystem.one,ReadNothingStep, an empty read with exact ranges, and a MergeTree read that cannot drop rows.LIMITand sorting limits over an exact input that is no larger than the limit pass statistics through unchanged. Otherwise they recordRowSubset. With an exact input and noWITH TIES, the row count afterOFFSET/LIMITstays exact. Both used to erase every value range; now they keep a range only while it is still enclosing (valueRange(Superset)after their own annotations), so a range that a step below disqualified (FINAL, a sub-join, partial statistics, a statistics hint) is cleared there, while its NULL fraction and provenance stay.max_rows_to_sort/max_bytes_to_sortrecordsRowSubset, with or without aLIMIT, and makes the row count inexact.GROUP BY.makeGroupingKeyStatskeeps the NDV and range of each grouping key. It drops the NULL fraction, because all NULL keys collapse into one group.GROUPING SETSand overflow rows recordUnmodeled. A non-throwingmax_rows_to_group_byrecordsRowSubset. Grouping keys used to come without a range; they keep one only while it is still enclosing after these annotations, so the keys ofGROUPING SETSor of a grouping over aFINALread get none.ARRAY JOIN. It recordsRowSubseton the remaining columns. The row count is exact only for an exactly empty input. As before, a filter above the array join or an element filter makes the row count unknown.remapColumnStatsrecordsNDVBoundExpressionfor a value-changing function and clears the range of its input, as before: the range ofksays nothing aboutnegate(k), andNDVBoundExpressionkeeps no value-range guarantee. The NULL fraction stays with the provenance that disqualifies it (aCASTcan turn NULL rows into values). Value-preserving lineage keeps everything. The clearing at this and the three sites above goes through one helper,keepOnlyEnclosingValueRange(RelationStatistics.h), which can go once every consumer reads ranges throughvalueRange.classifyUnaryStepStats/estimateUnaryStepStats:CommonSubplanStep,SaveSubqueryResultToBufferStep,ExtremesStep,WindowStep,BuildRuntimeFilterStepandStreamInQueryResultCacheStep.Unmodeled.DISTINCT,WITH FILL,UNION) still give unknown statistics, as before, and their children are not visited.analyzeReadCoveragereturns aReadCoverage, which says whether the read may drop rows (RowSubset) or rewrite values (Unmodeled):FINAL,SAMPLE,STREAM, a trivial limit and vector search may drop rows.UNIQUE KEYdelete bitmaps may drop rows. The bitmaps are checked per part, as the reader does.max_execution_timemay stop the read early. These limits are checked against the progress of the whole query. Leaf limits are set only on the leaves of a distributed query, so a local read is not affected by them.FINAL, masking policies and pending metadata-onlyRENAME COLUMN/DROP COLUMNmay rewrite values. The commands still pending for each part are checked; for a projection part, its parent part decides.ORDER BY … LIMIT n) keeps every row of the final topn. So it counts as a row subset only when it selects more thannrows.PREWHERE, row policies and non-throwing read limits recordRowSubseton the manifest statistics.JoinStepLogicalpropagates its estimate as on master (Make DPsub the default join order algorithm, with the CD-C conflict detector #120110), and its column statistics recordUnmodeled. A plan-time filter above it still makes the row count unknown, while a runtime filter does not.estimateReadRowsCount(node, RelationStatsOptions)no longer takes a filter. The filter is now internal toestimateRelationStatsUnderFilter.for_runtime_filter_transportmoved intoRelationStatsOptions.estimateUnaryStepStatsis exported for unit tests.Statistics layer changes
ConditionSelectivityEstimator::estimateRelationProfile(metadata): the unfiltered profile now takes the metadata and skips statistics built for an outdated column type, as filtered profiles already did. Otherwise those statistics would count as measured. Passingnullptruses every statistic; Iceberg manifests do this because their statistics are built with the current types.MeasuredStatisticswith a cardinality sketch andSyntheticFallbackotherwise.MeasuredStatisticswhen both bounds exist.PartialStatisticsCoverageis recorded when the statistics cover fewer rows than the selected parts, or when the bounds miss some values.RowSubset, plusEstimatedRowCountClampwhen the NDV is clamped to the filtered row count.StatisticsBasic::minMaxCoversAllValues()is false for a summary without bounds for rows that may be non-NULL, e.g. an Iceberg file with a NULL count but no bounds. Merging propagates the flag, andEstimate::min_max_covers_all_valuesexposes it. The flag is not serialized, because summaries are never written. Serializing a cleared flag throwsLOGICAL_ERROR.SyntheticOverride.Consumers
ValueRangeGuarantee::Representative.lo <= hifrom min/max. That needs the true extremes of the joined rows, so it requiresValueRangeGuarantee::Exact. Without them, the pair is scored as independent.EstimatedRowCountClampwhen it caps an NDV at the estimated output rows. The values are unchanged.query_plan_join_order_use_interesting_orders) still readsmin_value/max_valuedirectly to estimate how much of a sorted probe side a runtime filter prunes or a sharded merge join reads. It is not migrated tovalueRangehere; instead the four sites above keep only enclosing ranges, so it sees no range the previous estimator cleared unless the range still bounds the values. With the range ofkkept undernegate(k), it saw no overlap with the probe, priced the probe of the hash join at nothing and chose hash joins where the equivalent build side over the whole probe range gets a merge join.Diagnostics
The optimizer trace lines
estimate statistics ...andEstimated statistics ...now print provenance for every column. They share one formatter,dumpRelationStatsForLogs. The provenance comes last, so existing tests that match the NDV and the[...]fields still work:Not in this PR (follow-ups)
Tests
gtest_column_stats_provenance.cppcovers:keepOnlyEnclosingValueRangefor every transformation and origin, and its composition with limits, sorts and grouping over filtered, unmodeled and hinted inputs;ARRAY JOIN, including an exactly empty input and a filter above it;DISTINCT,WITH FILL,UNION), which do not visit their children;GROUPING SETS, overflow rows,GROUP BYlimits);CommonSubplanReferenceStep, generic row-preserving steps andsystem.one.gtest_stats.cpp:ColumnStatsOriginsTransformationsAndPartialCoveragecovers origins, partial coverage and filtered profiles.SummaryWithoutBoundsMakesRangePartialcovers data lake summaries with and without bounds, Nullable and non-Nullable columns, and all-NULL files.05023_ie_join_selectivity_condition_choice: added cases for plainGROUP BY, a grouping key with many NULLs,GROUPING SETS, overflow rows and aGROUP BYlimit.05042_ie_join_selectivity_stats_edge_cases:ORDER BY … LIMITabove the table size keeps ranges.WHERE,PREWHERE(both optimizer modes) and a trivialLIMITdrop them.DROP COLUMN+RENAME COLUMNfalls back to syntax order, and the materialized rename restores the choice by statistics.05241_relation_stats_final_provenance: checks the trace provenance for aFINALread onSummingMergeTree.05480_relation_stats_unique_key_provenance: aUNIQUE KEYtable with a superseded row falls back to syntax order, while the same table without one picks the keys by statistics.05299_iceberg_manifest_stats_min_max: files without bounds that hold only NULLs keep the range withoutpartial-statistics-coverage.05508_dpsub_key_ranges_through_build_expressions: with DPsub interesting orders, a build side computed asnegate(k)from keys over the whole probe range gets the same merge join as an alias over that range, instead of hash joins priced on a range that describeskrather thannegate(k); a build side behindGROUP BY,ORDER BY … LIMITorLIMITloses its hinted range as before, while a directly read table keeps it.The change set builds on a lot of insights created by #120784 (PoC: Data properties for join order cardinality cap).
Workflow [PR]
Sync PR [sync-upstream/pr/125809]
Version info
26.11.1.2788-master(included in26.11and later)