Skip to content

Track provenance of relation statistics - #125809

Merged
cv4g merged 31 commits into
masterfrom
relation-statistics-provenance-tracking
Nov 18, 2026
Merged

cv4g merged 31 commits into
masterfrom
relation-statistics-provenance-tracking

Conversation

@cv4g

@cv4g cv4g commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

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

  • Improvement

Changelog entry

  • An inequality join (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.
  • Value ranges of grouping keys now carry through GROUP BY, which removes duplicate rows but keeps every key value.
  • They also carry through ORDER BY … LIMIT n, including reads that use the top-K optimization, when the input is known to have at most n rows.
  • Statistics are no longer taken to describe the rows in these cases:
    • after a filter (including PREWHERE and row policies), FINAL, SAMPLE, any other LIMIT, ARRAY JOIN, or another join;
    • when the read skips lightweight-deleted rows or rows superseded by a UNIQUE KEY;
    • when the read applies mutations or patch parts on the fly, including a pending RENAME COLUMN / DROP COLUMN, or masking policies;
    • for GROUPING SETS and WITH TOTALS overflow rows;
    • when a read, sort or GROUP BY limit has a non-throwing overflow mode;
    • for Iceberg delete files;
    • when only some parts or data lake files have statistics or bounds.
  • Column statistics left outdated by ALTER TABLE … MODIFY COLUMN are 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:

  • It erased ranges after every LIMIT, even when the limit could not drop rows.
  • It erased the range and NULL fraction after a value-changing expression, but kept the distinct count without recording that it is only an upper bound.
  • It kept whole-part ranges after a WHERE or PREWHERE, 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. ColumnStats carries two independent instances:

  • ndv_provenance for num_distinct_values.
  • range_provenance for min_value / max_value. null_fraction is a fact about the same rows, so it follows the range.

The two are independent for two reasons. basic statistics 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.

Origin Meaning
Unknown No statistic: the fact is a default.
MeasuredStatistics Read from stored statistics: MergeTree part statistics or the column metrics of data lake manifests.
SyntheticFallback Heuristic NDV without a distinct-count statistic (e.g. only basic).
SyntheticOverride Test-only table stats hints or randomized join statistics, which the planner trusts as if measured.
Transformation Recorded by
RowSubset Rows dropped or repeated without changing values:
• filters, PREWHERE, row policies and deferred filters; filtered estimator profiles
• FINAL, SAMPLE, STREAM, a trivial LIMIT, 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 n rows
• LIMIT and sorting limits that may drop rows; sorts with a non-throwing max_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) An NDV lowered to an estimated row count: grouping keys over an inexact input, filtered estimator profiles, join-order DP entries. A clamp to an exact row count records nothing, since it cannot make the NDV too small.
NDVBoundExpression A deterministic function that may change values (e.g. CAST, roundToExp2). Value-preserving lineage (aliases, materialize, toNullable) records nothing.
PartialStatisticsCoverage Statistics that cover fewer rows than the selected parts. Also bounds merged with a data lake file that has a NULL count but no bounds, because they miss that file's values.
Unmodeled Steps whose effect is not modeled:
• FINAL, on-the-fly mutations and patch parts, a pending metadata-only RENAME 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) returns std::optional<UInt64>.
  • valueRange(ValueRangeGuarantee::Exact | Superset | Representative) returns std::optional<ColumnValueRange>, which holds min, max and null_fraction. A Superset range 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. Unmodeled breaks every guarantee, so estimation fails closed:

NDV Exact NDV UpperBound Range Exact Range Superset Range Representative
no transformation yes yes yes yes yes
RowSubset no yes no yes no
EstimatedRowCountClamp no no – – –
NDVBoundExpression no yes no no no
PartialStatisticsCoverage no no no no no
Unmodeled no no no no no

The NDV guarantees also require the origin MeasuredStatistics or SyntheticOverride. The range guarantees require MeasuredStatistics.

The NDV guarantees describe row coverage, not numerical accuracy. UpperBound means 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_v2 above 256 distinct values), and NULLs are not counted.

