Repository navigation
Materialize column statistics on INSERT for small tables by default - #109454
Conversation
Cost-based join reordering needs column statistics (notably NDV of join keys) to avoid pathological plans. Statistics are auto-declared (`auto_statistics_types = 'minmax, uniq'`) but only materialized during merges, so freshly-loaded dimension tables have none at query time. Concretely, TPC-H Q5 and Q8 at scale factor 40 time out (>100s, spilling to disk) on a 32 GB machine: without the NDV of the low-cardinality `nationkey` (25 distinct values), the optimizer materializes a ~19 billion row `customer x supplier` intermediate as the hash-join build side. Enable `materialize_statistics_on_insert` by default, bounded by a new setting `materialize_statistics_on_insert_max_table_size` (default 1 GiB): small dimension tables get statistics at insert time (so query planning is correct right after a load), while large fact tables skip the per-insert cost and materialize during merges as before. The size check is an O(1) atomic load of the table's current size; `0` disables the limit. After this change, TPC-H Q5/Q8 at SF40/32 GB run in well under a second out of the box instead of timing out. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [428cbff] Summary: ✅
AI ReviewSummaryThis PR flips Findings❌ Blockers
Final VerdictChanges requested. The size-gate implementation itself is in reasonable shape now, but the default flip still ships with a planner/cache blocker and several rollout regressions that the current test opt-outs only hide. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 26/26 (100.00%) · Uncovered code |
…sert default Enabling `materialize_statistics_on_insert` by default (together with the default `auto_statistics_types = 'minmax, uniq'`) now materializes column statistics on INSERT for small tables. This perturbs two tests that measure low-level I/O and are unrelated to statistics: - `02263_lazy_mark_load`: the minmax statistics on `n3` let statistics part pruning drop the impossible `n3 == 11` predicate (`n3` is `number % 10`), so the query opens 0 files instead of 2 and the test no longer measures lazy mark loading. - `03310_index_hints_read_columns`: the auto statistics files add extra `FileOpen` events, and this test counts opened files precisely. Set `auto_statistics_types = ''` on the tables in both tests so they keep testing what they intend, independent of the statistics defaults. Verified locally: with the default the `02263` query opens 0 files, with `auto_statistics_types = ''` it opens 2 (matching the reference), and both tests pass. Fast test report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109454&sha=14d003324c827a87ee636e482dec91976f6fe5d3&name_0=PR&name_1=Fast%20test Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…_statistics_on_insert default Enabling `materialize_statistics_on_insert` by default (together with the default `auto_statistics_types = 'minmax, uniq'`) now materializes column statistics on INSERT for small tables. Empirically this adds a `statistics.packed` file to every part (as large as the column data itself for these tables), which inflates the on-disk part sizes and perturbs the counters reported by distributed index analysis: `Parts send` / `Granules send` drop from 8 to 6 in the `explain indexes=1, json=1` output. These four tests exercise distributed index analysis, not statistics, so set `auto_statistics_types = ''` on their tables. With no auto statistics the parts are byte-for-byte identical to what master produces (verified: no `statistics.packed` file is written), so the index analysis output matches the reference again, independent of the statistics defaults: - 03622_explain_indexes_distributed_index_analysis - 03622_explain_indexes_distributed_index_analysis_pushdown - 03836_distributed_index_analysis_pk_expression - 03836_distributed_index_analysis_skip_index_expression This complements the earlier isolation of 02263_lazy_mark_load and 03310_index_hints_read_columns. Fast test report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109454&sha=14d003324c827a87ee636e482dec91976f6fe5d3&name_0=PR&name_1=Fast%20test Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
📊 Cloud Performance Report 🟢 AI verdict: This PR turns on column statistics at INSERT time by default for tables under the new size cap, so cost-based join reordering gets good estimates on freshly-loaded dimension tables. That is exactly what shows up in the numbers: TPC-H Q7 (×7.8 faster) and Q8 (×2.0 faster) both improve because the planner now picks a cheaper join order, with large deltas confirmed by both tests. ClickBench Q18 is a single-table query with no joins, so the change cannot touch it; its -6.1% is within the noise band and correctly stays no_change. No regressions were flagged, and the envelope-suppressed Q18 verdict is consistent with the diff. clickbench🟢 No significant changes tpch_adapted_1_official🟢 2 improved Flagged queries (2 of 22)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. Debug info
|
Address AI review blocker: the new setting `materialize_statistics_on_insert_max_table_size` was registered in `SettingsChangesHistory` with `previous_value = 1073741824`, so a `compatibility` level older than `26.7` did not restore the pre-change behavior for users who explicitly re-enable `materialize_statistics_on_insert`. Before this PR there was no size cap at all, which is equivalent to "no limit" (`0`). Set `previous_value = 0` so old `compatibility` levels keep materializing statistics on INSERT regardless of table size, as before. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109454&sha=6e89370d23b7ad6310da0f61977a4eea97a014d2&name_0=PR PR: #109454 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Address AI review: the size gate for `materialize_statistics_on_insert` only consulted `getTotalActiveSizeInBytes`, but the parts of the current INSERT are not active yet. On the very first bulk load into an otherwise empty table the active size is still ~0, so a large single block would build statistics anyway. Add the size of the block being written (`block.bytes`, the same estimate already used just below for the part size) to the check, so a single large block into a fresh table is bounded too. This is a conservative bound (uncompressed block bytes vs. compressed active bytes over-estimates the resulting size, erring towards skipping statistics). Cumulative bounding of a highly-partitioned multi-block INSERT would require tracking bytes written across the whole INSERT and is left as a follow-up. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109454&sha=6e89370d23b7ad6310da0f61977a4eea97a014d2&name_0=PR PR: #109454 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The full CI run surfaced more tests perturbed by the new default (they were
not exercised by the fast test). With `materialize_statistics_on_insert` on
and the default `auto_statistics_types = 'minmax, uniq'`, each small table
now materializes a `statistics.packed` file per part on INSERT, which:
- adds low-level I/O the following tests count precisely:
- `02770_async_buffer_ignore`: extra S3 reads change the profile events.
- `test_replicated_merge_tree_s3::test_insert_select_replicated`: one extra
S3 object per part breaks the exact object-count assertion (was off by
exactly 3 replicas * 3 parts = 9 files).
- `test_merge_tree_s3_failover::test_write_failover`: the extra S3 write per
part shifts the request numbering the test injects failures into, so the
insert never succeeds within the retry window.
- enables statistics-based part pruning on freshly-inserted parts:
- `test_broken_projections`: pruning drops the `d == 12` / `c == 12`
predicate so no part uses the projection and `force_optimize_projection = 1`
throws `PROJECTION_NOT_USED`.
Set `auto_statistics_types = ''` on the tables in these tests so their parts
are byte-identical to before and they keep testing what they intend,
independent of the statistics defaults.
CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109454&sha=6e89370d23b7ad6310da0f61977a4eea97a014d2&name_0=PR
PR: #109454
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Address AI review: verify that `compatibility` with a pre-26.7 version restores the old behavior of the statistics-on-insert defaults, i.e. `materialize_statistics_on_insert = 0` and `materialize_statistics_on_insert_max_table_size = 0` (no size limit), so profiles that opt back into insert-time statistics keep materializing them regardless of table size. PR: #109454 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ttings The new regression test read the effective value of `materialize_statistics_on_insert` from `system.settings` and verified that `SET compatibility = '26.6'` restores the old default (off). The settings-randomization harness, however, passes `--materialize_statistics_on_insert` explicitly on the session, and `compatibility` never overrides a setting the user has already changed. So under randomization the compatibility revert this test checks becomes a no-op and the test fails (confirmed by the flaky-check diagnosis: it passes without randomization and reproduces only with `--materialize_statistics_on_insert True`). Testing the default and `compatibility` semantics of a setting is only meaningful when the harness does not override that setting, so tag the test `no-random-settings`. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109454&sha=4ef06e22b94d4101245c3d50b149bbd501364dd3&name_0=PR PR: #109454 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ics-on-insert default With `materialize_statistics_on_insert` on by default and the default `auto_statistics_types = 'minmax, uniq'`, each part now gets a `statistics.packed` object on INSERT. This test counts S3 requests exactly (`s3_check_objects_after_upload = 1` also verifies each uploaded object), so the extra object shifted the read counts: the INSERT went 20 -> 22 and the merge 2 -> 8, breaking the fixed reference. Set `auto_statistics_types = ''` on the table so its parts are byte-identical to before and the test keeps measuring exactly the S3 traffic it intends, independent of the statistics defaults. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109454&sha=4ef06e22b94d4101245c3d50b149bbd501364dd3&name_0=PR PR: #109454 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The new `materialize_statistics_on_insert` default (with the default `auto_statistics_types = 'minmax, uniq'`) writes a `statistics.packed` file for every part on INSERT, which two integration tests do not expect: - `test_remote_blobs_naming/test_backward_compatibility.py::test_replicated_merge_tree` counts remote blobs and now sees an extra file per part (`assert 12 == 13`). - `test_asynchronous_metrics_pk_bytes_fields/test.py::test_total_proj_pk_ig_in_memory_fields` runs with `force_optimize_projection = 1`; the fresh minmax statistics change cost-based projection selection so the projection is no longer chosen and the server throws `PROJECTION_NOT_USED`. Set `auto_statistics_types = ''` on the tables in these tests so their parts stay byte-identical to master, same as the other tests already isolated in this PR. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109454&sha=1e6f7603f1cee604591cbdc47c59fe16d0698858&name_0=PR Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The full CI run surfaced more tests that are sensitive to the extra `statistics.packed` file the new `materialize_statistics_on_insert` default writes for every part on INSERT (with the default `auto_statistics_types = 'minmax, uniq'`): - `test_max_suspicious_broken_parts::test_max_suspicious_broken_parts_bytes` and its `__wide` variant: the byte accounting assumes a part is ~751 B, but the statistics file grows it to ~1.46 KiB, exceeding `max_suspicious_broken_parts_bytes = 1000` on load. - `test_http_limits::test_disk_hard_limit_hit`: the extra statistics write needs one more S3 connection, tripping the `Disk` connection hard limit. - `test_filesystem_cache::test_force_filesystem_cache_on_merges`: the merge reads/builds statistics through the cache, changing the read counts (`assert r_cache_count_3 == r_cache_count` failed with `24010 != 8614`). - `test_partition::test_partition_complex`: the `statistics.packed` file appears in the frozen parts, changing the hard-coded shadow checksums. Set `auto_statistics_types = ''` on the tables in these tests so their parts stay byte-identical to master, same as the other tests already isolated in this PR. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109454&sha=1e6f7603f1cee604591cbdc47c59fe16d0698858&name_0=PR Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…olation The previous change added the table-level setting `auto_statistics_types=''` to the `CREATE TABLE` in `test_remote_blobs_naming/test_backward_compatibility.py` to keep the number of remote blobs stable under the new `materialize_statistics_on_insert` default. But this `CREATE` is executed on `old_node` too, which runs a released `25.8.4.13` server that does not know the `auto_statistics_types` MergeTree setting (introduced later) and rejects it with `UNKNOWN_SETTING`, failing `test_replicated_merge_tree[test_case1..4]`. Only the new server materializes statistics on INSERT (`old_node` predates both the `auto_statistics_types='minmax, uniq'` default of 26.4 and the setting itself). So instead of a table-level setting, disable it on the new server's INSERT via the session setting `materialize_statistics_on_insert = 0`, which both versions understand and which leaves `old_node`'s `CREATE` untouched. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109454&sha=53f98c51adfbaa325eaad658479a807bc0640ec8&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20flaky%29 PR: #109454 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The previous fix disabled `materialize_statistics_on_insert` for the new
server's INSERT in `test_remote_blobs_naming/test_backward_compatibility.py`
by appending a `SETTINGS materialize_statistics_on_insert = 0` clause after
`VALUES (1, 'b')`. That placement is invalid: in an `INSERT ... VALUES ...`
query the `SETTINGS` clause must precede the data, and with async INSERT the
trailing text is parsed as another row, so the query fails with
`Code: 27. Cannot parse input: expected '(' before: 'SETTINGS ...'`
(`test_replicated_merge_tree[test_case1..4]`).
Pass the setting through the client (`settings={...}`) instead of embedding
it in the SQL. It is applied at the session level, so it works regardless of
async INSERT and does not perturb the query text. The setting is a core query
setting understood by both the new and the old server, unlike the table-level
`auto_statistics_types` that the old `25.8.4.13` server would reject.
CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109454&sha=d2c800e84d64f95f606ee7525465ba20b77963e3&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20flaky%29
PR: #109454
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
@groeneai my bot made a small prototype pass for this PR’s regressed tests code path, could you please verify its correctness and check if the tests mentioned by Alexey will not degrade and performance improvement in this PR will be still in place Patch ideaThe main issue seems to be that this PR makes statistics available by default on small MergeTree tables, and then The narrow prototype I tested avoids those cold stats loads in the two places that showed up in the affected regressions:
I would not claim this exact patch has zero possible downside. The risk is bounded but non-zero:
This prototype validates that avoiding synchronous cold loads fixes the measured PR regressions. Targeted local validationLocal ARM validation, simulating this PR behavior with
Profile-event probes confirmed the mechanism:
Caveat: this was tested on a local fe4258-derived build with PR behavior simulated via the setting, not an exact rebuild of this PR head. Prototype patchdiff --git a/src/Processors/QueryPlan/Optimizations/optimizeJoin.cpp b/src/Processors/QueryPlan/Optimizations/optimizeJoin.cpp
index bb0f4658a78..2486d69dac0 100644
--- a/src/Processors/QueryPlan/Optimizations/optimizeJoin.cpp
+++ b/src/Processors/QueryPlan/Optimizations/optimizeJoin.cpp
@@ -343,14 +343,20 @@ static RelationStats estimateAggregatingStepStats(const AggregatingStep & aggreg
}
RelationStats estimateReadRowsCount(QueryPlan::Node & node, const ActionsDAG::Node * filter = nullptr);
+RelationStats estimateReadRowsCount(QueryPlan::Node & node, const ActionsDAG::Node * filter, bool allow_statistics);
RelationStats estimateReadRowsCount(QueryPlan::Node & node, const ActionsDAG::Node * filter)
+{
+ return estimateReadRowsCount(node, filter, true);
+}
+
+RelationStats estimateReadRowsCount(QueryPlan::Node & node, const ActionsDAG::Node * filter, bool allow_statistics)
{
IQueryPlanStep * step = node.step.get();
if (const auto * reading = typeid_cast<const ReadFromMergeTree *>(step))
{
String table_display_name = reading->getStorageID().getTableName();
- if (reading->getContext()->getSettingsRef()[Setting::use_statistics])
+ if (allow_statistics && reading->getContext()->getSettingsRef()[Setting::use_statistics])
{
if (auto estimator = reading->getConditionSelectivityEstimator(reading->getAllColumnNames()))
{
@@ -416,7 +422,7 @@ RelationStats estimateReadRowsCount(QueryPlan::Node & node, const ActionsDAG::No
if (const auto * reading = typeid_cast<const CommonSubplanReferenceStep *>(step))
{
- return estimateReadRowsCount(*reading->getSubplanReferenceRoot(), filter);
+ return estimateReadRowsCount(*reading->getSubplanReferenceRoot(), filter, allow_statistics);
}
if (node.children.size() != 1)
@@ -424,7 +430,7 @@ RelationStats estimateReadRowsCount(QueryPlan::Node & node, const ActionsDAG::No
if (const auto * limit_step = typeid_cast<const LimitStep *>(step))
{
- auto estimated = estimateReadRowsCount(*node.children.front(), filter);
+ auto estimated = estimateReadRowsCount(*node.children.front(), filter, allow_statistics);
auto limit = limit_step->getLimit();
if (!estimated.estimated_rows || estimated.estimated_rows > limit)
estimated.estimated_rows = limit;
@@ -433,7 +439,7 @@ RelationStats estimateReadRowsCount(QueryPlan::Node & node, const ActionsDAG::No
if (const auto * expression_step = typeid_cast<const ExpressionStep *>(step))
{
- auto stats = estimateReadRowsCount(*node.children.front(), filter);
+ auto stats = estimateReadRowsCount(*node.children.front(), filter, allow_statistics);
remapColumnStats(stats.column_stats, expression_step->getExpression());
return stats;
}
@@ -442,14 +448,14 @@ RelationStats estimateReadRowsCount(QueryPlan::Node & node, const ActionsDAG::No
{
const auto & dag = filter_step->getExpression();
const auto * predicate = static_cast<const ActionsDAG::Node
*>(dag.tryFindInOutputs(filter_step->getFilterColumnName()));
- auto stats = estimateReadRowsCount(*node.children.front(), predicate);
+ auto stats = estimateReadRowsCount(*node.children.front(), predicate, allow_statistics);
remapColumnStats(stats.column_stats, filter_step->getExpression());
return stats;
}
if (const auto * aggregating_step = typeid_cast<const AggregatingStep *>(step))
{
- auto stats = estimateReadRowsCount(*node.children.front(), filter);
+ auto stats = estimateReadRowsCount(*node.children.front(), filter, allow_statistics);
auto aggregation_stats = estimateAggregatingStepStats(*aggregating_step, stats);
return aggregation_stats;
}
@@ -464,7 +470,7 @@ RelationStats estimateReadRowsCount(QueryPlan::Node & node, const ActionsDAG::No
if (const auto * sorting_step = typeid_cast<const SortingStep *>(step))
{
- auto stats = estimateReadRowsCount(*node.children.front(), filter);
+ auto stats = estimateReadRowsCount(*node.children.front(), filter, allow_statistics);
if (sorting_step->getLimit())
{
if (!stats.estimated_rows || stats.estimated_rows > sorting_step->getLimit())
@@ -475,12 +481,12 @@ RelationStats estimateReadRowsCount(QueryPlan::Node & node, const ActionsDAG::No
#if CLICKHOUSE_CLOUD
if (dynamic_cast<LogicalExchangeStep *>(step))
- return estimateReadRowsCount(*node.children.front(), filter);
+ return estimateReadRowsCount(*node.children.front(), filter, allow_statistics);
#endif
if (const auto * transform = dynamic_cast<const ITransformingStep *>(step);
transform && transform->getTransformTraits().preserves_number_of_rows)
- return estimateReadRowsCount(*node.children.front(), filter);
+ return estimateReadRowsCount(*node.children.front(), filter, allow_statistics);
return {};
}
@@ -603,6 +609,7 @@ struct QueryGraphBuilder
SortingStep::Settings sorting_settings;
String dummy_stats;
UInt64 effective_randomize_seed = 0;
+ bool allow_statistics_estimation = true;
BuilderContext(
const QueryPlanOptimizationSettings & optimization_settings_,
@@ -753,7 +760,7 @@ static size_t addChildQueryGraph(QueryGraphBuilder & graph, QueryPlan::Node * no
}
graph.inputs.push_back(node);
- RelationStats stats = estimateReadRowsCount(*node);
+ RelationStats stats = estimateReadRowsCount(*node, nullptr, graph.context->allow_statistics_estimation);
std::optional<size_t> num_rows_from_cache = graph.context->statistics_context.getCachedHint(node);
if (graph.context->join_settings.use_hash_table_stats_for_join_reordering && num_rows_from_cache)
@@ -1491,6 +1498,9 @@ void optimizeJoinLogicalImpl(JoinStepLogical * join_step, QueryPlan::Node & node
/// Do not reorder joins, only allow swap
query_graph_size_limit = 2;
+ std::vector<SharedHeader> relation_headers_for_statistics_policy;
+ collectJoinGraphRelationHeadersForJoin(node, query_graph_size_limit, join_step->getJoinSettings(),
relation_headers_for_statistics_policy);
+
/// Skip join order optimization when the join graph contains relations with overlapping column
/// names, which the `JoinExpressionActions`-based reconstruction does not support. See the comment
/// on `joinGraphHasOverlappingColumnNames`. This generalizes a check over the immediate children to
@@ -1503,6 +1513,7 @@ void optimizeJoinLogicalImpl(JoinStepLogical * join_step, QueryPlan::Node & node
QueryGraphBuilder query_graph_builder(optimization_settings, node, join_step->getJoinSettings(),
join_step->getSortingSettings());
query_graph_builder.context->dummy_stats = join_step->getDummyStats();
+ query_graph_builder.context->allow_statistics_estimation = relation_headers_for_statistics_policy.size() > 2;
buildQueryGraph(query_graph_builder, node, nodes, query_graph_size_limit);
node = chooseJoinOrder(std::move(query_graph_builder), nodes, strictness);
diff --git a/src/Processors/QueryPlan/Optimizations/optimizePrewhere.cpp
b/src/Processors/QueryPlan/Optimizations/optimizePrewhere.cpp
index 9b2bf726b36..956ae8d76c1 100644
--- a/src/Processors/QueryPlan/Optimizations/optimizePrewhere.cpp
+++ b/src/Processors/QueryPlan/Optimizations/optimizePrewhere.cpp
@@ -194,15 +194,13 @@ void optimizePrewhere(QueryPlan::Node & parent_node, const bool remove_unused_co
const auto & queried_columns = source_step_with_filter->requiredSourceColumns();
- /// Statistics are only used to reorder conditions, so skip if there is just one.
- const auto & filter_root_node = filter_step->getExpression().findInOutputs(filter_step->getFilterColumnName());
- const bool has_multiple_conditions = filter_root_node.type == ActionsDAG::ActionType::FUNCTION
- && filter_root_node.function_base && filter_root_node.function_base->getName() == "and";
-
+ /// Avoid loading column statistics in this latency-sensitive optimizer pass.
+ /// Here statistics are only used to reorder conditions before PREWHERE; column-size
+ /// heuristics are still available and are much cheaper for fresh small tables.
MergeTreeWhereOptimizer where_optimizer{
std::move(column_compressed_sizes),
storage_snapshot,
- (has_multiple_conditions && read_from_merge_tree_step) ?
read_from_merge_tree_step->getConditionSelectivityEstimator(queried_columns) : nullptr,
+ nullptr,
queried_columns,
storage.supportedPrewhereColumns(),
getLogger("QueryPlanOptimizePrewhere")}; |
|
@egor-click I verified the prototype on the actual PR head (eb0d115), not a simulated build. It compiles cleanly and the mechanism works as you describe. Verdict: correct, does not degrade the mentioned tests, and the headline wins are preserved. Method: rebuilt PR head with vs without the prototype, counted the join-optimizer stats-load path (the
So the Regressed tests will not degrade. All six ( PR performance improvement preserved. TPC-H Q5 and Q8 (the >200s to 0.5s cases) are 6-table join graphs, so Correctness. Statistics here only feed cost estimates for join order / build-side swap and for PREWHERE condition ordering. They never affect result rows, so results are unchanged in both halves. The join half falls back to the existing range/index estimates; the PREWHERE half falls back to column-size heuristics ( Two honest caveats, both bounded and both matching your own notes:
Net: the prototype is a sound, targeted fix for the regression class. If you want the two-table swap to still benefit from stats when they are already warm, an alternative would be to gate on "stats already cached" rather than on relation count, but that is more complex and the current gate is a reasonable trade-off. (FYI, unrelated to your question: the two items the AI review flagged, the |
|
Updating the branch to fix the |
| )", 0) \ | ||
| DECLARE(Bool, materialize_statistics_on_insert, false, R"( | ||
| If INSERTs build and insert statistics. If disabled, statistics will be build and stored during merges or by explicit MATERIALIZE STATISTICS | ||
| DECLARE(Bool, materialize_statistics_on_insert, true, R"( |
There was a problem hiding this comment.
Turning this default on means every freshly inserted small MergeTree part now carries statistics, and the planner immediately starts synchronously loading them in latency-sensitive paths. optimizeJoin always calls getConditionSelectivityEstimator for ReadFromMergeTree relations when use_statistics is enabled (optimizeJoin.cpp:353-356), optimizePrewhere does the same for multi-condition filters (optimizePrewhere.cpp:202-205), and MergeTreeData::getConditionSelectivityEstimator then reads stats from every part on the first query (MergeTreeData.cpp:869-888).
That gives the multiway-join win you want, but it also regresses simple two-relation joins and PREWHERE-only queries on freshly loaded small tables by making planning pay LoadedStatisticsMicroseconds for no reorder benefit. The regressions called out in the PR discussion (join_convert_outer_to_inner, join_filter_pushdown_equivalent_sets, etc.) are exactly this path. Either keep materialize_statistics_on_insert off by default until those planner call sites stop cold-loading statistics in the no-benefit cases, or land that planner guard in the same PR.
There was a problem hiding this comment.
Acknowledged, and this is the central open question of the PR rather than something I can settle unilaterally — @rschu1ze has asked to hold the default flip precisely on this ground, so the decision is his and mine to make together.
To state my position on the record: the cold-load in optimizeJoin / optimizePrewhere is not introduced by this PR — it already happens today for any table whose statistics were built at merge time. What this PR changes is when the first cold load happens: with the default off, a freshly loaded small table has no statistics at all and the planner skips the estimator entirely; with it on, the first query after the load pays the load. That cost is bounded by the statistics of one small table (the gate caps it at materialize_statistics_on_insert_max_table_size), and it buys the cost-based join reordering that is worth ×8 on TPC-H Q7 and ×2.1 on Q8 in the cloud benchmark runs on this PR.
The warm-on-commit fix that removes the cold load from the query path is #109925; my stated plan is to merge that first and re-evaluate this PR on top of it. I am not going to work around it here with planner-side guards, because that would add a second mechanism for something #109925 removes at the source.
|
@alexey-milovidov wdyt about the proposed patch? |
|
@egor-click, both sounds ok, but are they necessary? There are two questions:
|
| ENGINE = MergeTree() | ||
| ORDER BY id | ||
| SETTINGS storage_policy = 's3', min_bytes_for_wide_part=1000000; | ||
| -- auto_statistics_types='': otherwise the new materialize_statistics_on_insert default writes an |
There was a problem hiding this comment.
This test change is masking a real upgrade regression rather than just isolating test noise. With the new default, the same compact S3-backed INSERT now needs one more active disk connection for statistics.packed, so installations that deliberately run with disk_connections_hard_limit = 10 start throwing HTTP_CONNECTION_LIMIT_REACHED after upgrade. Disabling auto_statistics_types here makes CI green, but it leaves the production behavior broken for that configuration. The fix needs to be in the feature itself: either avoid spending another disk-connection slot on insert-time statistics here, or keep insert-time statistics off for remote-storage tables / tight connection budgets.
There was a problem hiding this comment.
This one I agree is a real behavioral change and not just test noise, and I do not want to paper over it: with the default on, an S3-backed INSERT writes one more object and therefore needs one more disk connection, so an installation that has pinned disk_connections_hard_limit to exactly its current high-water mark can start getting HTTP_CONNECTION_LIMIT_REACHED after an upgrade.
Two things bound it. The statistics file is written through the same part-writing path as the other part files, so it is one additional object per part, not a per-column or per-block multiplier; and disk_connections_hard_limit is not set by default — the test sets it to 10 deliberately to exercise the limit, which is far below any realistic budget. So the exposure is "a deployment that has tuned the limit to the exact minimum", not "every S3 user".
Still, the honest fix for the deployment case is a compatibility/opt-out story, and that already exists: materialize_statistics_on_insert = 0, or auto_statistics_types = '' per table, or compatibility set to a version before 26.8, all restore the previous connection profile — this is covered by the SettingsChangesHistory entries and by 04505_materialize_statistics_on_insert_compatibility. Making the default itself conditional on the connection budget is not something I want to build: a default that silently changes behavior based on a resource limit is harder to reason about than a default the user can turn off. Whether that trade is acceptable at rollout time is a call for @rschu1ze and me, and it is part of the same "should the default flip now" decision.
|
Item 2 is fixed by #114039, but not the way I said it would be: the bound derivation is unchanged. Scaling the bound for debug builds does not work here. With the engine fix of #113456 reverted the two Concentrating the same fold in one row keeps the interruptible work and drops the prologue by the same factor. The arms now stop at about 1100ms worst case over 50 runs, and still overshoot to about 14.8s with #113456 reverted, so the assertion discriminates more sharply than before. Both arms are changed; the second one had the same margin and had not crossed the bound only by luck. |
|
Update on item 2: #114039 is closed. @ PedroTadim closed it and is removing the test instead, in #114061, which deletes Item 1 is unaffected: #113925 is still open and awaiting review. |
| # https://github.com/ClickHouse/ClickHouse/issues/112598 | ||
| node.query( | ||
| "CREATE OR REPLACE TABLE t_packed_local (id UInt64, s String) ENGINE = MergeTree ORDER BY id SETTINGS min_bytes_for_full_part_storage = '10M'" | ||
| "CREATE OR REPLACE TABLE t_packed_local (id UInt64, s String) ENGINE = MergeTree ORDER BY id SETTINGS min_bytes_for_full_part_storage = '10M', auto_statistics_types = ''" |
There was a problem hiding this comment.
This auto_statistics_types='' pin is hiding a real rollout bug, not just test noise. With materialize_statistics_on_insert on by default, freshly inserted small parts now carry statistics on the ordinary path, but packed-io create / extract still copy the statistics representation verbatim instead of converting between the full-part statistics.packed layout and the packed-part statistics_<column>.stats layout (see src/IO/PackedFilesOperations.cpp). In the create direction that is worse than a diff-only mismatch: IMergeTreeDataPart::getStatisticsPackedReader still opens <part>/statistics.packed directly whenever the checksum says it exists, so a packed part created from a full part with stats ends up with unreadable statistics. Disabling auto_statistics_types here makes the test pass, but it leaves the default flip broken for packed-io users. This needs the packed-io fix in the same PR, or the default should stay off until #112598 is resolved.
There was a problem hiding this comment.
🕵 This incompatibility is real, but it is pre-existing and tracked in #112598 (filed from this PR's review; the test references it in a comment right above this line). Parts produced by merges, MATERIALIZE STATISTICS, or explicit STATISTICS(...) columns already hit the same packed-io layout mismatch with the old default, because auto_statistics_types already produces statistics on merge — the default flip only makes fresh insert-time parts reach it sooner. The auto_statistics_types = '' pin keeps this test focused on the packed-io round-trip itself; the representation conversion belongs in the packed-io fix for #112598 rather than in this PR.
|
@alexey-milovidov @rschu1ze @egor-click — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
…ESTORE A non-APPEND refreshable materialized view is only supported in Atomic and Replicated databases. CREATE enforced this in validateMaterializedViewColumnsAndEngine, but the call is gated on mode <= CREATE, so a full-definition ATTACH (mode ATTACH) and a RESTORE that remaps the view into another database (SECONDARY_CREATE with is_restore_from_backup) bypassed the check. In a Memory database the view then got a Nil StorageID UUID, and its refresh (CREATE OR REPLACE of the temp inner table into a Replicated-db target) wrote the Nil into DDLLogEntry.parent_table_uuid, so checkParentTableExists(Nil) -> DatabaseCatalog::tryGetByUUID(Nil) tripped chassert(uuid != Nil && ...) (abort in debug/sanitizer; in release the refresh instead failed permanently with TABLE_IS_DROPPED "Parent table doesn't exist"). Hoist the engine check out of validateMaterializedViewColumnsAndEngine into createTable, gated on is_fresh_definition = mode <= CREATE || (mode == ATTACH && !attach_short_syntax) || is_restore_from_backup, mirroring the existing is_fresh_definition predicate in registerStorageMergeTree.cpp. Stored definitions (short ATTACH, ATTACH DATABASE, restart) and plain Replicated-DDL replay stay exempt; fresh full-definition ATTACH and RESTORE-with-remap are validated like CREATE. Also add a fail-close Nil guard in checkParentTableExists (return false, mirroring the existing guard in getRMVCoordinationInfo) so metadata written by older binaries loads and its refresh fails cleanly instead of aborting. Found by BuzzHouse (arm_asan_ubsan on PR ClickHouse#111370, amd_msan on PR ClickHouse#109454; both unrelated to this code path). Co-Authored-By: Claude Opus 4.8 <[email protected]>
`WITH FILL FROM`/`TO` values are converted to a type wide enough for the
arithmetic - `Int64` for every integer column type - while the generated values
are written into a column of the column's own type, which truncates whatever
does not fit its range. A truncated value wraps around, so the filled stream
stops being monotonic while the query plan keeps claiming that it is still
sorted by the fill columns.
`DISTINCT` in order relies on that claim and reads the stream as a sequence of
sorted runs, so it deduplicates within wrong ranges:
SELECT count() FROM (SELECT DISTINCT x, s FROM
(SELECT toUInt8(5) AS x, 'Hello' AS s ORDER BY x ASC WITH FILL FROM 1 TO 1025))
returns 1024 instead of 257 in a release build, and in a debug or sanitizer
build it aborts with `Equal values are not contiguous within the range assumed
to be sorted` in `DistinctSortedStreamTransform`.
Reject such bounds with `INVALID_WITH_FILL_EXPRESSION`, next to the existing
check that rejects negative bounds for an unsigned column type. `TO` is an
exclusive bound, so it may still be one step outside of the range:
`WITH FILL FROM 0 TO 256` over a `UInt8` column keeps generating 0..255.
Found by the AST fuzzer:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109454&sha=b0030d87c1f4e4b31d2766c17286e42492a2da94&name_0=PR&name_1=AST%20fuzzer%20%28amd_msan%29
ClickHouse#109454
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Query 2 of polymorphic_parts_l.xml (INSERT through hits_buffer) takes 2.30 s on MasterCI amd and 4.22 s on arm. No existing query number or text changes: 1 query is disabled and 1 copy appended as 3, the same INSERT on numbers(20000), i.e. 20 parts of the same 1000 rows. Decision (deterministic, two repetitions on NUMA nodes 5 and 0, official amd release builds, both seat orders): - copy of query 2: per-part time 0.971 / 1.010 of the original's, per-part user time 1.005 / 1.026; on the MasterCI pair of ClickHouse#109000 (7a4e895 -> e523465) it keeps 1.002 / 1.097 of the original's client-time slowdown (original 1.217 / 1.214, copy 1.217 / 1.234). - query 0 (wide) is not replaced: on the ClickHouse#109454 pair (2485f14 -> 45cb837) its 20-part copy's per-part user time moved by 0.972 in one of four passes, and the rule asks for > 1 in every pass. hits_wide now receives 20 instead of 100 parts per run from the Buffer query, so a cost that grows with the parts already in the table, rather than per written part, is smaller in the copy. Saving: about 19 s of query time per master perf job on amd and 34 s on arm. Related: ClickHouse#129258 Co-Authored-By: Claude Opus 5.5 <[email protected]>
No existing query number or text changes: 2 queries are disabled and 2 copies appended as 3 and 4. Queries 0 (wide) and 2 (Buffer) take 1.59 and 2.19 s on MasterCI amd (3.00 and 4.09 s on arm); each writes 100 parts of 100 rows. The copies are the same INSERTs on numbers(2000): 20 parts of the same 100 rows. The compact query (0.28 s) keeps its 100 parts. Local A/B with perf.py on official MasterCI builds, two repetitions on different NUMA nodes, both seat orders (decide.py VERDICT ok, GEN_ARGS 1 1): - per part, copy vs original: time 0.97-1.00x, user time 1.00-1.03x; file opens and buffer allocations per part equal, statistics step present exactly when in the original. - ClickHouse#109000 (7a4e895 -> e523465): the Buffer copy keeps 80-104% of query 2's client-time slowdown (CI: user time 1.38x amd, 1.70x arm). - ClickHouse#109454 (2485f14 -> 45cb837): the wide copy keeps 93-97% of query 0's per-part user time increase (CI: 1.07x amd, 1.06x arm). The ClickHouse#109454 passes ran perf.py with --min-runs 30 --cap 30: at CI's 5-7 runs per server a copy that keeps a 6% effect fully misses it in a third or more of passes. hits_wide receives 20 instead of 100 parts per run from each copy, so a cost that grows with the parts already in the table, rather than per written part, is smaller in the copies. Projected CI medians: 0.32 / 0.42-0.43 s on amd, 0.60 / 0.79-0.80 s on arm; about 31 s of query time per master perf job on amd and 57 s on arm. Related: ClickHouse#129258 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes: #109261
Cost-based join reordering relies on column statistics (in particular the number of distinct values of join keys) to avoid pathological plans. Column statistics are auto-declared by default (
auto_statistics_types = 'minmax, uniq'), but they are only materialized during merges (materialize_statistics_on_merge) — so a freshly bulk-loaded table has no usable statistics at query time until it happens to be merged.This bites the TPC-H benchmark. At scale factor 40 on a 32 GB machine, Q5 and Q8 time out (>100s, spilling to disk):
nationkey(25 distinct values), the optimizer cannot see that joiningcustomerandsupplieronnationkey(via the transitivec_nationkey = s_nationkey) produces a ~19 billion row many-to-many intermediate, and it materializes that as the hash-join build side.customer509 MiB,supplier32 MiB,region/nationtiny), so materializing their statistics on insert is cheap — but the fact tables (lineitem11 GiB,orders2.5 GiB) are large and should not pay per-insert statistics cost.This PR enables
materialize_statistics_on_insertby default, bounded by a new settingmaterialize_statistics_on_insert_max_table_size(default 25 GiB): tables whose current size is at or below the threshold build statistics at insert time, larger tables skip it and materialize during merges as before. The size check is anO(1)atomic load of the table's current active size;0disables the limit.Measured on TPC-H SF40 with the server memory capped at 28.8 GiB (0.9 × 32 GiB), out of the box (no manual
MATERIALIZE STATISTICS):The per-insert cost is gated correctly: inserting into a table already above the threshold builds no statistics (
MergeTreeDataWriterStatisticsCalculationMicroseconds = 0), while an uncapped insert of the same block spends the usual time.Validation on other benchmarks
To check the effect more broadly, I compared having statistics available at load time (this change) against not having them (
use_statistics=0, the pre-change planning state), on the ClickBench/versionsquery sets, on the same freshly-loaded data under the 32 GiB cap:Overall, making dimension statistics available out of the box is strongly net-positive — many multi-× speedups and several queries rescued from OOM/timeout. A small number of queries regress because the cost-based join reorder occasionally makes a worse choice with statistics than without; that is a pre-existing optimizer-quality concern that enabling statistics by default surfaces more often, not a regression in the materialization itself.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Column statistics are now materialized on
INSERTby default when the table's current active size plus the written block size is at most the newmaterialize_statistics_on_insert_max_table_sizesetting (default 25 GiB); the check is per written block, so a first bulk load into an empty table may still materialize statistics for each written block. This gives the cost-based join optimizer accurate estimates for freshly-loaded dimension tables and avoids pathological join orders (for example, TPC-H Q5 and Q8 no longer time out at scale factor 40), while large established fact tables keep materializing statistics during merges.🤖 Generated with Claude Code
Version info
26.8.1.1307(included in26.8and later)