Skip to content

Count columns read only by PREWHERE in the MergeTree block size estimate - #126041

Closed
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:fix-107596-block-size-predictor-prewhere
Closed

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:fix-107596-block-size-predictor-prewhere

Conversation

@groeneai

@groeneai groeneai commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #107596
Related: #122919

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

preferred_block_size_bytes is respected again for columns that are read only by PREWHERE (including conditions moved there automatically), which brings the peak memory of such queries back to the 26.1 level. Closes #107596.

Description

On 26.3.42.3, a query whose PREWHERE reads a wide column that it does not output ignores preferred_block_size_bytes after the first block: with ~1000-byte rows and preferred_block_size_bytes = 100000 it reads 9872-row blocks instead of ~128. This is the 7x peak memory in #107596.

MergeTreeBlockSizePredictor is created with every column the reader reads, but on the first update() it re-initializes itself from the result block only. Since #89982 (query_plan_remove_unused_columns) columns used only by PREWHERE are not in the result block, so after the first block their bytes per row drop out of the estimate and blocks grow to max_block_size.

The fix keeps the constructor's columns in that re-initialization and keeps the current estimate of a column that is absent from the result block. 2 files, +18/-2. Such queries go back to their 26.1 block sizes; the per-block cost of the estimate is unchanged. Compact parts store no per-column sizes, so there these columns still count as 0 bytes; such a part is smaller than min_bytes_for_wide_part (10 MiB by default), which bounds the block.

Validation (debug build, the issue's schema and generator, max_threads = 6, peak memory_usage): master 735.8 MiB at defaults vs 45.2 MiB with query_plan_remove_unused_columns = 0; with this change 45.1 MiB at defaults. The new test fails on master (both queries) and passes 50/50 with randomized settings, and in the s3, DatabaseReplicated and parallel replicas modes.

#122919 addresses the same mechanism and also brings the reproducer to 45.1 MiB. This PR is a smaller variant (no new MergeTreeReadersChain API, no Block built per read) and adds a regression test.


Workflow [PR]
Sync PR [sync-upstream/pr/126041]

`MergeTreeBlockSizePredictor` is created with every column the reader
reads (result columns plus the columns of every PREWHERE step), but on
the first `update()` of a task it re-initialized itself from the result
block only, to re-estimate DEFAULT/MATERIALIZED columns the part does not
hold. Since ClickHouse#89982 (`query_plan_remove_unused_columns`) columns used only
by PREWHERE are not in the result block, so after the first block their
bytes per row dropped out of the estimate, `estimateNumRows` saturated
and every later block was `max_block_size` rows of the wide columns.
`preferred_block_size_bytes` was effectively ignored, which is the ~7x
peak memory reported in ClickHouse#107596 (735.8 MiB vs 45.2 MiB with
`query_plan_remove_unused_columns = 0` on the issue's reproducer).

Keep the constructor's sample block and merge it into the
re-initialization block, and keep the current estimate of a dynamic
column that is absent from the result block. `block_size_bytes` still
counts only the columns that are in the block. With the change the
reproducer peaks at 45.1 MiB at default settings.

Closes ClickHouse#107596

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 findings) plus my own review (1 finding).

# Sev Finding Verdict Evidence / action
1 ❌ A PREWHERE-only column the part does not hold under its read name (pending RENAME COLUMN, DEFAULT not yet written) still gets no estimate AGREE on the mechanism, not blocking Same as master for those columns. A pending rename needs alter_sync = 0 or a held mutation (StorageMergeTree.cpp:1038); a missing DEFAULT column's source columns are read by the same step and counted. Covering them needs measured per-step sizes, a second mechanism.
2 ⚠️ max(blockSize()) <= 1024 is looser than the fixed value (128) DISAGREE A column is either counted at its part average or not at all: not counted gives blocks of at least 8000 rows (randomized max_block_size is 8000..100000), a compressed-size source gives ~3800. Nothing lands in 129..1024. The test fails on master in both queries.
3 💡 Compact parts store no per-column sizes, so these columns still count as 0 bytes there AGREE, noted Stated in the description; bounded by min_bytes_for_wide_part (10 MiB by default), one part per read task.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-9:20261015-141700

@clickhouse-gh

clickhouse-gh Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7a60373]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 1/6) FAIL Performance dashboard
and_compare_chain_derived #0 FAIL dashboard
uniq #75 unstable query history
Performance Comparison (arm_release, master_head, 6/6) FAIL Performance dashboard
tpch-join_algorithm-partial_merge #17 FAIL dashboard
insert_statistics_countmin #2 unstable query history
window_partitions #15 unstable query history
Build profile diff ERROR

AI Review

Summary

The PR retains per-part size estimates for columns used only by PREWHERE, while preserving first-update learning for columns present in the result. No actionable findings remain after reviewing the current diff, callers, tests, and prior discussion. The regression test passes in Fast test for commit 7a603735c301071c658706ab4b92c8d17fca7c31; the overall CI workflow is still running. No local build or tests were run.

Final Verdict

✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 15, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @tiandiwonder @Algunenano, could you review this? On the first update(), MergeTreeBlockSizePredictor re-initializes from the result block only, so since #89982 columns read only by PREWHERE drop out of the estimate and blocks grow to max_block_size; this keeps the constructor's columns in that re-initialization (+18/-2, with a test).

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Oct 15, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 15, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b774a99

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) / 04034_autopr_dataflow_cache_reuse_between_different_queries flaky, not from this PR (it changes the MergeTree block size estimate, not the automatic parallel replicas decision): pr_used 1 -> 0 for queries 1 and 2, 43 of 43 reruns passed; it failed on 7 other PRs and on master in the last 30 days #125544 (mine, open)
Mergeable Check, PR praktika rollups of the row above #125544 (mine, open)

CIDB has no other FAIL or ERROR row from the finished run on this head.

Session id: cron:our-pr-ci-monitor:20261015-230015

@fm4v

fm4v commented Oct 28, 2026

Copy link
Copy Markdown
Member

Performance Comparison (arm_release, 1/6 and 6/6) on 7a60373: both slowdowns are real and caused by this PR, and they are the intended trade-off of the fix rather than a defect.

Query client_time peak memory_usage FunctionExecute
and_compare_chain_derived #0 (SELECT count() ... WHERE s1 < s2 AND s2 < s3 AND ..., four ~105-byte strings read only by PREWHERE) 90.8 ms -> 107.0 ms (+17.8%, confirmed after restart +22.6%) 465 MiB -> 105 MiB (-77%) 2076 -> 11229 (5.4x)
tpch-join_algorithm-partial_merge #17 (TPC-H Q19, lineitem filter columns in PREWHERE) 226.4 ms -> 262.3 ms (+15.8%, confirmed +14.5%) 41.7 MiB -> 25.6 MiB (-39%) 34703 -> 98000 (2.8x)

The metrics (from all-query-metrics.tsv) show exactly the mechanism of the fix: the PREWHERE-only columns are counted again, preferred_block_size_bytes (1 MB) caps the block at about one granule instead of max_block_size, so the same rows go through several times more blocks (more FunctionExecute, more per-block overhead) while peak memory drops 2-4x. This is the 26.1 behaviour, so the master baseline of these queries was recorded with the bug. The previous run on b774a99 showed the same tpch partial_merge slowdown, so it is reproducible. No other query is slower.

So the two red performance shards should be accepted by the reviewer as the cost of honouring preferred_block_size_bytes, not fixed in this PR. CH Inc sync failures are unrelated: 05449_radix_uniq_exact_spill_bounded_sets fails across hundreds of private PRs and master (raise of its limit in #127837), and the ASan stack-use-after-scope in LoadStatistics at server startup is #127895 (fix #127911); failed private jobs were rerun. Build profile diff is the LogClusterNotReady infra failure (fix #126200).

@fm4v

fm4v commented Nov 14, 2026

Copy link
Copy Markdown
Member

superseded by #122919

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Performance: ~7x peak memory for aggregate queries with a PREWHERE filter over wide String columns since 26.2

3 participants