Skip to content

Materialize column statistics on INSERT for small tables by default - #109454

Merged
alexey-milovidov merged 69 commits into
masterfrom
stats-on-insert-size-threshold
Aug 13, 2026
Merged

alexey-milovidov merged 69 commits into
masterfrom
stats-on-insert-size-threshold

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 5, 2026 •

Copy link
Copy Markdown
Member

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

  • Without the NDV of the low-cardinality nationkey (25 distinct values), the optimizer cannot see that joining customer and supplier on nationkey (via the transitive c_nationkey = s_nationkey) produces a ~19 billion row many-to-many intermediate, and it materializes that as the hash-join build side.
  • The dimension tables that carry the decisive join keys are small (SF40: customer 509 MiB, supplier 32 MiB, region/nation tiny), so materializing their statistics on insert is cheap — but the fact tables (lineitem 11 GiB, orders 2.5 GiB) are large and should not pay per-insert statistics cost.

This PR enables materialize_statistics_on_insert by default, bounded by a new setting materialize_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 an O(1) atomic load of the table's current active size; 0 disables 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):

Query Before After
Q5 >200s, 8.6 GB spilled to disk 0.5s, 636 MiB, no spill
Q8 143s, 4.35 GB spilled to disk 0.6s, 1.37 GiB, no spill

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 /versions query sets, on the same freshly-loaded data under the 32 GiB cap:

  • TPC-DS (SF40, 103 queries): 4 queries go from OOM/timeout to succeeding (q24, q51, q71, q93); many large speedups (q74 98×, q66 31×, q7 22×, q83 18×, …); ~35% faster in aggregate; no genuine regressions.
  • JOB / IMDB (113 queries): net ~12% faster; wins up to ~8× (q1, q91, q92). The dataset is small enough that nothing fails either way; a couple of queries regress mildly (q55, q26).
  • Coffee Shop (fact 359M rows + 2 dimensions, 17 queries): wins up to ~50× (q8 42×, q11 and q16 go from timeout to 1.4s / 63s, q13 15×); one query regresses ~2.3× (q17).

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

  • Performance Improvement

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

Column statistics are now materialized on INSERT by default when the table's current active size plus the written block size is at most the new materialize_statistics_on_insert_max_table_size setting (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

  • Merged into: 26.8.1.1307 (included in 26.8 and later)

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

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

LGTM

@clickhouse-gh

clickhouse-gh Bot commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [428cbff]

Summary: ✅


AI Review

Summary

This PR flips materialize_statistics_on_insert on by default and adds materialize_statistics_on_insert_max_table_size to limit insert-time statistics to small tables. The size-gate and compatibility wiring now look coherent, but the rollout is still not merge-ready: the current head still makes common queries synchronously load statistics from the planner, still leaves warmed estimators stale after new inserts, and the test opt-outs are still masking user-visible regressions in S3 hard-limit, projection, and packed-io flows.

Findings

❌ Blockers

  • [src/Core/Settings.cpp:1968-1972, src/Processors/QueryPlan/Optimizations/optimizeJoin.cpp:362-366, src/Processors/QueryPlan/Optimizations/optimizePrewhere.cpp:246-255, src/Storages/MergeTree/MergeTreeData.cpp:918-927, 3304-3325, src/Storages/MergeTree/MergeTreeDataWriter.cpp:829-849] The PR promises “fresh statistics on freshly-loaded dimension tables”, but the current code still only exposes them through query-time synchronous loads or the periodic background refresh. optimizeJoin and optimizePrewhere still call getConditionSelectivityEstimator on the hot planning path, that helper still loads statistics.packed synchronously without storing the result in cached_estimator, and an already-warm cached_estimator is still returned unchanged until refresh_statistics_interval refreshes it. The new 04650_materialize_statistics_on_insert_planner_cold_load test now pins the planner-side load explicitly, and the current MergeTreeData.cpp logic still means repeated queries keep paying it until the background task fires while warmed tables keep planning against stale NDVs after new inserts. Suggested fix: land the commit-time estimator warming/invalidation path first (the #109925 approach referenced in the review threads), or keep materialize_statistics_on_insert off by default until the planner no longer has to cold-load or reuse stale statistics.

⚠️ Majors

  • [tests/integration/test_http_limits/test_hard_limit.py:56-58] This opt-out is still masking a real upgrade regression: on S3-backed tables the new default writes one extra statistics object per part, so inserts need one more disk connection. Installations that deliberately set disk_connections_hard_limit to the current minimum start throwing HTTP_CONNECTION_LIMIT_REACHED after upgrade even though the table shape and insert volume are unchanged. The feature path is unchanged; only the test is opted out. Suggested fix: either make insert-time statistics not consume an extra concurrent disk connection on the write path, or keep the default off for remote-storage tables and tight connection budgets.
  • [tests/integration/test_broken_projections/test.py:77-80] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/109454#discussion_r3631508165] The projection/pruning conflict is still real on the current head: insert-time statistics make freshly inserted parts immediately eligible for statistics-based part pruning, and force_optimize_projection = 1 can still turn that into PROJECTION_NOT_USED on ordinary fresh-data queries. This was already possible later on merged tables, but the default flip makes it happen right after INSERT, which changes user-visible behavior for workloads that rely on forced projection use. Suggested fix: either fix the projection-selection contract when statistics prune all base parts, or keep insert-time statistics off by default until that interaction is addressed.
  • [tests/integration/test_packed_io/test.py:132-145, src/Storages/MergeTree/IMergeTreeDataPart.cpp:1195-1210, src/IO/PackedFilesOperations.cpp:184-223] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/109454#discussion_r3748593740] packed-io still does not translate column-statistics representation between full and packed parts: create and extract copy files verbatim, while getStatisticsPackedReader still looks for a top-level statistics.packed. As soon as ordinary INSERTs start materializing statistics by default, packed-io round-trips on fresh small tables inherit that mismatch instead of only hitting it after a merge or explicit materialization. Suggested fix: land the representation-conversion fix from #112598 together with the default flip, or keep the default off until packed-io can round-trip parts with statistics.
Final Verdict

Changes 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

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.00% 79.10% +0.10%

Changed lines: Changed C/C++ lines covered: 26/26 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jul 5, 2026
alexey-milovidov and others added 2 commits July 5, 2026 23:14
…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]>
Comment thread src/Core/SettingsChangesHistory.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 2 query(s) improved out of 35 analysed

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)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 7 improvement 557 71 ×7.8 faster <0.0001 plan_change: This PR enables column statistics on INSERT by default for small tables, giving cost-based join reordering good estimates. Q7's ×7.8 faster delta is a better join order, exactly the intended effect, and confirmed by both tests.
🟢 8 improvement 165 82 ×2.0 faster <0.0001 plan_change: Same mechanism as Q7: fresh dimension-table statistics let the planner pick a cheaper join order, yielding ×2.0 faster here. Large, consistent delta directly attributable to the diff.

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
  • StressHouse run: 71636219-0fd7-42bb-9219-46b312affb9f
  • MIRAI run: f633179a-2187-466c-9fca-026a60b2008f
  • PR check IDs:
    • clickbench_984255_1786581567
    • clickbench_984268_1786581567
    • clickbench_984275_1786581567
    • tpch_adapted_1_official_984620_1786581669
    • tpch_adapted_1_official_984746_1786581683
    • tpch_adapted_1_official_984902_1786581798

alexey-milovidov and others added 10 commits July 6, 2026 03:52
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]>
@egor-click

Copy link
Copy Markdown
Contributor

@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 idea

The main issue seems to be that this PR makes statistics available by default on small MergeTree tables, and then
latency-sensitive optimizer passes synchronously load those stats during planning.

The narrow prototype I tested avoids those cold stats loads in the two places that showed up in the affected regressions:

  1. Join optimization: avoid loading table statistics for two-relation join graphs.

    • For a flattened join graph with only two base relations, there is no multiway join-order search benefit.
    • Multi-relation join graphs still keep the current statistics-based behavior.
    • The fallback path still uses existing range/index estimates.
  2. PREWHERE optimization: avoid loading table statistics only to reorder PREWHERE conditions.

    • MergeTreeWhereOptimizer can still use cheap column-size heuristics.
    • This removes another cold stats-load path hit by join_convert_outer_to_inner/1.

I would not claim this exact patch has zero possible downside. The risk is bounded but non-zero:

  • For two-table joins, stats might still occasionally help choose a better swapped side / relation estimate for skewed or highly selective cases.
  • For PREWHERE condition ordering, stats can theoretically choose a better condition order than column-size heuristics when stats are already warm/cached.

This prototype validates that avoiding synchronous cold loads fixes the measured PR regressions.

Targeted local validation

Local ARM validation, simulating this PR behavior with materialize_statistics_on_insert=1:

query unpatched patched prototype change
join_convert_outer_to_inner/1 53.23 ms 4.94 ms -90.72%
join_filter_pushdown_equivalent_sets/2 36.96 ms 4.13 ms -88.83%
top_k_through_join/0 28.18 ms 15.19 ms -46.12%
join_filter_pushdown/0 20.90 ms 8.21 ms -60.70%
right_full_hash_join/1 162.83 ms 141.07 ms -13.36%
parallel_index/2 5.91 ms 5.73 ms -3.06%

Profile-event probes confirmed the mechanism:

  • join_convert_outer_to_inner/1: LoadedStatisticsMicroseconds about 44 ms -> 0
  • join_filter_pushdown_equivalent_sets/2: LoadedStatisticsMicroseconds about 31.6 ms -> 0

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 patch
diff --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")};

@groeneai

groeneai commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator

@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 optimizeJoin "estimate statistics" trace, which fires exactly when estimateReadRowsCount takes the use_statistics branch) on two synthetic joins over 5M-row MergeTree tables with statistics materialized on insert.

query baseline (PR head) prototype
2-relation join 2 stats loads 0
3-relation join 3 stats loads 3

So the relation_headers_for_statistics_policy.size() > 2 gate does what you intend: it removes the cold stats loads for 2-relation graphs and leaves 3+-relation graphs untouched.

Regressed tests will not degrade. All six (join_convert_outer_to_inner, join_filter_pushdown_equivalent_sets, join_filter_pushdown, top_k_through_join, right_full_hash_join, parallel_index) are two-relation joins or single-table-plus-subquery, i.e. exactly the graphs the gate now skips. That matches your measured -90%/-88%/etc.

PR performance improvement preserved. TPC-H Q5 and Q8 (the >200s to 0.5s cases) are 6-table join graphs, so size() > 2 is true and they keep loading statistics. The gate only turns stats off where there is no multiway reorder benefit, which is where the regressions came from, and leaves them on where the big wins come from.

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 (MergeTreeWhereOptimizer already treats a null estimator as "statistics off", so this is a supported path, not a new one).

Two honest caveats, both bounded and both matching your own notes:

  1. The gate is computed after query_graph_size_limit is clamped to 2 for swap-only strictness (LEFT/RIGHT/FULL). So for a swap-only two-table join, the build-side swap decision now uses range/index estimates instead of NDV. For skewed or highly selective two-table joins that is a real (small) risk of a worse swap. In practice range/index estimates are usually enough for a two-way swap, and the tests confirm no regression, but it is the one place stats could have helped.

  2. Minor: collectJoinGraphRelationHeadersForJoin is now traversed twice per join (once for the policy vector, once inside joinGraphHasOverlappingColumnNames). It is only header collection, no stats load, so cost is negligible, but the vector could be collected once and reused.

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 SettingsChangesHistory previous_value and the multi-part INSERT size gate, are separate from this prototype and are for the PR author to address.)

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Updating the branch to fix the 03532_window_function_and_null_source_max_threads test, which was broken today in master.

Comment thread src/Core/Settings.cpp
)", 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"(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

@egor-click

Copy link
Copy Markdown
Contributor

@alexey-milovidov wdyt about the proposed patch?

@alexey-milovidov

Copy link
Copy Markdown
Member Author

@egor-click, both sounds ok, but are they necessary? There are two questions:

  • why does loading of statistics take a lot of time - shouldn't it be a tiny data structure?
  • why they are not already loaded after INSERT, which created them?

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator

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 arrayFold arms take about 5.2s, so an 8000ms bound would sit above the unfixed path and the arms would report stopped promptly either way. The real defect is the fixture. arrayFold checks for cancellation in its per-slice fold loop, while the selector loop and scatter ahead of it are O(total array elements) and effectively uninterruptible, so spreading 1.8e8 elements over 60000 rows made the arm pay about 2.9s of prologue before the deadline could be observed. That left a 1.78x margin against the bound where every other arm of the test has 8x to 52x.

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.

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator

Update on item 2: #114039 is closed. @ PedroTadim closed it and is removing the test instead, in #114061, which deletes 04752_persisted_expression_cancellation along with six sibling cancellation tests. So item 2 resolves by deletion rather than by the fixture change I described above. The disposition is his and I am not contesting it.

Item 1 is unaffected: #113925 is still open and awaiting review.

@groeneai groeneai mentioned this pull request Aug 9, 2026
1 task done
# 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 = ''"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

🕵 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
alexey-milovidov added this pull request to the merge queue Aug 13, 2026
Merged via the queue into master with commit 45cb837 Aug 13, 2026
180 checks passed
@alexey-milovidov
alexey-milovidov deleted the stats-on-insert-size-threshold branch August 13, 2026 04:07
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 13, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@alexey-milovidov @rschu1ze @egor-click — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

pull Bot pushed a commit to erickirt/ClickHouse that referenced this pull request Sep 26, 2026
…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]>
opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Nov 8, 2026
`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]>
nihalzp pushed a commit to nihalzp/ClickHouse that referenced this pull request Nov 16, 2026
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]>
eoger-ant pushed a commit to eoger-ant/ClickHouse that referenced this pull request Nov 16, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants