Skip to content

Lazy-load column statistics during query planning - #104691

Closed
zoomxi wants to merge 33 commits into
ClickHouse:masterfrom
zoomxi:statistic-lazy
Closed

zoomxi wants to merge 33 commits into
ClickHouse:masterfrom
zoomxi:statistic-lazy

Conversation

@zoomxi

@zoomxi zoomxi commented May 12, 2026

Copy link
Copy Markdown
Contributor

When the query planner needs column statistics — for join reordering, for prewhere selectivity estimation, or for part pruning — it currently loads statistics for every column of the table from disk on the first access, even when the query only filters or joins on a handful of columns. This PR reduces statistics-file I/O during query planning on wide tables.

Changelog category (leave one):

  • Improvement

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

Column statistics are now loaded on demand for only the columns the query planner needs instead of for every column of the table on first access.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label May 12, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [392a7ae]

Summary: ✅


AI Review

Summary

This PR rewires the planner and MergeTree statistics paths to load only the columns needed for join reordering, PREWHERE, and part pruning, and it fixes several earlier lazy-loading regressions in the process. The remaining issue is in the storage-wide statistics cache lifecycle: selective query-built estimators can now prevent the background refresher from ever rebuilding the full cache, so the default cached path regresses to repeated on-demand disk reads for different column subsets.

Findings

⚠️ Majors

  • src/Storages/MergeTree/MergeTreeData.cpp:944-953 Query-specific subset estimators are now stored in the storage-global cached_estimator, but refreshStatistics still treats any estimator for the same part set as fresh. After the first cached selective query, the periodic refresher returns early and never rebuilds the full-table estimator, so later queries on other columns keep missing the cache and reloading statistics from disk until the part set changes.
    Suggested fix: track whether cached_estimator covers the full statistics set (or otherwise keep subset-built estimators out of the storage-global cache), and only let refreshStatistics skip its rebuild when that full-cache invariant still holds.
Final Verdict

Request changes: the lazy-loading behavior looks correct on the reviewed planner/storage paths, but the storage-wide cache refresh contract is still broken for selective requests.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.60% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.90% +0.10%

Changed lines: Changed C/C++ lines covered: 391/407 (96.07%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label May 12, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

This was fixed by #105146. Let's update the branch.

@rschu1ze

Copy link
Copy Markdown
Member

@hanfei1991 Something interesting to review when you are back.

alexey-milovidov and others added 3 commits June 16, 2026 23:08
# Conflicts:
#	src/Processors/QueryPlan/Optimizations/optimizeJoin.cpp
#	src/Storages/MergeTree/IMergeTreeDataPart.cpp
The merge silently combined the PR's `getUsedColumns` (which remapped `.null`
virtual keys to their parent column via `virtual_key_to_parent`) with master's
member list, which no longer declares `virtual_key_to_parent` or
`null_subcolumns_to_normalize`. Master reverted `StatisticsPartPruner` to a
MinMax-only pruner and dropped the `NullCount` / `.null`-subcolumn machinery the
PR's change depended on, so the combined header failed to compile with
`use of undeclared identifier 'virtual_key_to_parent'`.

Take master's `getUsedColumns`, which returns `used_column_names` populated by
master's `StatisticsPartPruner.cpp`. The lazy per-column loading the PR relies on
is preserved: part pruning still loads statistics only for the filter columns via
`getEstimates(getUsedColumns())`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`IMergeTreeDataPart::getEstimates` only recorded a column in
`estimates_attempted_columns` (the negative cache) when the column had no
statistics declared in metadata. A column that *did* declare statistics but
whose statistics file was unreadable was neither cached in `estimates` nor
marked as attempted, so every query re-read, re-failed, and re-logged the same
deterministic miss for that part. This defeats the lazy-loading goal of the PR
and is the issue raised by the AI Review verdict and the `clickhouse-gh`
review thread.

