Skip to content

Warm statistics estimator on commit to avoid first-SELECT cold load - #109925

Closed
groeneai wants to merge 32 commits into
ClickHouse:stats-on-insert-size-thresholdfrom
groeneai:groeneai/stats-warm-on-commit
Closed

groeneai wants to merge 32 commits into
ClickHouse:stats-on-insert-size-thresholdfrom
groeneai:groeneai/stats-warm-on-commit

Conversation

@groeneai

@groeneai groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Performance Improvement

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 SELECT does 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):

  • Retain the full per-column ColumnsStatistics that 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.
  • Warm MergeTreeData::cached_estimator in Transaction::commit once committed parts become Active, so the first SELECT skips the synchronous planner cold-load.
  • 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. This also protects refreshStatistics and the what-if estimator, which both route through addStatistics.

Hardening applied (item 1 of the 3 reported on #109454):

  • Commit-time warming is gated on committed parts actually carrying retained in-memory statistics (hasCachedStatistics), not on use_statistics_cache alone. Without this gate, tables whose statistics are NOT materialized on insert (large tables above materialize_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):

  • Smoke (MergeTree, tdigest+uniq+minmax+countmin on 2 cols): server-side planner cold-load marker = 0 across SELECT-after-INSERT / repeat / SELECT-after-2nd-INSERT; commit-warm fired 3x; no crash / LOGICAL_ERROR / sanitizer.
  • Gate verified both directions: implicit-stats table warms on commit under the INSERT query id; auto_statistics_types='' + materialize_statistics_on_insert=0 skips warming under the INSERT id.
  • A/B on the exact join_convert_outer_to_inner query, 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_cache retention by a table-size budget or drop after first warm; and the disk_connections_hard_limit interaction the bot flagged for remote-storage inserts.

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]>
@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Check Result
a Deterministic repro? Yes. First SELECT-after-INSERT with use_statistics_cache=1, stats materialized on insert: baseline = 4 planner cold-loads (2 parts x 2 tables); with fix = 0. Reproduced on demand via .scratch/ab*.sh.
b Root cause explained? INSERT builds full ColumnsStatistics but only the lightweight Estimate summary was retained on the part; the estimator builder needs full ColumnStatisticsPtr, so the first query re-read/rebuilt stats from disk synchronously in the planner (getConditionSelectivityEstimator loops all parts -> loadStatistics).
c Fix matches root cause? Yes. Retain the INSERT-built full stats on the in-memory part and warm the estimator at commit, so no cold-load in the planner. Not a gate/band-aid around the symptom.
d Test intent preserved / new tests? No existing test weakened. Behavior is a cache-warming optimization; correctness of stats-fed cost estimates is unchanged (stats never affect result rows).
e Demonstrated both directions? Yes. Baseline (no cache) = 4 cold-loads; fix = 0. Gate verified both ways (warms with retained stats; skips when stats not materialized).
f Fix general, not narrow patch? Yes. cloneEmpty()+merge in addStatistics protects ALL builder callers (commit warm, background refreshStatistics, what-if estimator), not just the reproduced path.
g Generalizes across inputs? Retention/warm applies to any stats types (tdigest/uniq/minmax/countmin) and any column set; tryGetCachedStatistics honors required-column filtering incl. .null subcolumns.
h Backward compatible? Yes. No setting default, on-disk, or wire format change. Behavior only warms an in-memory cache; disk-loaded parts keep using on-disk files.
i Invariants/contracts preserved? Yes. Estimator no longer mutates part-owned ColumnStatisticsPtr (was the correctness hazard). Lock ordering safe (parts_lock -> stats_mutex consistently; getConditionSelectivityEstimator releases stats_mutex before parts_lock). No ABBA.

Session id: cron:clickhouse-worker-slot-2:20260709-162000

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 9, 2026
@clickhouse-gh clickhouse-gh Bot closed this Jul 9, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Jul 9, 2026
@rschu1ze

Copy link
Copy Markdown
Member

Warm the table statistics estimator right after an INSERT commits so the first SELECT does not synchronously cold-load and rebuild column statistics from disk in the query planner.

For the primary key, we went the opposite route (MergeTree setting primary_key_lazy_load = true by default). Postponing work as much as possible is also the generally more reasonable approach. Just saying.

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.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks, all three points are fair.

  1. Orthogonality: agreed, this is independent of Materialize column statistics on INSERT for small tables by default #109454; merge or not on its own schedule.

  2. Lazy vs eager: your PK analogy holds against this PR as written. Warming happens synchronously on the commit path, so it moves cost from the first SELECT onto every INSERT and penalizes write-only / insert-heavy workloads, which is exactly what primary_key_lazy_load=true avoids. The distinction I'd draw is only about where the cold load lands, not whether to defer: for statistics the load currently happens inside the optimizer (getConditionSelectivityEstimator loops parts x columns and rebuilds countmin/tdigest/uniq), so it is on the latency-critical planning path rather than the read stage like PK. That argues for a cached first-touch load (build once on first planner access, cache thereafter) rather than eager-on-commit. That converges toward the PK lazy model while still killing repeated cold loads, without taxing writers. I'll pivot the PR that way if you agree the direction is worth it.

  3. Support statistics UniqV2 which internally uses UniqCombined64(12) #107863: it is still open and swaps only the uniq collector for UniqCombined(12); it does not change countmin, which is the heavy ~152 KB/col contributor on the cold-load path. So for tables using countmin statistics the first-SELECT cold load will largely remain after Support statistics UniqV2 which internally uses UniqCombined64(12) #107863 lands. Happy to re-measure the planner cold-load marker and first-SELECT wall-clock once Support statistics UniqV2 which internally uses UniqCombined64(12) #107863 is merged so we have hard numbers before deciding.

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");

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.

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?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

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.

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"))

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.

I see this bad code already exists. Who and when introduced it? Please ping that person.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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).

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.

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.

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.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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).

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.

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).

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.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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?

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.

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.

@alexey-milovidov alexey-milovidov self-assigned this Jul 15, 2026

@alexey-milovidov alexey-milovidov 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.

.

alexey-milovidov and others added 3 commits July 15, 2026 12:25
…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Reviewed both commits against the four points; they match what the inline notes describe:

  • 46a556f414c (c1/c2): loadStatistics now normalizes every requested name to its storage column via tryGetColumn/getNameInStorage, so .null, .size0, and any other subcolumn are served by the parent column's statistics through a plain exact-match filter. The hand-listed .null case and isColumnStatisticsRequired are gone; the helper is columnPassesFilter(columns_filter) with the empty-set = "no filter" convention documented in both the .cpp and the header.
  • 001c07e7435 (c3/c4): the per-part catch is removed and refreshStatistics no longer catches anything, so a statistics load failure propagates like a broken part. The asynchronous path catches at the upper level in the startStatisticsCache task lambda (log + reschedule), and the commit-time warm moved after clear() so a propagated exception cannot roll back parts that are already Active.

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 uniq for UniqCombined64(12); countmin (the ~152 KB/col contributor that dominates the cold load) is unchanged, so the first-SELECT cold-load cost for countmin tables is the same as before it merged.

…into groeneai/stats-warm-on-commit

# Conflicts:
#	src/Storages/MergeTree/MergeTreeData.cpp
…into groeneai/stats-warm-on-commit

# Conflicts:
#	src/Storages/MergeTree/IMergeTreeDataPart.cpp
@alexey-milovidov
alexey-milovidov deleted the branch ClickHouse:stats-on-insert-size-threshold August 13, 2026 04:07
@groeneai

Copy link
Copy Markdown
Collaborator Author

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 primary_key_lazy_load = true was chosen to avoid, and I have no production-shaped (coalesced, asynchronous, memory-aware) version of it.

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 <col>.null back to its parent (ConditionSelectivityEstimator.cpp:490, consumed under the parent name at :853). Any other subcolumn fails the exact-match getColumns().tryGet() at :362 and takes the explicit "not a real column" path at :367, which assigns a default selectivity and never consults statistics. So master's .null-only filter is co-extensive with what the estimator can actually use, and widening it would only read statistics files that nothing reads back. The two exception-handling points are moot as well: the per-part catch was removed in 6509e77, covered by 04209_statistics_retry_load.

No action needed here; noting it so the closed PR does not read as unfinished.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants