Skip to content

fix: Include read columns when updating MergeTreeBlockSizePredictor - #122919

Merged
fm4v merged 12 commits into
ClickHouse:masterfrom
jgsogo:fix/107596-prewhere-regression
Nov 14, 2026
Merged

fm4v merged 12 commits into
ClickHouse:masterfrom
jgsogo:fix/107596-prewhere-regression

Conversation

@jgsogo

@jgsogo jgsogo commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

After the optimization introduced in #89982, the columns that were only used in the PREWHERE no longer appear in the sample Block used to recompute the predicted size of the following blocks to read; only the columns that were part of the output port of the pipeline step.

As a consequence, when the columns to read were large compared to the output columns, the computed predicted size (only output columns) was very small compared to the actual memory needed to read the input rows. The next read task will include too many rows, and it can crash with an OOM error.

In this pull request, I'm fetching all the columns used by all the stages of the reader and will keep considering them when updating the MergeTreeBlockSizePredictor. We don't have, though, the actual size of these columns, so we keep using the estimation we used in the first iteration. We also don't have information about other materialized columns that could require additional memory ( ... WHERE lower(huge_str_column) != ''), but IMHO, this fix allows for future extensions in those directions.

Note.- This is my first PR here; I'll be very happy to learn about the process and include any feedback. I should probably add some tests (maybe regression tests), so any help in that direction will be more than welcome. Thanks for the amazing product (and the patience with this PR).


Closes: #107596

Changelog category:

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

Fix computation of the predicted size for MergeTree readers involving PREWHERE clause. The columns that are read just to execute the prewhere clause are also considered for the block size, preventing out-of-memory errors.


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

Version info

  • Merged into: 26.11.1.2291-master (included in 26.11 and later)
  • Backported to: 26.10.5.7

@CLAassistant

CLAassistant commented Sep 29, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@clickhouse-gh clickhouse-gh Bot added comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. external Author is not a member of the ClickHouse organization labels Sep 29, 2026
@fm4v fm4v added the can be tested Allows running workflows for external contributors label Oct 15, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [faa73ee]

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 IGNORED

AI Review

Summary

PR #122919, reviewed at faa73eed0a985f2c968e3718b060442df5b1553e, keeps columns used only by PREWHERE in the MergeTreeBlockSizePredictor estimate after output-column pruning, preventing oversized subsequent reads. First-update initialization from actual result columns remains intact, addressing the previous finding about generated columns. No remaining actionable findings.

Missing context / blind spots
  • ⚠️ Completed targeted-test and performance results for the latest commit were unavailable during review, and this checkout has no local build for independent execution. The unchanged regression test passed all 50 targeted ASan/UBSan runs and bugfix validation on d5bc17863adae170e934707dd34edfd94b6aa38e. Current-head CI should confirm the latest allocation optimization.
Final Verdict

✅ Approve. No code changes requested; complete current-head CI before merging.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 15, 2026
fm4v added 2 commits November 5, 2026 01:02
…add a test

Address the review: dropping the first-update reinitialization in `update` meant
that `DEFAULT` and `MATERIALIZED` columns that are not stored in the part, and all
columns of compact parts (which have no per-column sizes), never got a real
estimation of bytes per row. Restore the reinitialization from the result block
and merge the columns remembered in the constructor into it, so columns read only
by `PREWHERE` steps keep the estimation obtained from the part instead of being
dropped from the estimate. In the per-block update, keep the current estimation
of such columns instead of indexing the result block with a name it does not have.

Remove the `getReadSampleBlock` plumbing: the predictor is constructed with all
columns read from the part (including `PREWHERE` columns), so passing the read
header to every `update` only added a `Block` construction per read call without
changing the result.

Add a stateless test: on master `sum(k) ... PREWHERE s LIKE '%a%'` reads
8192-row blocks of 2 KB strings with `preferred_block_size_bytes = 200000`;
with the fix the blocks stay within one 256-row granule.

Closes: ClickHouse#107596
@fm4v

fm4v commented Nov 5, 2026

Copy link
Copy Markdown
Member

I pushed two commits on top of this branch (maintainerCanModify is on), see 31a8328 and the merge of master d5bc178.