The miss is deterministic by the time the caching block runs: a column absent
from `estimates` at that point either has no statistics file, or a file that
fails to deserialize (corrupted, unsupported version, or a stale stored type
left by an in-progress `MODIFY COLUMN`, for which `ColumnStatistics::deserialize`
now returns a null pointer after merging master). Transient errors while opening
the statistics file propagate out of `loadStatistics` and never reach this point,
so they remain retryable, and a fresh part object (after reload or mutation)
starts with an empty cache. Record every such miss in the negative cache.

Add `04341_stats_lazy_deterministic_miss`: it corrupts the statistics file of a
metadata-declared column (preserving its size so the on-load size check still
passes), then runs the same statistics-using query twice and asserts the first
query logs a `Cannot load statistics for column` warning while the second does
not, proving the column is probed at most once per part object.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alexey-milovidov and others added 4 commits June 18, 2026 18:44
After merging master, `makeDistributed.cpp` still forward-declared the
two-argument `estimateReadRowsCount`, while the definition in `optimizeJoin.cpp`
had gained a third `estimator` argument. The mismatched declaration referenced a
symbol that is never defined, so linking `clickhouse` failed in the Fast test
with `undefined symbol:
DB::QueryPlanOptimizations::estimateReadRowsCount(DB::QueryPlan::Node&, DB::ActionsDAG::Node const*)`.

Update the forward declaration to the three-argument signature; the callers here
pass no estimator and keep relying on the index-analysis fallback.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104691&sha=e4e143995a3ca517c0665e983af01612733199f7&name_0=PR
PR: ClickHouse#104691

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`filterPartsByStatistics` called `getEstimates(getUsedColumns())`, but
`StatisticsPartPruner::getUsedColumns` is populated only once `checkPartCanMatch`
builds a key condition, which first happens inside the per-part loop. Before the
loop it returns an empty list, and `IMergeTreeDataPart::getEstimates` treats an
empty list as "load every column's statistics" -- so statistics-based part
pruning deserialized the statistics of all columns instead of only the filter
columns, defeating the lazy-loading goal of this pull request.

Add `StatisticsPartPruner::getCandidateColumns`, which returns the filter columns
that carry `MinMax`/`Basic` statistics (known right after construction), and pass
it to `getEstimates`. `getUsedColumns` is kept for the post-loop query-plan
reporting, where it reflects the columns the key conditions actually used.

Covered by `04209_stats_lazy_columns` (case `04209_part_lazy`).

PR: ClickHouse#104691

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`estimateReadRowsCount` recurses through a generic row-preserving
`ITransformingStep` (e.g. a window function), but `collectStatsColumnsForRelation`
-- which decides which columns the estimator should be built for -- did not. For
a relation subtree like `WindowStep -> FilterStep -> ReadFromMergeTree` the
collector returned no `ReadFromMergeTree`, so no estimator was built and the
relation lost its statistics-backed row estimate, even though the fold still
treated the step as a pass-through.

Handle the generic row-preserving transform in `collectStatsColumnsForRelation`
the same way the fold does, and forward the `estimator` in the fold's recursion
so the estimate is actually computed for such subtrees.

Add `04342_stats_lazy_window_relation`: a window function above a filtered
`ReadFromMergeTree` in a join relation must load the same statistics columns as
the equivalent relation without the window.

PR: ClickHouse#104691

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Per-column statistics are now stored inside a single `statistics.packed` file
rather than legacy per-column `statistics_<col>.stats` files, and
`materialize_statistics_on_insert` is a query setting, not a table setting. The
test corrupted a non-existent `statistics_b.stats` and never materialized
statistics, so its premise no longer held.

Materialize statistics on insert and zero out only column `b`'s blob inside
`statistics.packed` (parsing the packed index so the container still loads and
column `a` stays intact), which makes deserializing `b` deterministically fail.
Stream the resulting warning away from the client with `--send_logs_level=error`
so the test asserts it via `system.text_log` only.

PR: ClickHouse#104691

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

Copy link
Copy Markdown
Member

