Skip to content

Generalize basic statistics null count into a default-value count - #109977

Merged
hanfei1991 merged 13 commits into
ClickHouse:masterfrom
hanfei1991:basic-stats-default-count
Jul 29, 2026
Merged

hanfei1991 merged 13 commits into
ClickHouse:masterfrom
hanfei1991:basic-stats-default-count

Conversation

@hanfei1991

@hanfei1991 hanfei1991 commented Jul 10, 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):

The basic statistics NullCount sub-statistic is renamed to DefaultCount: instead of counting NULL rows of a Nullable column, build now counts rows equal to the column type's intrinsic default via IColumn::getNumberOfDefaultRows.

Version info

  • Merged into: 26.8.1.390 (included in 26.8 and later)

The `basic` statistics `NullCount` sub-statistic is renamed to `DefaultCount`:
instead of counting `NULL` rows of a `Nullable` column, `build` now counts rows
equal to the column type's intrinsic default via `IColumn::getNumberOfDefaultRows`.

"Default" here is the type-intrinsic default (`isDefaultAt` / `IDataType::getDefault`),
not the column's DDL `DEFAULT` expression. For a `Nullable` / `LowCardinality(Nullable)`
column the type default is `NULL` (`ColumnNullable::isDefaultAt` == `isNullAt`, and the
`LowCardinality` dictionary keeps `NULL` at index 0), so the default count is exactly the
`NULL` count and `getNullCount` / `IS NULL` estimation are preserved. For a non-`Nullable`
column it is the number of type-default rows (`0`, `''`, `[]`, ...), which enables an exact
equality-to-default estimate (`col = 0`, `col = ''`) that no other `basic` sub-statistic
provided; `ColumnStatistics::estimateEqual` consults it first because it is exact.

Because a default-value count is defined for every column type, `basic` is now valid on any
column, including composite types such as `Array`, `Tuple`, and `Map`.

The on-disk format is unchanged: the `DefaultCount` bit reuses the old `NullCount` bit and,
for `Nullable` columns, the stored value is identical, so old blobs deserialize correctly. A
`has_default_count` flag distinguishes a genuine count of zero from an old non-`Nullable` blob
that predates the feature (which falls back to the generic selectivity factor rather than
reporting a wrong zero).

To let `basic` return "no exact answer" for non-default values, `IStatistics::estimateEqual`
now returns `std::optional<Float64>` (mirroring `estimateLess`); its default returns
`std::nullopt` instead of throwing, and the `tdigest` / `countmin` overrides are updated.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a5e2055]

Summary: ✅


AI Review

Summary

This PR generalizes basic statistics from a nullable-only null_count into a broader default_count, wires the new count into equality estimation and system.parts_columns, and fixes the earlier part-pruning gap for non-numeric basic columns. The main remaining problem is an upgrade-path regression: mixed legacy/new non-Nullable basic parts are now treated as incompatible everywhere, which makes the query-time estimator silently ignore later parts and lose still-valid range information until the table is fully rematerialized.

Findings

⚠️ Majors

  • [src/Storages/Statistics/StatisticsBasic.cpp:285] The new has_default_count compatibility gate is also reused by ConditionSelectivityEstimatorBuilder, not just by the merge-task rebuild path. A legacy non-Nullable basic blob deserializes with has_default_count = false, so a table that mixes old and new parts after upgrade stops aggregating statistics for that column: the estimator keeps whichever part it saw first and silently drops later incompatible parts. That makes range/equality estimates order-dependent and discards valid min/max or string-length data from the skipped parts until all old parts are rewritten. Suggested fix: preserve the compatible basic sub-statistics when only default_count availability differs and degrade default_count to “unknown”, or teach the estimator path to merge the compatible pieces instead of skipping the whole part.
Tests
  • ⚠️ Add a focused regression test that deserializes a legacy non-Nullable basic blob, combines it with a freshly built basic statistic through ConditionSelectivityEstimatorBuilder, and verifies a range predicate still reflects both parts. The current tests cover merge-time rebuilds and legacy round-trips, but not the mixed active-part estimator path.
Final Verdict

Status: ⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 10, 2026
`StatisticsPartPruner` incorrectly treated `STATISTICS(basic)` on any column
as evidence that numeric min/max would be available for part pruning. `Basic`
only populates `estimated_min`/`estimated_max` for numeric/temporal types;
for Array, Tuple, Map, etc. only a default-value count is tracked.

Two bug fixes in `StatisticsPartPruner`:
- Constructor: use a `statisticsHasMinMax` helper that checks the column type
  before marking the pruner as useful, so non-numeric `Basic` columns no longer
  trigger a fruitless per-part pruning pass.
- `checkPartCanMatch`: replace `estimate.types.contains(StatisticsType::Basic)`
  with `estimate.estimated_min.has_value()` — the authoritative data-driven gate.

Also add `ColumnStatistics::hasMinMax()` for callers with loaded statistics.

Other changes:
- Fix `Statistics.Estimator` unit test to call `tryRegisterFunctions()` so it
  is self-contained.
- Add `Statistics.BasicLegacyBlobNoDefaultCount` unit test: deserializing a
  legacy `basic` blob (bit 2 absent) must leave `has_default_count = false`,
  so `estimateEqual(0)` returns `nullopt` rather than `0`. Covers the merge
  case too.
- Update `02864_statistics_ddl`: `basicStatisticsValidator` now accepts all
  column types, so move formerly-rejected cases to the positive section.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@hanfei1991
hanfei1991 marked this pull request as ready for review July 10, 2026 14:06
@CurtizJ CurtizJ self-assigned this Jul 10, 2026
hanfei1991 and others added 3 commits July 17, 2026 15:05
`StatisticsBasic::is_nullable` was set only via `isNullableOrLowCardinalityNullable`,
which recognises `Nullable(T)` and `LowCardinality(Nullable(T))` wrappers but not
`Variant` or `Dynamic`.  Both of those types have a `NULL` column-level default:
`ColumnVariant::isDefaultAt` / `ColumnDynamic::isDefaultAt` return true for
`NULL_DISCRIMINATOR` rows, so `build` already counted them correctly into
`default_count` — but `hasNullCount()` returned false because `is_nullable` was
never set, leaving `system.parts_columns.estimates.null_count` empty and causing
`estimateIsNull` to fall back to the generic selectivity factor.

Fix: compute `column_default_field` (from the already-stripped `data_type`) before
setting `is_nullable`, then extend the condition:

    is_nullable = isNullableOrLowCardinalityNullable(data_type_) || column_default_field.isNull();

For `Variant`/`Dynamic` the stripped type is the same type (neither is a Nullable
or LC wrapper), so `insertDefault()` inserts `NULL_DISCRIMINATOR` and the resulting
`Field` is `Null()`, triggering the new branch.  All existing paths (`Nullable`,
`LowCardinality(Nullable)`, plain numeric/string) are unaffected.

Add regression test `04511_statistics_basic_variant_dynamic_null_count` that
inserts 10 rows with 3 NULLs into `Variant(UInt32, String)` and `Dynamic` columns
and asserts that both `estimates.null_count` and `estimates.default_count` equal 3.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

@CurtizJ CurtizJ left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good in general. I've added a few minor comments. Could you also please shorten all AI-generated comments?

Comment on lines +285 to +287
return tracks_numeric == other_basic->tracks_numeric
&& tracks_string == other_basic->tracks_string
&& has_default_count == other_basic->has_default_count;

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.

Legacy non-Nullable basic blobs deserialize with has_default_count = false, so this new compatibility check makes them structurally incompatible with any freshly built basic stats object on the same column. That is fine for the merge-task rebuild path, but the same ColumnStatistics::structureEquals gate is also used by ConditionSelectivityEstimatorBuilder::addStatistics (src/Storages/Statistics/ConditionSelectivityEstimator.cpp:501-514): as soon as a table has a mix of old and new parts after upgrade, the first part wins and every later incompatible part is silently skipped.

That drops even the still-valid min/max / string-length information from the skipped parts, so query estimates become order-dependent until all legacy parts are rematerialized. A concrete repro is two Int32 STATISTICS(basic) parts, one legacy with values [0, 999] and one new with [10000, 10999]; if the legacy part is seen first, value > 5000 is estimated from only the old range and comes out near 0 instead of about 0.5 * rows.

I think this needs a mixed-layout merge path that preserves the compatible basic sub-statistics while degrading default_count to “unknown”, or a narrower compatibility check here plus a regression test that feeds a legacy blob and a new blob through ConditionSelectivityEstimatorBuilder.

@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 47.80% 86.30% +38.50%
Functions 57.20% 92.00% +34.80%
Branches 36.40% 78.40% +42.00%

Changed lines: Changed C/C++ lines covered: 197/230 (85.65%) · Uncovered code

Full report · Diff report

@hanfei1991
hanfei1991 added this pull request to the merge queue Jul 29, 2026
Merged via the queue into ClickHouse:master with commit b0daddf Jul 29, 2026
178 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

3 participants