What changed relative to the previous revision:

  • The first-update reinitialization in MergeTreeBlockSizePredictor::update is kept, as requested in the review: it rebuilds the estimate from the actual result columns, so DEFAULT / MATERIALIZED columns that are not stored in the part and all columns of compact parts (which have no per-column sizes) still learn their real size. The columns remembered in the constructor are merged into that block, so columns read only by PREWHERE keep the estimation taken from the part instead of dropping out of the estimate. A column absent from the result block keeps its current bytes_per_row in the per-block loop.
  • The getReadSampleBlock plumbing through MergeTreeReadersChain and MergeTreeReadTask is removed: the predictor is already constructed with all columns of all PREWHERE steps, so the read header added no information while costing a Block construction per read call.
  • Added 05321_block_size_predictor_prewhere_only_columns.sql. On the current master binary the three sum(...) ... PREWHERE s LIKE '%a%' queries read 8192-row blocks of 2 KB strings with preferred_block_size_bytes = 200000; with the fix the estimate of s (about 2000 bytes per row) keeps the blocks within one 256-row granule.

Note for reviewers: on the current master the pure count() shape from the issue no longer overshoots (the reading step has no result columns, so update is not called and the constructor estimate survives), but any query that keeps a narrow column after the PREWHERE still does. Columns read only by PREWHERE from compact parts still count as 0 bytes because compact parts store no per-column sizes; such parts are bounded by min_bytes_for_wide_part.

Related: #126041 (same root cause, overlapping fix).

@clickhouse-gh

clickhouse-gh Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing faa73eed0 with master 8a8d2e477 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

14 translation units recompiled, 90 s compile time in total, 14 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×0.92 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -9.0 s (-9%) in total before that adjustment.

Job report

… without copying the sample block

The previous revision remembered the sample block of the part in a `Block` member of the predictor and merged it into the result block on the first `update`. The predictor is created once per part and copied once per read task, so every part paid for a `NameSet`, a `Block` with its name index, a `cloneWithColumns` and one `insertUnique` per column. In the performance test `merge_tree_many_partitions_2` (3000 parts of 26 `UInt64` columns) this added 13.5 MB of memory (15.2 MB to 28.8 MB), 21 ms to `QueryPipelineBuildMicroseconds` (97 ms to 118 ms) and 15% to the query time (177 ms to 204 ms).

Now the constructor stores nothing but the names and value sizes of the fixed-size columns of the part (`fixed_columns_from_part`, one small vector), and the estimates of the variable-size columns are already in `dynamic_columns_infos`. On the first `update`, `initialize` keeps the entries whose column is absent from the result block, which are exactly the columns read only by `PREWHERE`, and rebuilds the rest from the actual columns as before.

The estimate for the columns read only by `PREWHERE` is unchanged, so the fix for ClickHouse#107596 and the test `05321_block_size_predictor_prewhere_only_columns` are not affected.

Performance report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122919&sha=d5bc17863adae170e934707dd34edfd94b6aa38e&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%203%2F6%29
Pull request: ClickHouse#122919
@fm4v

fm4v commented Nov 9, 2026

Copy link
Copy Markdown
Member

Analysis of the three performance comparison failures on d5bc17863ad, and one more commit (faa73ee) on the branch.

merge_tree_many_partitions_2 #0 (+15%, 177 ms to 204 ms): real, caused by the previous revision, fixed in faa73ee. The query reads 3000 one-row parts with 26 UInt64 columns. The perf run metrics show the cost is per part, not per row: memory_usage 15.2 MB to 28.8 MB (+89%), QueryPipelineBuildMicroseconds 97 ms to 118 ms (the read pool creates one predictor per part while the pipeline is built), SoftPageFaults 3410 to 6029. The previous revision kept a Block with all columns of the part inside every predictor (one per part plus one copy per read task), so each part paid for a NameSet, a Block with its name index, a cloneWithColumns and one insertUnique per column, about 4.5 KB and a few microseconds per part. With the CI binaries on the same data locally, memory_usage of this query is 14.0 MiB on master and 28.3 MiB on d5bc17863ad, matching the perf run. The new commit stores only the names and value sizes of the fixed-size columns of the part (one small vector); the estimates of the variable-size columns are already in dynamic_columns_infos. On the first update, initialize keeps the entries whose column is absent from the result block (exactly the columns read only by PREWHERE) and rebuilds the rest from the actual columns as before. The estimate for PREWHERE-only columns is unchanged, so the fix for #107596 and the test 05321_block_size_predictor_prewhere_only_columns are not affected.