Pushed e4e143995a3..d6016fbd7f8 addressing the red Fast test build and the AI review's "Request changes" actions:

  • Build (undefined symbol) — 0d3104f9ec5. After the master merge makeDistributed.cpp still forward-declared the 2-arg estimateReadRowsCount, but the definition gained a 3rd estimator argument, so the Fast test link failed with undefined symbol: ...estimateReadRowsCount(DB::QueryPlan::Node&, DB::ActionsDAG::Node const*). Updated the forward declaration to the 3-arg signature.
  • Selective column discovery for part pruning — e2609c3872e. getUsedColumns() is empty before the per-part loop (it is only filled once checkPartCanMatch builds a key condition), so getEstimates({}) was loading every column's statistics. Added StatisticsPartPruner::getCandidateColumns() (filter columns carrying MinMax/Basic statistics, known at construction) and pass it to getEstimates. Covered by 04209_stats_lazy_columns.
  • Statistics through row-preserving transforms — a4015918658. collectStatsColumnsForRelation now treats a generic row-preserving ITransformingStep the same as the estimateReadRowsCount fold (which also now forwards the estimator), so a WindowStep -> FilterStep -> ReadFromMergeTree relation keeps its statistics-backed estimate. New regression test 04342_stats_lazy_window_relation.
  • 04341 test — d6016fbd7f8. Repaired the deterministic-miss test for the current packed statistics format (statistics.packed, parsing the packed index to corrupt only column b's blob).

Locally (a build with rust/mongo/azure disabled) 04209_stats_lazy_columns, 04209_statistics_retry_load, 04341_stats_lazy_deterministic_miss, and 04342_stats_lazy_window_relation all pass across repeated runs.

@zoomxi

zoomxi commented Jul 28, 2026

Copy link
Copy Markdown
Contributor Author

Lots of code was added but given that all statistics live in one file (#93414), I would first like to see a performance experiment / test / benchmarking that proves this PR improves speed.

Although all column statistics are packed into a single statistics.packed file, reducing the column set still cuts both bytes read and deserialization cost.
I added the perf test tests/performance/statistics_lazy_loading.xml, which sets use_statistics_cache = 0 inline on each query to avoid hitting a warm cache.

Results (100 columns × 50 parts, perf.py --min-runs=5, median):

Scenario Optimization off Optimization on Speedup Columns loaded
Part pruning 312 ms 20 ms 15.6x 5000 → 150
Prewhere selectivity 380 ms 92 ms 4.1x 5000 → 150
Join reorder 636 ms 56 ms 11.5x 10000 → 300

@zoomxi

zoomxi commented Jul 28, 2026

Copy link
Copy Markdown
Contributor Author

@rschu1ze Found a related PR #109925 — both aim to optimize the cold load of statistics.
#109925 warms cached_estimator after INSERT so the first SELECT doesn't load from disk synchronously;
this PR makes the planner request only the needed column subset instead of all columns.
Do you have a suggestion on whether the two PRs can be merged? Thanks.

@rschu1ze

Copy link
Copy Markdown
Member

I don't have time to check in detail this week, will check later.

@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 383/400 (95.75%) · Uncovered code

Full report · Diff report

# Conflicts:
#	src/Processors/QueryPlan/Optimizations/optimizeJoin.cpp
#	src/Storages/MergeTree/IMergeTreeDataPart.cpp
#	src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp
Reconcile the lazy loading with master's fail-close semantics for corrupt
statistics ("Abort operations on corrupt MergeTree statistics"):

- `IMergeTreeDataPart::getEstimates` no longer swallows a thrown
  `loadStatistics` failure and no longer records `std::nullopt` for every
  requested column on that path. A corrupted file or transient read error now
  propagates to the caller and stays retryable instead of permanently
  disabling statistics for the column set on the in-memory part object (a
  failing racing query could also overwrite a concurrent successful load).
  `std::nullopt` is recorded only for deterministic misses, i.e. when the
  load succeeds but returns nothing for the column, and via `emplace` so it
  never overwrites a concurrently loaded value.
- The `merge_tree_load_statistics_throw` failpoint moved back to master's
  per-file placement inside `loadStatisticsPacked` / `loadStatisticsWide`,
  preserving the per-column exception message contract asserted by
  `04209_statistics_retry_load`.
- `04341_stats_lazy_deterministic_miss` is reworked for the new semantics:
  a query pruning on a column with corrupted statistics fails with the column
  and part in the message, fails the same way on retry (no negative-cache
  poisoning), and a query that does not need those statistics is unaffected.
- Require the exact same part set (order-insensitive) for reusing the cached
  `ConditionSelectivityEstimator`: the estimator stores one merged
  `total_rows` and one merged set of column statistics for all its parts, so
  reusing a superset estimator for a narrower part request would return
  whole-table estimates for a partial read and skew join-order, distributed
  strategy, or `PREWHERE` decisions.
- Normalize virtual `<col>.null` subcolumn requests (produced with
  `optimize_functions_to_subcolumns = 1`) to the physical parent column in
  the cache-coverage check, the same way `getColumnForStatisticsFile` does
  when loading; previously every repeated `IS NULL` query missed the cache
  and reread statistics from disk.

Adds `04815_stats_cache_scope_and_null_subcolumn` covering cache hits on
repeated queries, rebuild on a wider column set, and the `.null` reuse.
…cs I/O

The test counts `Seek` and `ReadCompressedBytes` of the measured query. With
a randomized `use_statistics_cache = 0` the planner rereads column statistics
from disk on every query, inflating the counters (reproducible CI failure:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104691&sha=8ed0900293ece5040c2a8efd14444d24669cc492&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20sequential%29).
Pin `use_statistics = 0` and `use_statistics_for_part_pruning = 0` for the
measured query.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged current master into the branch (8ed0900293e..5ed8cf56046) and reconciled it with the statistics changes that landed there, since the PR was reported as conflicting.

Merge resolution (f72f918904b): kept this branch's caller-built estimator flow in optimizeJoin.cpp while adopting master's new RowEstimateSource metadata and the improved hash-table-cache hint logic (now applied in refreshQueryGraphRelationStats, where this branch computes relation stats); kept master's placement of getEstimates outside the per-part try in MergeTreeDataSelectExecutor (load failures abort, per master's "abort operations on corrupt statistics" change) with this branch's column-subset arguments; adapted getColumnsWithStatistics to the shared_part_columns refactoring.

Semantic reconciliation (4e4f4c3e091): master's rewritten 04209_statistics_retry_load requires statistics load failures to propagate with per-file context. The lazy getEstimates cache path used to swallow them and negatively cache every requested column — a transient failure permanently disabled statistics for the part object (also flagged by the AI review). It now lets the failure propagate and records std::nullopt only for deterministic misses; the merge_tree_load_statistics_throw failpoint moved back to master's per-file placement to preserve the exception-message contract. 04341_stats_lazy_deterministic_miss is reworked accordingly: corrupted statistics now fail the pruning query (retryably) instead of being warned-and-ignored.

AI review Majors (b5190891544): ConditionSelectivityEstimator::isStale now requires the exact same part set for cache reuse (a superset estimator's merged aggregates cannot be restricted to a pruned subset), and normalizes virtual <col>.null requests to the parent column so repeated IS NULL queries hit the cache. Added 04815_stats_cache_scope_and_null_subcolumn covering both.

CI failure of 00933_test_fix_extra_seek_on_compressed_cache (5ed8cf56046): reproducible with randomized use_statistics_cache = 0, which makes the planner reread statistics from disk during the measured query and inflates its I/O counters; the test now pins use_statistics = 0 and use_statistics_for_part_pruning = 0.

Validated locally on a fresh build: 04209_statistics_retry_load, 04209_stats_lazy_columns, 04341, 04342, 04343, 04815, and 00933 (including with use_statistics_cache = 0 pinned) all pass.

Remaining CI reds on the previous run look unrelated: 04357_distributed_alias_same_expression is a known master flaky (issue #112987, fix in progress in #108855) and the BuzzHouse Not-ready Set report is tracked in #107619. The amd_tsan s3 job stopped because the server exited mid-run with no diagnostic in the harness log — worth re-checking on the fresh run for this push.

The design questions from @rschu1ze (single-file I/O premise / whether to optimize further, and the step-type enumeration) are left for the humans; the perf-test results posted above by @zoomxi address the benchmarking request.

The Fast test failed on `03738_aggregation_stats`: in the "Aggregation
by 0 columns" case the join input was labeled `tt2[no_stats~1]` with
`ResultRows: ~~1` instead of the precise `tt2[1]` / `ResultRows: 1`.

With lazy statistics loading, a relation whose only step of interest is
a global aggregation (`SELECT 7 AS key, sum(value) FROM t2`) requests
no columns, so `buildEstimatorForRelation` deliberately builds no
estimator and the underlying read takes the imprecise `PrimaryIndex`
fallback, which `estimateAggregatingStepStats` then propagated.

But a global aggregation (no GROUP BY keys) produces exactly one row
regardless of the input, so return a precise one-row estimate from
`estimateAggregatingStepStats` before consulting the input stats. This
restores the master-visible behavior; the `no_stats` labels pinned by
`04341_join_reorder_imprecise_stats_label` and
`04342_join_reorder_aggregation_subquery_imprecise_stats` (keyed
aggregation over a stats-less table) are unaffected.

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104691&sha=5ed8cf560466272855de4636b6bd261da4141f62&name_0=PR&name_1=Fast%20test
PR: ClickHouse#104691

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Fixed the only red in the last CI run — Fast test's 03738_aggregation_stats (392a7ae57b8).

In the "Aggregation by 0 columns" case the join input was labeled tt2[no_stats~1] / ResultRows: ~~1 instead of the precise tt2[1] / ResultRows: 1. With lazy loading, a relation whose subquery is a global aggregation (SELECT 7 AS key, sum(value) FROM t2) requests no columns, so no estimator is built and the read takes the imprecise PrimaryIndex fallback, which estimateAggregatingStepStats propagated to the label.

Since a global aggregation (no GROUP BY keys) produces exactly one row regardless of the input, estimateAggregatingStepStats now returns a precise one-row estimate up front instead of inheriting the input's missing-statistics annotation. The no_stats labels pinned by 04341_join_reorder_imprecise_stats_label / 04342_join_reorder_aggregation_subquery_imprecise_stats (keyed aggregation over a stats-less table) are unaffected.

Validated locally on a fresh build: 03738_aggregation_stats, all lazy-stats tests (04209, 04341, 04342, 04343, 04815), 00933, and the no_stats-label tests (04341, 04342, 03837, 03707, 03708, 03762, 04011, 04012) all pass.

/// refresher still guarantees a periodic full refresh regardless.
if (!cached_estimator
|| cached_estimator->isStale(data_parts, required_columns))
cached_estimator = estimator;

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.

This makes cached_estimator behave like a single subset cache until the part set changes. getConditionSelectivityEstimator now stores estimators built from explicit required_columns, but refreshStatistics still skips its full rebuild whenever !cached_estimator->isStale(data_parts) (MergeTreeData.cpp:3323). With an empty required_columns that staleness check only compares the part set, so the first cached query after startup can pin the storage-global cache to {a} (or any other narrow subset). Every later background refresh returns early, so the periodic whole-table cache never gets rebuilt and repeated queries on other columns keep re-reading statistics from disk.

Can we distinguish "covers all statistics columns" from "query-specific subset" before assigning to cached_estimator, or otherwise make refreshStatistics bypass that early-return for subset-built estimators?

@zoomxi

zoomxi commented Aug 13, 2026

Copy link
Copy Markdown
Contributor Author

Closing in favor of a narrower follow-up PR #114610 that keeps only the part-level change.

This PR covered two kinds of lazy loading:

  • Table-level lazy loading
    This is a large change whose benefit is conditional: with the default use_statistics_cache = 1 and the storage-level cached_estimator, the lazy load only pays off on cold start, cache invalidation, or when the cache is disabled. That narrow window does not justify the code churn.

  • Part-level lazy loading
    This is a small change that pays off unconditionally: IMergeTreeDataPart::getEstimates loads only the actually needed columns' statistics instead of every column of the part, which reduces statistics deserialization on wide tables.

@zoomxi zoomxi closed this Aug 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants