Repository navigation
Conversation
|
Workflow [PR], commit [392a7ae] Summary: ✅
AI ReviewSummaryThis PR rewires the planner and Findings
Final VerdictRequest 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
Changed lines: Changed C/C++ lines covered: 391/407 (96.07%) · Uncovered code |
|
This was fixed by #105146. Let's update the branch. |
|
@hanfei1991 Something interesting to review when you are back. |
# 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]>
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]>
|
Pushed
Locally (a build with |
Although all column statistics are packed into a single Results (100 columns × 50 parts, perf.py --min-runs=5, median):
|
|
@rschu1ze Found a related PR #109925 — both aim to optimize the cold load of statistics. |
|
I don't have time to check in detail this week, will check later. |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 383/400 (95.75%) · Uncovered code |
# 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.
|
🕵 Merged current Merge resolution ( Semantic reconciliation ( AI review Majors ( CI failure of Validated locally on a fresh build: Remaining CI reds on the previous run look unrelated: 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]>
|
🕵 Fixed the only red in the last CI run — Fast test's In the "Aggregation by 0 columns" case the join input was labeled Since a global aggregation (no Validated locally on a fresh build: |
| /// refresher still guarantees a periodic full refresh regardless. | ||
| if (!cached_estimator | ||
| || cached_estimator->isStale(data_parts, required_columns)) | ||
| cached_estimator = estimator; |
There was a problem hiding this comment.
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?
|
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:
|
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):
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.