and_compare_chain_derived #0 (+24%, 101 ms to 125 ms): the intended effect of the fix, not an over-estimate. The query is SELECT count() FROM t_chain_derived WHERE s1 < s2 AND s2 < s3 AND s3 < s4 AND s4 < repeat('p', 100) || 'z' over 10M rows of four ~105-byte strings in one part. All four conditions land in a single PREWHERE step, so all four string columns are alive at once while a block is read: about 456 bytes per row, which with the default preferred_block_size_bytes = 1000000 allows about 2200 rows, rounded up to one granule of 8192 rows. On master the predictor forgets these columns after the first block (the result block is empty) and reads 65536-row blocks: measured with the CI binaries, master reads 154 blocks (1 x 8192, 152 x 65536, 1 x 30336), this PR reads 1221 blocks of 8192 rows. The perf run shows the trade: memory_usage 385 MB to 66 MB (-83%), SoftPageFaults 85139 to 22008, SystemTimeMicroseconds 159 ms to 56 ms, but FunctionExecute 2076 to 11229 and UserTimeMicroseconds 929 ms to 1308 ms, so 8x more per-block overhead for the filter chain costs more than the smaller allocations save. A more accurate estimate cannot recover the old speed: even if only one of the four strings were counted (114 bytes per row), the quota would allow 8700 rows, still one granule. Getting back to 65536-row blocks requires ignoring the PREWHERE-only columns, which is the bug being fixed. This is also the behaviour before #89982 (merged 2026-02-17), when these columns were still in the reading step header and were measured by update; the perf test was added on 2026-07-29, so its baseline includes the oversized blocks. The same slowdown of this query is reported on #126041, an independent implementation of the same fix (88 ms to 108 ms in both of its runs), and on no other PR or master run in the last 30 days (1222 master runs, p50 90 ms, max 148 ms).

formats_columns_nullable #20 (+39%, 10.6 ms to 14.7 ms): unrelated noise. The query is SELECT avg(col_int32) FROM table_ORC_with_nullable_columns, an ORC File table, so the MergeTree block size predictor is not involved. The same query was flagged slower on master on 2026-11-02 (30609f3ee6) and on PRs #128998, #128445 and #129547 in the same week, and it passed on the earlier revision b9ac44d7592 of this PR.

Expected on the next run: merge_tree_many_partitions_2 #0 back to the master time and memory, and_compare_chain_derived #0 still about +20% with 83% less memory. If the maintainers prefer the test not to flag this, the test query could set preferred_block_size_bytes explicitly, but I have not touched the test.

@fm4v

fm4v commented Nov 13, 2026

Copy link
Copy Markdown
Member

@groeneai check if perf regressions are related

@groeneai

Copy link
Copy Markdown
Collaborator

I checked every query the performance comparison flagged on faa73ee (arm, 1 slower, 6 faster, 1 unstable). All of them except the unstable one are caused by the PR, and only through the block size.

  • and_compare_chain_derived #0 (+20.7%, 88 to 107 ms, memory -83%): caused by the PR and intended. With max_threads = 1 the PR reads 1221 blocks of 8192 rows and master reads 154 blocks of 65536 rows. 25.12 reads 1221 x 8192 like the PR, and 26.3 reads 154 x 65536 like master, so the PR restores the behaviour from before Optimize remove unused column read from merge tree #89982. Measured on x86 with the two CI builds (Xeon 6975P-C, 12 pinned CPUs, max_threads = 12, warm, median of 15 runs):

    • master 133 ms, the PR 81 ms
    • master with max_block_size = 8192: 87 ms
    • the PR with preferred_block_size_bytes = 0: 132 ms

    FunctionExecute is the same for the PR and for master with max_block_size = 8192 (11229). So on x86 the change itself costs nothing and the whole difference is the block size: smaller blocks are faster here and slower on the arm runner. #3, the join variant (+12% on arm, not flagged), behaves the same way: 142 ms on master, 118 ms with the PR, 113 ms on master with max_block_size = 8192.

  • text_index_like #2 to #7 (18% to 34% faster, memory -74% to -93%): caused by the PR, same mechanism. Peak memory of #2 is 18.6 MiB on master and 4.6 MiB with the PR, the same as master with max_block_size = 8192.

  • system_clusters_replicated_databases #0 (unstable, -2.7%): unrelated, it reads system.clusters.

  • merge_tree_many_partitions_2 #0 is no longer flagged (user time -1%), but its memory is still +28% on this run (15.2 to 19.5 MB). Locally, on 3000 one-row parts, the difference is +4.5 MiB with the test's 26 UInt64 columns, +3.8 MiB with 52 columns and none with 2 columns.

Apart from that remaining memory, nothing here can be avoided while keeping the fix: getting #0 back to 65536-row blocks on arm would mean leaving the PREWHERE-only columns out of the estimate, which is the bug itself.

@fm4v
fm4v added this pull request to the merge queue Nov 14, 2026
Merged via the queue into ClickHouse:master with commit 5157e6d Nov 14, 2026
366 of 369 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 14, 2026
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 14, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 14, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 14, 2026
Backport #122919 to 26.10: fix: Include read columns when updating `MergeTreeBlockSizePredictor`
valerypetrov pushed a commit to valerypetrov/ClickHouse that referenced this pull request Nov 16, 2026
…shorter than a bucket

The selector of a table with buckets of samples wrapped every read in
`WHERE notEmpty(samples)` over `timeSeriesSliceSortedArray(samples, a, b)`.
Filter push-down moves that condition into PREWHERE, which reads the raw
`samples`, computes the slice and drops the raw column, so the raw column
is PREWHERE-only. Since ClickHouse#122919 `MergeTreeBlockSizePredictor` counts such a
column at its part estimate on top of the measured slice copy: for a long
window (the slice is the whole array) bytes per row double, and with
granules under 512 KiB a block holds about one granule instead of two or
three. Whole-metric selectors then process about twice as many blocks
(`promql_selector_id_range_row_cost` #0/ClickHouse#1 1.3x slower with 262144-byte
granules, ClickHouse#131678).

The filter is a no-op unless the range is shorter than a bucket: every
sample of a row lies in [bucket, bucket + step), `min_time`/`max_time` are
the smallest/largest of them, and the inner query keeps a row only if
`max_time >= a AND min_time <= b`. If `min_time >= a` the sample at
`min_time` is in the range, if `max_time <= b` the sample at `max_time` is,
so an empty slice needs `min_time < a AND b < max_time`, i.e.
`b - a < max_time - min_time < step`. With a bound absent the same holds for
the other bound. So the filter is now emitted only when both bounds are set
and `b - a < step` in the units of the table being read (the samples table
or the recent samples table, each with its own step). The difference is
computed in Int128: the bounds of a DateTime64 table can be anywhere in
[INT64_MIN, INT64_MAX]. For long windows nothing on `samples` goes to
PREWHERE, the raw column is read by the main step and measured once, and
the slice is computed after it.

The bucket step at the table scale is moved into `getBucketStep`, shared
with `makeBucketedSamplesTimeRangeConditions`.

Measured (release build, master vs this change concurrently on identical
parts, 2 x 25 interleaved runs, max_threads = 4): row_cost #0 0.81/0.76 at
262144, 0.86/0.81 at 131072, 0.93/0.84 at 524288; ClickHouse#1 0.79/0.73,
0.88/0.83, 0.99/0.91; promql_selector_old_short_window 0.94-0.97. Results
identical.

Edge: a row written directly with `min_time`/`max_time` looser than its
samples (against the documented contract) can now be returned as an empty
array by `timeSeriesSelector(..., 'samples')` for a long range. PromQL drops
series whose merged array is empty, as it does for rows emptied by the
stale-marker filter.

Tests: 05770_time_series_selector_empty_slice_filter checks both sides of the
bucket boundary and the plan shape (no-parallel-replicas: without a local
plan the initiator's EXPLAIN does not show the replicas' filters). New perf
test promql_selector_small_granules: the row_cost shape at 131072-byte
granules, the default of the recent samples table.

Related: ClickHouse#131678
Related: ClickHouse#122919

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

can be tested Allows running workflows for external contributors comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. external Author is not a member of the ClickHouse organization pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.10-must-backport

Projects

None yet

6 participants