Repository navigation
Conversation
Retain the full per-column statistics that INSERT already builds on the in-memory part (IMergeTreeDataPart::statistics_cache) and warm the table-level ConditionSelectivityEstimator right after committed parts become Active, so the first SELECT does not synchronously cold-load and rebuild statistics from disk in the planner. The estimator builder now copies statistics into its own aggregate (cloneEmpty + merge) before merging, so it never mutates the part-owned ColumnStatistics that loadStatistics() returns. Commit-time warming is gated on committed parts actually carrying retained in-memory statistics (hasCachedStatistics), so when statistics are not materialized on insert (large tables above materialize_statistics_on_insert_max_table_size, or the setting off) the INSERT path does not trigger a full on-disk cold-load of all parts. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-2:20260709-162000 |
For the primary key, we went the opposite route (MergeTree setting Note that this PR is orthogonal/unrelated/independent of #109454 - we can merge it (or not) later. Also, there is a recent optimization #107863 which will cause statistics to be much smaller. I think we should re-evaluate if the problem still exists once the other optimization is in. |
|
Thanks, all three points are fair.
No rush on my side given the orthogonality. |
| /// `optimize_functions_to_subcolumns=1`, keep stats for the parent column in that case. | ||
| return required_columns.empty() | ||
| || required_columns.contains(column_name) | ||
| || required_columns.contains(column_name + ".null"); |
There was a problem hiding this comment.
Isn't this too special? We also have optimization for string and array sizes, but listing all subcolumns here would be too ad-hoc. Remove?
Also, why empty required_columns lead to the assumption that statistics are required?
There was a problem hiding this comment.
Agreed it is ad-hoc. This is pre-existing logic (line 1145) that I only lifted verbatim into isColumnStatisticsRequired to reuse it for the cache lookup - see the blame note below. Rather than hand-listing .null (which also misses .size0 etc. for the string/array-size stats you mention), the robust fix is to normalize each required_columns entry to its parent column via the subcolumn API and compare against that, so no subcolumn is enumerated. I will change it to that.
On the empty case: empty required_columns means "no column filter, load all columns" - it is the convention used by the no-arg loadStatistics() overload, which passes {}. It does not mean "statistics are required", it means "do not filter". I will rename to make that read as a filter.
There was a problem hiding this comment.
Implemented in 46a556f: loadStatistics now normalizes every requested name to its parent storage column via the subcolumn API (tryGetColumn / getNameInStorage), so no subcolumn suffix (.null, .size0, ...) is enumerated by hand, and the filter check is a plain exact match on storage column names. The helper is renamed to columnPassesFilter with the parameter columns_filter, documenting that an empty set means "no filter" (the convention of the no-arg loadStatistics overload), not "statistics are required".
| /// `optimize_functions_to_subcolumns=1`, keep stats for the parent column in that case. | ||
| if (!required_columns.empty() | ||
| && !required_columns.contains(column_name) | ||
| && !required_columns.contains(column_name + ".null")) |
There was a problem hiding this comment.
I see this bad code already exists. Who and when introduced it? Please ping that person.
There was a problem hiding this comment.
git blame on this block (before my PR): introduced by @hanfei1991 in commit 1829afb ("Add basic statistics type", 2026-05-28). @hanfei1991 could you confirm the intent of the .null special-case?
I will replace the hand-listed subcolumn check with parent-column normalization via the subcolumn API so it is not ad-hoc (covers .null, .size0, etc. uniformly).
There was a problem hiding this comment.
The hand-listed .null check is gone in 46a556f - replaced by parent-column normalization through the subcolumn API, which covers .null, .size0, and any other subcolumn uniformly.
There was a problem hiding this comment.
Why is the exception acceptable here? Would it be better to propagate it?
Because not loading statistics is not a normal situation - it is similar to a broken part.
Find the person who did that and ping here.
There was a problem hiding this comment.
This catch is pre-existing, not added by my PR. git blame: introduced by @hanfei1991 in commit e27dce3 ("cache statistics in MergeTreeData", 2025-10-16). @hanfei1991 for context.
I agree with the framing: a part whose statistics fail to load is closer to a broken part than a normal case. The per-part swallow here means one unreadable statistics file silently degrades the whole estimator to "no stats for that part" with only a log line, which can produce silently-worse plans. I will make this propagate rather than swallow (see the reply on the outer catch about where it should surface).
There was a problem hiding this comment.
Implemented in 001c07e: the per-part catch is removed, so a statistics load failure propagates instead of silently degrading the estimator to "no statistics for that part". Verified with the merge_tree_load_statistics_throw failpoint: a synchronous warm on the INSERT path now reports the real error to the client (while the inserted data stays committed - the warm call moved after the transaction is finalized so the propagated exception cannot trigger a rollback of already-Active parts).
There was a problem hiding this comment.
Why do we catch the exception here? If the function is invoked by an asynchronous thread, the catch block should be at the upper level. If the function is invoked synchronously, exceptions should propagate without being caught here.
Dig into the history of this code and bring up the authors.
There was a problem hiding this comment.
Same author/history as above: @hanfei1991, commit e27dce3.
The concern is exactly the sync-vs-async split. refreshStatistics is called two ways: (1) from the background BackgroundSchedulePool task (async), where swallow+reschedule is the right shape; (2) synchronously from my new warm-on-commit path (and it can also be called synchronously elsewhere). Swallowing at this level hides errors from synchronous callers.
Fix I propose: keep the reschedule-on-error behavior only when interval_seconds != 0 (the async/scheduled invocation); when called synchronously (interval_seconds == 0), let the exception propagate to the caller. The inner per-part catch (line 3000) should likewise not swallow. That way the async thread stays alive and retries, while a synchronous warm/commit sees the real failure. Does that match your intent?
There was a problem hiding this comment.
Implemented in 001c07e as described: refreshStatistics no longer catches anything - errors always propagate to the caller - and the catch block for the asynchronous invocation moved to the upper level, the background task lambda in startStatisticsCache, which logs and reschedules so a broken part does not permanently disable the periodic refresh. The interval_seconds parameter is gone since scheduling now lives entirely in the task. Verified with the failpoint: the task logs Failed to refresh statistics while the failpoint is enabled, keeps rescheduling, and recovers as soon as it is disabled.
…hold' into groeneai/stats-warm-on-commit # Conflicts: # src/Storages/Statistics/ConditionSelectivityEstimator.cpp
…atistics filter Instead of hand-listing the `.null` subcolumn suffix (which also missed `.size0` and other subcolumns), `loadStatistics` now normalizes every requested name to its name in storage via the subcolumn API (`tryGetColumn` / `getNameInStorage`), and the filter check became a plain exact match. The helper is renamed to `columnPassesFilter` and the parameter to `columns_filter` to make the "empty set means no filter" convention read as a filter, not as "statistics are required". Co-Authored-By: Claude Fable 5 <[email protected]>
…istics` A part whose statistics cannot be loaded is similar to a broken part, so swallowing the exception and silently degrading the estimator hides real errors. `refreshStatistics` no longer catches anything: the per-part catch is removed and errors always propagate to the caller. The asynchronous invocation now catches at the upper level - the background task lambda in `startStatisticsCache` logs and reschedules, so a broken part does not permanently disable the periodic refresh - and the `interval_seconds` parameter is gone since scheduling lives in the task. The commit-time warm in `Transaction::commit` moved after `clear()`: with errors propagating, an exception thrown before `clear()` would make the destructor roll back parts that are already committed and Active. Verified with the `merge_tree_load_statistics_throw` failpoint: the INSERT reports the injected error while the inserted data stays committed, and the background task retries and recovers once the failpoint is disabled. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Reviewed both commits against the four points; they match what the inline notes describe:
No objections. CI has not started on the new head yet; I will watch it and flag any failure. One data point for the earlier "re-evaluate after #107863" question: #107863 is now merged, but it only swaps |
…into groeneai/stats-warm-on-commit
…into groeneai/stats-warm-on-commit
…into groeneai/stats-warm-on-commit
…into groeneai/stats-warm-on-commit
…into groeneai/stats-warm-on-commit
…into groeneai/stats-warm-on-commit
…into groeneai/stats-warm-on-commit
…into groeneai/stats-warm-on-commit
…/stats-warm-on-commit
…into groeneai/stats-warm-on-commit
…into groeneai/stats-warm-on-commit
…into groeneai/stats-warm-on-commit
…into groeneai/stats-warm-on-commit
…into groeneai/stats-warm-on-commit # Conflicts: # src/Storages/MergeTree/MergeTreeData.cpp
…into groeneai/stats-warm-on-commit # Conflicts: # src/Storages/MergeTree/IMergeTreeDataPart.cpp
…into groeneai/stats-warm-on-commit
…into groeneai/stats-warm-on-commit
…into groeneai/stats-warm-on-commit
…into groeneai/stats-warm-on-commit
…into groeneai/stats-warm-on-commit
…into groeneai/stats-warm-on-commit
…into groeneai/stats-warm-on-commit
…into groeneai/stats-warm-on-commit
…into groeneai/stats-warm-on-commit
…into groeneai/stats-warm-on-commit
…into groeneai/stats-warm-on-commit
|
I am not pursuing this further, and I do not think a PR should come out of it. Summary of what I measured on current master. The warm-on-commit approach: @ rschu1ze's point was right and I concede it. Warming on the commit path moves the cost off the first SELECT and onto every INSERT, which is what The lazy direction is already covered by #104691, so I am not duplicating it. I also checked whether the subcolumn normalization from 46a556f was worth carrying to master on its own, since it never landed there. It is not. Statistics are keyed by the parent column, and the estimator only translates No action needed here; noting it so the closed PR does not read as unfinished. |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Warm the table statistics estimator right after an INSERT commits so the first
SELECTdoes not synchronously cold-load and rebuild column statistics from disk in the query planner.Description
Helper PR against
stats-on-insert-size-threshold, folding in the root-fix direction discussed on #109454. Opened at @egor-click's request.Root fix (instead of gating the planner around the cold load):
ColumnsStatisticsthat INSERT already builds on the in-memory part (IMergeTreeDataPart::statistics_cache+setStatistics/tryGetCachedStatistics/hasCachedStatistics). Disk-loaded parts leave it empty and keep using the on-disk files.MergeTreeData::cached_estimatorinTransaction::commitonce committed parts become Active, so the firstSELECTskips the synchronous planner cold-load.cloneEmpty()+merge) before merging, so it never mutates the part-ownedColumnStatisticsthatloadStatistics()returns. This also protectsrefreshStatisticsand the what-if estimator, which both route throughaddStatistics.Hardening applied (item 1 of the 3 reported on #109454):
hasCachedStatistics), not onuse_statistics_cachealone. Without this gate, tables whose statistics are NOT materialized on insert (large tables abovematerialize_statistics_on_insert_max_table_size, or the setting off) would loop all active parts and do the full on-disk cold-load synchronously on every INSERT.Measurements (debug, this branch's base):
auto_statistics_types=''+materialize_statistics_on_insert=0skips warming under the INSERT id.join_convert_outer_to_innerquery, same binary/data: fix = 0 planner cold-loads on first SELECT-after-INSERT; baseline (use_statistics_cache=0) = 4 cold-loads (2 parts x 2 tables).Remaining follow-ups (reported on #109454, not in this PR): incremental warm instead of O(parts) rebuild per commit; bound
statistics_cacheretention by a table-size budget or drop after first warm; and thedisk_connections_hard_limitinteraction the bot flagged for remote-storage inserts.