Representative means 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

  • Exact row counts. RelationStats::rows_exact / exactRows() track whether a row count is exact. This is independent of imprecise_estimate, which describes the estimator path. Row counts are exact for system.one, ReadNothingStep, an empty read with exact ranges, and a MergeTree read that cannot drop rows.
  • Limits. LIMIT and sorting limits over an exact input that is no larger than the limit pass statistics through unchanged. Otherwise they record RowSubset. With an exact input and no WITH TIES, the row count after OFFSET/LIMIT stays 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.
  • Sort limits. A sort with a non-throwing max_rows_to_sort / max_bytes_to_sort records RowSubset, with or without a LIMIT, and makes the row count inexact.
  • GROUP BY. makeGroupingKeyStats keeps the NDV and range of each grouping key. It drops the NULL fraction, because all NULL keys collapse into one group. GROUPING SETS and overflow rows record Unmodeled. A non-throwing max_rows_to_group_by records RowSubset. Grouping keys used to come without a range; they keep one only while it is still enclosing after these annotations, so the keys of GROUPING SETS or of a grouping over a FINAL read get none.
  • ARRAY JOIN. It records RowSubset on 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.
  • Expressions. remapColumnStats records NDVBoundExpression for a value-changing function and clears the range of its input, as before: the range of k says nothing about negate(k), and NDVBoundExpression keeps no value-range guarantee. The NULL fraction stays with the provenance that disqualifies it (a CAST can 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 through valueRange.
  • Unary steps. These go through classifyUnaryStepStats / estimateUnaryStepStats:
    • Known pass-through steps keep their statistics unchanged: CommonSubplanStep, SaveSubqueryResultToBufferStep, ExtremesStep, WindowStep, BuildRuntimeFilterStep and StreamInQueryResultCacheStep.
    • Other row-preserving steps keep their values but record Unmodeled.
    • Unsupported steps (e.g. DISTINCT, WITH FILL, UNION) still give unknown statistics, as before, and their children are not visited.
  • MergeTree reads. analyzeReadCoverage returns a ReadCoverage, which says whether the read may drop rows (RowSubset) or rewrite values (Unmodeled):
    • Predicates, FINAL, SAMPLE, STREAM, a trivial limit and vector search may drop rows.
    • Lightweight deletes and non-empty UNIQUE KEY delete bitmaps may drop rows. The bitmaps are checked per part, as the reader does.
    • Non-throwing read limits, leaf limits and max_execution_time may 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.
    • On-the-fly mutations and patch parts may drop rows and rewrite values.
    • FINAL, masking policies and pending metadata-only RENAME COLUMN / DROP COLUMN may rewrite values. The commands still pending for each part are checked; for a projection part, its parent part decides.
    • A top-K read (ORDER BY … LIMIT n) keeps every row of the final top n. So it counts as a row subset only when it selects more than n rows.
  • Data lake reads. Delete files, filters, PREWHERE, row policies and non-throwing read limits record RowSubset on the manifest statistics.
  • Sub-joins. An optimized JoinStepLogical propagates its estimate as on master (Make DPsub the default join order algorithm, with the CD-C conflict detector #120110), and its column statistics record Unmodeled. A plan-time filter above it still makes the row count unknown, while a runtime filter does not.
  • API. estimateReadRowsCount(node, RelationStatsOptions) no longer takes a filter. The filter is now internal to estimateRelationStatsUnderFilter. for_runtime_filter_transport moved into RelationStatsOptions. estimateUnaryStepStats is 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. Passing nullptr uses every statistic; Iceberg manifests do this because their statistics are built with the current types.
  • Profiles set the origins:
    • The NDV is MeasuredStatistics with a cardinality sketch and SyntheticFallback otherwise.
    • The range is MeasuredStatistics when both bounds exist.
    • PartialStatisticsCoverage is recorded when the statistics cover fewer rows than the selected parts, or when the bounds miss some values.
  • Filtered profiles record RowSubset, plus EstimatedRowCountClamp when 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, and Estimate::min_max_covers_all_values exposes it. The flag is not serialized, because summaries are never written. Serializing a cleared flag throws LOGICAL_ERROR.
  • Table stats hints and randomized join statistics set the origin SyntheticOverride.
  • data lake. summary with bounds but no NULL count leaves the NULL fraction unset, while the bounds stay qualified.

Consumers

  • IEJoin condition selectivity (uniform interpolation over min/max) requires ValueRangeGuarantee::Representative.
  • IEJoin band key-pair scoring refutes lo <= hi from min/max. That needs the true extremes of the joined rows, so it requires ValueRangeGuarantee::Exact. Without them, the pair is scored as independent.
  • The join-order DP records EstimatedRowCountClamp when it caps an NDV at the estimated output rows. The values are unchanged.
  • The join-order optimizer's interesting-order costing (DPsub, query_plan_join_order_use_interesting_orders) still reads min_value / max_value directly to estimate how much of a sorted probe side a runtime filter prunes or a sharded merge join reads. It is not migrated to valueRange here; 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 of k kept under negate(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.
  • No other consumer is changed. Join order, Cascades and distributed aggregation get the same NDV values as before and ignore provenance for now.

Diagnostics

The optimizer trace lines estimate statistics ... and Estimated 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:

estimate statistics t: 2 rows, columns: [b3: 1 (ndv: measured-statistics[row-subset,unmodeled], range: measured-statistics[row-subset,unmodeled])]

Not in this PR (follow-ups)

  • Making the Cascades statistics derivation, join-order cardinality estimation and the distributed aggregation strategy check provenance.
  • A certified NDV upper bound (numerical, not only row coverage), to be added together with a consumer that needs it.

Tests

  • Unit tests:
    • New gtest_column_stats_provenance.cpp covers:
      • the guarantee table and origin requirements, and value ranges together with their NULL fraction;
      • stable diagnostic strings and synthetic planner inputs;
      • expression lineage, which clears the range of a value-changing function and keeps its NULL fraction;
      • keepOnlyEnclosingValueRange for 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;
      • unsupported boundaries (DISTINCT, WITH FILL, UNION), which do not visit their children;
      • filters, limits and exact rows, sorting limits and non-throwing sort limits;
      • aggregation (plain keys, GROUPING SETS, overflow rows, GROUP BY limits);
      • the join-order NDV clamp;
      • sub-joins of every kind, also under a plan-time filter;
      • pass-through steps, CommonSubplanReferenceStep, generic row-preserving steps and system.one.
    • gtest_stats.cpp:
      • ColumnStatsOriginsTransformationsAndPartialCoverage covers origins, partial coverage and filtered profiles.
      • SummaryWithoutBoundsMakesRangePartial covers 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 plain GROUP BY, a grouping key with many NULLs, GROUPING SETS, overflow rows and a GROUP BY limit.
  • 05042_ie_join_selectivity_stats_edge_cases:
    • ORDER BY … LIMIT above the table size keeps ranges.
    • WHERE, PREWHERE (both optimizer modes) and a trivial LIMIT drop them.
    • Non-throwing sort limits, read limits and timeouts drop them. Throwing sort limits keep them, and so do leaf read limits on a local read.
    • Top-K reads and top-K granule selection keep ranges when no rows are dropped, and drop them otherwise.
    • A pending metadata-only DROP COLUMN + RENAME COLUMN falls back to syntax order, and the materialized rename restores the choice by statistics.
  • New 05241_relation_stats_final_provenance: checks the trace provenance for a FINAL read on SummingMergeTree.
  • New 05480_relation_stats_unique_key_provenance: a UNIQUE KEY table 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 without partial-statistics-coverage.
  • New 05508_dpsub_key_ranges_through_build_expressions: with DPsub interesting orders, a build side computed as negate(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 describes k rather than negate(k); a build side behind GROUP BY, ORDER BY … LIMIT or LIMIT loses 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

  • Merged into: 26.11.1.2788-master (included in 26.11 and later)

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.
@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Oct 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [11bef88]

Summary: ✅


AI Review

Summary

Reviewed #125809 at 11bef88b81d03a9f96df4664300525ac625b11d5, including the full diff, current code, and every prior discussion and reply. The change tracks statistics provenance, requires qualified ranges for IEJoin condition selection, and preserves enclosing ranges through grouping and limits. No actionable findings remain; the previous bot findings are addressed in the current code.

Consumer coverage for the newly preserved ranges:

  • IEJoin condition scoring requests Representative ranges; band scoring requests Exact ranges.
  • DPSubJoinOrderOptimizer::initDPsubScratch still reads raw bounds. keepOnlyEnclosingValueRange protects the expression, grouping, limit, and sorting-limit boundaries where ranges were previously cleared.
  • Join-order cardinality estimation, Cascades, distributed aggregation, and Iceberg distinct-count estimation continue using heuristic estimates without asserting the new guarantees.
  • Distributed join planning and runtime-filter transport consume row estimates; hash-join row-store sizing consumes column widths. Neither interprets the newly retained bounds.
  • WhatIfStatisticalEstimator consumes profile row counts; optimizer diagnostics retain provenance without exposing bounds.

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 Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Oct 14, 2026
cv4g added 3 commits October 14, 2026 17:51
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`.
@clickhouse-gh

clickhouse-gh Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 11bef88b8 with master 0bfadae35 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

33 object files changed (+110.05 KiB total), 2 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/Statistics/RelationProfile.cpp.o new 40.25 KiB +40.25 KiB
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/RelationStatisticsEstimator.cpp.o 164.93 KiB 204.81 KiB +39.88 KiB (+24.18%)
src/CMakeFiles/dbms.dir/Storages/Statistics/ColumnStatsProvenance.cpp.o new 18.83 KiB +18.83 KiB

711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

348 translation units recompiled, 4201 s compile time in total, 346 of them have a recent master baseline.

Job report

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.
@novikd novikd self-assigned this Oct 22, 2026
cv4g added 7 commits October 22, 2026 15:04
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.
cv4g added 3 commits November 9, 2026 14:24
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
@Manerone Manerone self-assigned this Nov 10, 2026
nickitat and others added 2 commits November 14, 2026 13:53
# Conflicts:
#	src/Processors/QueryPlan/JoinStepLogical.cpp
#	src/Processors/QueryPlan/Optimizations/RelationStatistics.h
#	src/Processors/QueryPlan/Optimizations/RelationStatisticsEstimator.cpp
#	src/Storages/Statistics/RelationProfile.h
@nickitat

Copy link
Copy Markdown
Member

🕵 Merged master into this branch and resolved the conflicts caused by #129617 (the switch to the -WithMemoryTracking containers). I also added a small commit that switches the new code to the -WithMemoryTracking types where it meets the APIs changed there, so that it compiles. This update was made automatically.

cv4g added 2 commits November 17, 2026 12:04
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.
@cv4g

cv4g commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

@groeneai

Copy link
Copy Markdown
Collaborator

The only red scenario is 07_many_parts.sql (+639,872 B, 5.2%; the gate is >1 KiB and >1%), and it is caused by this PR: by the layout of struct Estimate, not by extra work.

The report's cross-version diff for scenario 7 puts +640,000 B (master 3,296,000 B, PR 3,936,000 B) under IMergeTreeDataPart::setEstimates. Every part keeps an Estimates map (unordered_map<String, Estimate>) with one node per column, so the scenario holds 1000 parts x 10 columns = 10,000 nodes.

The two new bools (Statistics.h#L142, #L145) are each followed by an 8-byte-aligned std::optional<UInt64>, so each costs 8 bytes. Sizes I measured by compiling against master's headers and libc++:

Layout sizeof(Estimate) hash node jemalloc size class
master 272 312 320
this PR 288 328 384
both bools together after estimated_sum 280 320 320

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 min_max_covers_all_values and null_count_covers_all_rows next to each other at the end of Estimate. The node then stays in the 320 B class, so the scenario delta should drop to ~0 with no behaviour change. All other scenarios are already below the 1 KiB threshold.

@cv4g
cv4g added this pull request to the merge queue Nov 18, 2026
Merged via the queue into master with commit aac5992 Nov 18, 2026
194 checks passed
@cv4g
cv4g deleted the relation-statistics-provenance-tracking branch November 18, 2026 22:53
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 18, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 20, 2026
`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]>
alexey-milovidov added a commit that referenced this pull request Nov 21, 2026
…-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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants