Skip to content

Group PREWHERE read steps by exact columns and rewrite m['key'] to a key subcolumn only for bucketed Map - #124553

Merged
Avogar merged 13 commits into
ClickHouse:masterfrom
groeneai:fix-124535-prewhere-subcolumn-read-steps
Nov 5, 2026
Merged

Avogar merged 13 commits into
ClickHouse:masterfrom
groeneai:fix-124535-prewhere-subcolumn-read-steps

Conversation

@groeneai

@groeneai groeneai commented Oct 8, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #124535
Related: #107988
Related: #107912
Related: #111954
Related: #114150

Since #107988, MergeTreeWhereOptimizer and tryBuildPrewhereSteps group PREWHERE conditions by the storage column they read instead of by the exact columns. The reason was the rewrite of m['key'] to the Map key subcolumn m.key_<key>: with basic serialization a key subcolumn reads the whole Map, so N keys in N read steps read the Map N times (#107912). The same grouping merges a cheap subcolumn condition with an expensive condition on the rest of the column: in #124535, j.kind = 'b' AND length(toString(j)) > 10 reads and serializes the whole j for every row.

This PR removes the cause instead of teaching the PREWHERE code about Map:

  • m['key'] is rewritten to m.key_<key> only when the table uses bucketed Map serialization. The new IStorage::hasBucketedMapSerialization is true for a MergeTree table if either map_serialization_version setting is with_buckets; Merge, MaterializedView, Buffer, Alias, MaterializedPostgreSQL and proxies answer for the tables they read, and Merge requires all of them. The check is in storageAllowsTransformer, so both passes of FunctionToSubcolumnsPass agree. Explicitly written key subcolumns still work for any serialization.
  • MergeTreeWhereOptimizer and tryBuildPrewhereSteps group conditions by the exact columns they read again. A condition on a subcolumn and a condition on the whole column or on another subcolumn of it get separate steps, while conditions on virtual columns of one index still share a step. With basic serialization all m['kN'] conditions read m and share one step. The may_throw split from Do not evaluate a potentially throwing PREWHERE condition ahead of its guard #111954 and the read-ahead of a split run are unchanged, and tryBuildPrewhereSteps no longer needs ColumnsDescription.

Keys of a bucketed Map that land in the same bucket are read once per step, as before #107988. Avoiding repeated reads of physical streams shared between steps is a general reader improvement and is left for a separate change.

An earlier revision of this PR kept the storage-column grouping and folded Map key subcolumns into their Map inside tryBuildPrewhereSteps, which made generic PREWHERE code depend on Map serialization details and was wrong for with_buckets.

Expected performance comparison changes: tables with the default basic Map serialization read the whole Map for m['key'] again, so get_map_value, map_lowcardinality_key_lookup and serialization_pool_lookup may move. map_bucketed_serialization.xml now actually uses with_buckets, which its comment already claimed.

Tests: 05340_map_element_to_subcolumn_bucketed_only covers the rewrite gate, including Merge, MaterializedView and Buffer. 05339_prewhere_subcolumn_read_steps checks that a condition on a cheap subcolumn keeps the rest of the column unread for JSON, Tuple and Map, including a with_buckets key next to the whole Map; its payloads are random, so that the on-disk sizes by which WHERE conditions are ordered reflect the cost of reading. Tests that assert the rewrite now pin both map serialization settings, which clickhouse-test randomizes.

Changelog category (leave one):

  • Performance Improvement

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

A PREWHERE condition on a subcolumn (for example j.kind = 'b' on a JSON column) is again evaluated in its own read step, so the rest of the column is read only for the rows that pass it. m['key'] is now rewritten to the Map key subcolumn only for tables with with_buckets Map serialization, where it reads a single bucket; with basic serialization the whole Map is read once, as before 26.3. Closes #124535.


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

Version info

  • Merged into: 26.11.1.1442-master (included in 26.11 and later)

groeneai and others added 2 commits October 8, 2026 05:07
…n its subcolumn

Since ClickHouse#107988, tryBuildPrewhereSteps groups adjacent PREWHERE conditions
by the storage column they read, so that the keys of one Map, each of
which reads the whole Map, share one read step (ClickHouse#107912). The resolution
was type-blind: `j.kind` and `j`, two JSON paths, a Tuple element and the
whole Tuple, `m.size0` and `m.key_k1`, and keys of two Maps nested in one
Tuple all resolved to one storage column. A cheap subcolumn condition was
then merged with an expensive condition on the rest of the column, which
read the whole column for every row. On master a may-throw `toString(j)`
gets its own step (ClickHouse#111954), but its read-ahead, keyed on the same
comparison, reads `j` in step 0 anyway.

Key each input by the storage column and the substreams cache key of its
subcolumn path instead. A Map key subcolumn drops its trailing
MapKeyValue, so it keys as the Map that owns it (`(m, "")` at the top
level, as before; `(c, "%2Eleft")` for a Map inside a Tuple, so two
sibling Maps no longer share a step). The pair is used rather than a
concatenated string because the path rendering escapes tuple dots.

MergeTreeWhereOptimizer keeps grouping by storage column: that keeps a
guard ahead of a throwing condition on the same column. So with the
expensive condition written first the order is still kept.

Closes ClickHouse#124535

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the clause narrating how the new grouping identity splits steps from the resolveStorageColumnName comment.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Oct 8, 2026
@groeneai

groeneai commented Oct 8, 2026

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

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

# Sev Finding Verdict Evidence / action
1 ❌ Compact parts without per-substream marks deserialize the whole parent column once per step DISAGREE (mechanism true, not a blocker) Off the default path: write_marks_for_substreams_in_compact_parts is true since 25.8, so only never-merged older compact parts or an explicit = 0 reach it; bounded by compact part size, and it is the step layout before #107988. Not changed here.
2 💡 SET enable_analyzer = 1 in the test pins nothing on master noted not blocking
3 💡 The Map key comment describes basic serialization; with_buckets reads one bucket noted grouping unchanged from master either way
4 💡 Expensive condition written first still reads the whole column noted MergeTreeWhereOptimizer keeps the written order inside its group (guard before a throwing condition); disclosed in the description

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

Session id: cron:clickhouse-review-slot-8:20261008-051100

@groeneai

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 05339_prewhere_subcolumn_read_steps prints 0 on all 6 lines without the change (randomization off and on); the reporter's script reads 400.73 MiB instead of 3.43 MiB.
b Root cause explained? #107988 groups adjacent PREWHERE conditions by storage column name, so a cheap subcolumn condition and a condition on the rest of the same column share one read step, and the whole column is read for every row.
c Fix matches root cause? Yes. Only the grouping identity changes: storage column plus the subcolumn's substreams path, where a Map key subcolumn keys as its Map.
d Test intent preserved / new tests added? New stateless test (6 cases) and a performance test. Existing 04630, 04631, 04000, 04513, 04811 are unchanged and pass.
e Both directions demonstrated? Yes: the new test fails without the change and passes 50/50 randomized with it. Reverting the identity reddens all 6 lines; dropping the Map-key rule reddens 04631.
f Fix is general across code paths? One grouping decision, also used by the read-ahead. MergeTreeWhereOptimizer is unchanged on purpose: its grouping keeps a guard ahead of a throwing condition on the same column.
g Fix generalizes across inputs (params/datatypes/wrappers)? JSON paths, Tuple elements, Map size, keys and nested Maps are covered; two keys of one Map still share a step. The prewhere and subcolumn suites (505 tests) give the same results as without the change.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or default changes; query results are identical, only which conditions share a read step.
i Invariants and contracts preserved? Steps still compute the single-step result. The may-throw split and the filter materialization before it are untouched; the read-ahead still requires equal column identities.

Session id: cron:clickhouse-impl-slot-4:20261008-035200

@clickhouse-gh

clickhouse-gh Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c6da0df]

Summary: ❌

job_name test_name status info comment
Performance Comparison (amd_release, master_head, 3/6) FAIL Performance dashboard
map_subcolumns_prewhere #5 FAIL dashboard IGNORED
map_subcolumns_prewhere #1 slower query history IGNORED
norm_distance #15 unstable query history IGNORED

AI Review

Summary

This PR separates independently readable subcolumns into distinct PREWHERE steps and disables automatic map-key subcolumn rewrites for storages without bucketed serialization. The new gate breaks previously working constant lookups and introduces a measured CPU regression for compact parts. Two earlier performance/index concerns remain in the current code; the author has explicitly accepted those tradeoffs, so their resolved threads remain closed.

Missing context / blind spots
  • ⚠️ No local PR-head binary was available. The key-type finding combines current-code tracing with read-only queries against public baseline 26.10.3.7; running the supplied query on this head would complete runtime confirmation.
  • ⚠️ Available performance measurements are from 4655ccb4f65a7a7d1d095c25fe11e3dd9a1a9d38 on 2026-10-19; current-head comparisons were pending. The relevant gate remains present and arrayElement is unchanged between that measured revision and this checkout. A focused comparison after a fix would close this gap.
Findings

❌ Blockers

  • Constant map lookups lose supported key types — FunctionToSubcolumnsPass.cpp:1286. With optimize_functions_to_subcolumns = 1, SELECT m[1.5] FROM values('m Map(Float64, String)', map(1.5, 'hit')) returns hit on the public baseline. The new gate leaves arrayElement, whose numeric dispatch excludes Float64 and throws ILLEGAL_TYPE_OF_ARGUMENT; the previous subcolumn extractor supports it. Basic MergeTree maps are affected too. Preserve the rewrite for affected key types or extend the replacement lookup implementation before disabling it.

  • Compact-part map lookups incur a substantial CPU slowdown — FunctionToSubcolumnsPass.cpp:1285. map_subcolumns_prewhere, query 5 regresses from 0.574 s to 1.0072 s on AMD (+75.4%) and 0.2441 s to 0.2911 s on ARM (+19.2%). The preceding run shows +58.9% on AMD, and confidence/history analysis supports a real slowdown. The local release-build comparison independently reports 0.15 s versus 0.25 s with identical compressed bytes read, isolating the replacement arrayElement path. Retain efficient extraction or improve that path before merging.

⚠️ Majors — previously reported, dismissed by the author

  • Shared physical streams are read repeatedly across steps — MergeTreeSplitPrewhereIntoReadSteps.cpp:70. [dismissed by author -- https://github.com/Group PREWHERE read steps by exact columns and rewrite m['key'] to a key subcolumn only for bucketed Map #124553#discussion_r4286969354]. Exact subcolumn-name grouping still creates independent readers for keys sharing one bucket, and for basic parts exposed by mixed serialization settings. The prior reproduction read 26,494,339 versus 6,623,385 compressed bytes for four passing predicates. Explicit basic-map key subcolumns also repeat full-map reads; the author's local measurement reports 0.14 s versus 0.9 s for 16 keys. The author accepts this as a reader-level follow-up; the regression remains real because these supported layouts still deserialize the same physical stream separately for each step. Reuse shared streams across steps or preserve grouping where reads are inseparable.

  • Existing indexes on map-key subcolumns lose implicit lookup matching — FunctionToSubcolumnsPass.cpp:1286. [dismissed by author -- https://github.com/Group PREWHERE read steps by exact columns and rewrite m['key'] to a key subcolumn only for bucketed Map #124553#discussion_r4314211854]. For a basic map indexed by ORDER BY m.key_k, a predicate written as m['k'] = 50000 no longer becomes the indexed subcolumn expression: the prior PR-head reproduction selected 782/782 granules instead of 1/782 and threw INDEX_NOT_USED with force_primary_key = 1. The author correctly identifies an improvement for indexes declared directly on m['k'] and accepts exact expression matching. The concern remains for existing indexes declared on m.key_k, whose previously indexed queries now scan or throw. Preserve expression equivalence during index analysis to support both forms.

Tests
  • ⚠️ Add a focused stateless regression proving constant Float64 key lookups still return their values for a basic Map, including a storage without bucketed serialization support.
  • ⚠️ Existing new read-byte tests reject every row at the first predicate. A nonselective multi-key case is needed to expose shared-stream rereads; the existing compact-part performance query should be rerun after the lookup-path fix.
Final Verdict

Status: ❌ Block. At minimum, preserve previously working map-key lookups and remove the measured compact-part CPU regression, with focused correctness and performance verification. The two author-dismissed concerns above remain recorded without reopening or replying to their threads.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Oct 8, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Oct 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c6da0df35 with master 4944813cc (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

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

Job report

The performance test runner expands every `{name}` in a query template
with `str.format`, so the JSON literal in the fill query was read as a
`{"kind"}` placeholder and the test failed with `KeyError: '"kind"'`
before running any query. Double the braces, as other JSON perf tests do.

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

clickhouse-gh Bot commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 32 queries analysed

All four flagged improvements are downgraded to not_sure. This PR only changes how PREWHERE conditions on subcolumns are grouped into read steps: Map key subcolumns still count as their parent Map, while other JSON and Tuple subcolumns are now told apart by the part of the column they read. No ClickBench or TPC-H query reads Map, JSON or Tuple subcolumns, so for plain columns the change returns the same result as before. The ClickBench Q33 (-8.5%) and Q34 (-10.1%) speedups also show about 11% lower CPU time, but their medians are only slightly below master's current band, and TPC-H Q1 (-20.0%) and Q7 (-25.9%) fall inside or at the edge of that band. That points to differences between the test runs, not to this change. The new prewhere_subcolumn_read_steps performance test is the right place to check the intended effect.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 33 not_sure 1153 1055 -8.5% <0.0001 aggregation: This query reads only plain columns, with no Map, JSON or Tuple subcolumns, so the PR's change to PREWHERE grouping for subcolumns is never reached. The -8.5% is not attributable to this PR.
⚠️ 34 not_sure 1164 1046 -10.1% <0.0001 aggregation: This is a GROUP BY over the plain hits table, which has no subcolumns, so the changed subcolumn grouping logic has nothing to act on. The -10.1% is not attributable to this PR.

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.

tpch_adapted_1_official

⚠️ 2 inconclusive

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 1 not_sure 65 52 -20.0% <0.0001 The lineitem filter uses only scalar columns, so the changed subcolumn handling returns the same read steps as before. The query is noisy on master, and the source median of 52 ms sits inside master's current band.
⚠️ 7 not_sure 81 60 -25.9% <0.0001 This multi-join query filters only on scalar columns, so the PR's change to how Map, JSON and Tuple subcolumns are grouped does not apply. The source median of 60 ms is at the lower edge of master's current band.

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: 45568691-e9cb-4b31-96ed-c96b710b9eb3
  • MIRAI run: 9d017d6a-7aa8-4dd3-819d-8fdddb7acd28
  • PR check IDs:
    • clickbench_341554_1791460752
    • clickbench_341668_1791460794
    • clickbench_341975_1791460891
    • tpch_adapted_1_official_341989_1791460891
    • tpch_adapted_1_official_342003_1791460892
    • tpch_adapted_1_official_342151_1791460894

@Avogar Avogar self-assigned this Oct 8, 2026
Avogar and others added 7 commits October 12, 2026 19:03
…zation

With `basic` serialization, reading the key subcolumn `m.key_<key>` of a
`Map` reads the whole column, so the rewrite gave nothing there, and
ClickHouse#107988 had to group PREWHERE conditions by the storage column to keep
several keys of one `Map` in one read step. That grouping also merged a
cheap subcolumn condition with an expensive condition on the rest of the
same column (ClickHouse#124535). The first version of this pull request worked
around it with a `Map` key special case in `tryBuildPrewhereSteps`,
which put generic PREWHERE code in charge of `Map` serialization details
and was wrong for `with_buckets`.

Gate the rewrite on the new `IStorage::hasBucketedMapSerialization`,
true for a `MergeTree` table if either `map_serialization_version`
setting is `with_buckets`, and forwarded by the storages that pass the
analyzed query to other tables (`Merge` requires all of them). The check
is in `storageAllowsTransformer`, so both passes of
`FunctionToSubcolumnsPass` agree. Explicit key subcolumns still work for
any serialization.

With that, `MergeTreeWhereOptimizer` and `tryBuildPrewhereSteps` group
conditions by their exact column set again, and `tryBuildPrewhereSteps`
no longer needs `ColumnsDescription`. The `may_throw` split and the
read-ahead of a split run stay.

Tests that assert the rewrite now pin both map serialization settings,
which clickhouse-test randomizes. The new `05340` covers the gate, and
`05339` gets the `with_buckets` case from the CI review.

Closes: ClickHouse#124535
Related: ClickHouse#124553

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…re-subcolumn-read-steps

Keep the query condition cache attribution boundary from master in the
PREWHERE step grouping, comparing exact column sets. Drop the
`ColumnsDescription` argument from the new seal-gated
`MergeTreeSelectProcessor` call site.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The test compares the `arrayElement` and key subcolumn forms of
`m['key']`, and the key subcolumn rewrite now applies only to bucketed
Maps.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The new `SubcolumnSupportAnswers::bucketed_map_serialization` field was
missing from the aggregate initialization, which fails the build with
`-Wmissing-field-initializers`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=124553&sha=6a84ce82278446b934bb316be58af106c2f4f53b&name_0=PR&name_1=Fast%20test
PR: ClickHouse#124553

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
In 04631 the interleaved Map conditions read the same column `tags`, so
the last step takes it from the first one instead of reading it again,
and only two of the three steps read rows.

In 05339 the WHERE optimizer may put `m['k1'] != ''` before
`length(m) = 3` based on the column sizes, and the key condition passes
every row. Write that case as PREWHERE, which keeps the written order,
since the test is about separate read steps, not about the order.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=124553&sha=29003da91f5a35f49a43deb35dedd0055448880c&name_0=PR&name_1=Fast%20test
PR: ClickHouse#124553

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…re-subcolumn-read-steps

Keep the index-aware PREWHERE steps from master (`required_indexes`,
`index_read_tasks`), grouping table columns by exact name instead of by
storage column, and drop the `ColumnsDescription` argument from the new
`tryBuildPrewhereSteps` call.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The WHERE optimizer orders the conditions by the on-disk size of their
columns when it has no selectivity estimate. A repeated character
compresses to a few bytes per row, so the expensive subcolumn could be
ordered first and read for every row. Random values make the on-disk
size reflect the cost of reading a column.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=124553&sha=0686a448ce0ba3aa70b6aeecc1aa20a2747a7b17&name_0=PR&name_1=Fast%20test
PR: ClickHouse#124553

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 06aa3e9

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, ParallelReplicas, s3 storage, parallel) / 05345_text_index_prewhere_read_step_order flaky, not from this PR: the known read_order_index_first 0 -> 1 diff in the ParallelReplicas lane, the same diff as on 83 PRs and on master in the last 30 days; 68 of 68 reruns passed #125892 (mine, open)
CH Inc sync - CH Inc sync (private, not actionable by me)
Mergeable Check, PR praktika rollups of the first row #125892 (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-233008

robot-clickhouse-ci-1 added a commit that referenced this pull request Nov 10, 2026
Cherry pick #124553 to 26.9: Group PREWHERE read steps by exact columns and rewrite `m['key']` to a key subcolumn only for bucketed `Map`
robot-clickhouse added a commit that referenced this pull request Nov 10, 2026
…and rewrite `m['key']` to a key subcolumn only for bucketed `Map`
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 10, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 10, 2026
Backport #124553 to 26.8: Group PREWHERE read steps by exact columns and rewrite `m['key']` to a key subcolumn only for bucketed `Map`
clickhouse-gh Bot added a commit that referenced this pull request Nov 10, 2026
Backport #124553 to 26.9: Group PREWHERE read steps by exact columns and rewrite `m['key']` to a key subcolumn only for bucketed `Map`
PedroTadim added a commit that referenced this pull request Nov 11, 2026
Backport #124553 to 26.3: Group PREWHERE read steps by exact columns and rewrite `m['key']` to a key subcolumn only for bucketed `Map`
middas-0706 pushed a commit to middas-0706/ClickHouse that referenced this pull request Nov 12, 2026
… its sibling

Since ClickHouse#124553, `MergeTreeWhereOptimizer` groups conditions by the exact columns they read, so in `t.safe != '' AND toUInt64(t.val) > 50` the two conditions on subcolumns of one `Tuple` (or `JSON`, or bucketed `Map`) became separate groups and were reordered by size, and `toUInt64` ran on the rows the guard rejects.

When a condition that may throw follows a condition over the same physical columns, group all conditions over these physical columns by them again, as before that PR. `tryBuildPrewhereSteps` still splits the group into exact-column steps and filters before the throwing one.

Closes: ClickHouse#130086
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…and rewrite `m['key']` to a key subcolumn only for bucketed `Map`
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…and rewrite `m['key']` to a key subcolumn only for bucketed `Map`
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…and rewrite `m['key']` to a key subcolumn only for bucketed `Map`
leshikus pushed a commit that referenced this pull request Nov 13, 2026
… and rewrite `m['key']` to a key subcolumn only for bucketed `Map`
@groeneai

Copy link
Copy Markdown
Collaborator Author

The backports of this PR to 26.3, 26.8 and 26.9 make the 05627_prewhere_guard_sibling_subcolumn queries fail with CANNOT_PARSE_TEXT on those branches, for example:

SELECT count() FROM t_guard_tuple WHERE t.safe != '' AND toUInt64(t.val) > 50;

I measured the test's three queries (Tuple, JSON, bucketed Map) with official binaries:

build default settings query_plan_merge_filters = 0
26.3.60.2, 26.8.34.13, 26.9.25.15 (before the backports) OK OK
26.3.63.123-lts, 26.8.37.168-lts OK CANNOT_PARSE_TEXT
26.9 branch tip (26.9.28.166) CANNOT_PARSE_TEXT CANNOT_PARSE_TEXT
26.10 tip, master OK OK

The backports split the guard on t.safe and the conversion on t.val into separate PREWHERE steps. On master, #111954 forces the filter of the step before a step that may throw. 26.3, 26.8 and 26.9 do not have #111954, so there a non-final step filters only with query_plan_merge_filters = 1 or when fewer than 60% of the rows pass. 26.9 also lacks the #131054 backport (#131110 is conflicting), so it fails with default settings too.

26.8 CI already shows it whenever query_plan_merge_filters = 0 is randomized: 1, 2, 3.

Which do you prefer for 26.3, 26.8 and 26.9:

I have not checked whether #111954 cherry-picks cleanly onto these branches.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Correction to option (a) above: #131110 as it stands makes 26.9 crash with SIGSEGV, and #131109 already does on 26.8.37.168-lts (details: #131054 (comment)). So (a) also needs a fix in #131110 before it lands, while (b) already covers #131109.

@snelheidai

Copy link
Copy Markdown

Most of the compact-part slowdown of map_subcolumns_prewhere #1 and #3 can be removed without bringing back the rewrite; the patch below does not fix #5. Since this PR was merged, CI history (amd) shows #1 0.337 → 0.454 s and #3 0.351 → 0.442 s, in addition to #5.

The cause is the first block of each read task. A compact part has no sizes of individual columns, so MergeTreeBlockSizePredictor estimates the Map at 0 bytes per row until a block is read, and the first block has max_block_size rows (about 26 MB of Map here). Before this PR only the key subcolumns left the reader, so that block was cheap. With CI release builds of the merge's parent and of master 30c7f43, max_block_size = 8192 leaves the parent unchanged (#1/#3: 306/334 ms) and brings master from 346/378 to 298/323 ms.

The patch below starts the main-step columns of a compact part with more rows than max_block_size from the part's uncompressed size per row, an upper bound that the first block then corrects. Measured on master 30c7f43, local Release builds on a 32-vCPU x86 VM, 15 paired runs, server time:

Query master patched change [95% CI]
#1 compact, SELECT 16 keys 418 ms 314 ms −24.4% [−27.0, −21.7]
#3 compact, WHERE on 16 keys 409 ms 335 ms −18.6% [−21.4, −15.8]
#5 compact, PREWHERE on 16 keys 566 ms 556 ms −0.8% [−2.8, +1.2]
#0, #2, #4, #6, #8 (wide) no significant change
#7 (wide, code path not changed) 260 ms 251 ms −4.0% [−7.5, −0.5]
One 10M-row compact part: SELECT * / max(s4) 98 / 44 ms 76 / 33 ms −22.2% / −25.6%
Same part: 6 queries with narrow filters, GROUP BY or sum(length(s1)) no significant change
200 compact parts of 50k rows: 6 queries, 1 and 32 threads no significant change

Peak memory of #1/#3 drops from 1.1 GB to 0.19/0.14 GB. With caches dropped, #1/#3 are 18%/14% faster and read the same bytes; with 8 concurrent clients they get 7% more QPS. Results are identical on 22 query variants, 115 related stateless tests have the same outcomes on both builds, and the new test 05814_block_size_predictor_compact_part fails without the patch.

Two cases are left alone because extending the estimate to them made them slower. A column read only by PREWHERE keeps the part's estimate for the whole read (#122919), and for the Map of #5 on a compact part that is 0, so every block has max_block_size rows. The upper bound there made #5 39% faster but narrow PREWHERE filters 4–6% slower, because their blocks stay small; #5 needs such columns to be measured after the first block. Parts with at most max_block_size rows are read in one block per task, and splitting it cost 3–5% for single-thread scans of many small parts.

@groeneai could you take a look?

Patch
diff --git a/src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp b/src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp
index 3ac4ca8ab7d..2acdd1b86ab 100644
--- a/src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp
+++ b/src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp
@@ -253,16 +253,34 @@ NameSet injectRequiredColumns(
 }
 
 MergeTreeBlockSizePredictor::MergeTreeBlockSizePredictor(
-    const MergeTreeDataPartInfoForReaderPtr & data_part_, const Names & columns, const Block & sample_block, bool allow_subcolumns_sizes_calculation_)
+    const MergeTreeDataPartInfoForReaderPtr & data_part_,
+    const Names & columns,
+    const Block & sample_block,
+    bool allow_subcolumns_sizes_calculation_,
+    const NameSet & columns_estimated_by_part_size)
     : data_part(data_part_), allow_subcolumns_sizes_calculation(allow_subcolumns_sizes_calculation_)
 {
     number_of_rows_in_part = data_part->getRowCount();
 
+    double part_bytes_per_row = 0;
+    if (!columns_estimated_by_part_size.empty() && data_part->isCompactPart() && number_of_rows_in_part)
+    {
+        if (auto part = data_part->getDataPart())
+            part_bytes_per_row
+                = static_cast<double>(part->getTotalColumnsSize().data_uncompressed) / static_cast<double>(number_of_rows_in_part);
+    }
+
     /// Initialize with sample block until update won't called.
-    initialize(sample_block, {}, columns);
+    initialize(sample_block, {}, columns, /*from_update=*/ false, &columns_estimated_by_part_size, part_bytes_per_row);
 }
 
-void MergeTreeBlockSizePredictor::initialize(const Block & sample_block, const Columns & columns, const Names & names, bool from_update)
+void MergeTreeBlockSizePredictor::initialize(
+    const Block & sample_block,
+    const Columns & columns,
+    const Names & names,
+    bool from_update,
+    const NameSet * columns_estimated_by_part_size,
+    double part_bytes_per_row)
 {
     /// Columns that are read only by `PREWHERE` steps are absent from the result block (the header of the reading step
     /// contains only columns that are used later in the query), but they still occupy memory while the block is being read.
@@ -327,9 +345,13 @@ void MergeTreeBlockSizePredictor::initialize(const Block & sample_block, const C
             else
                 column_size = data_part->getColumnSize(column_from_part ? column_from_part->getNameInStorage() : column_name);
 
-            info.bytes_per_row_global = column_size.data_uncompressed
-                ? static_cast<double>(column_size.data_uncompressed) / static_cast<double>(number_of_rows_in_part)
-                : static_cast<double>(column_data->byteSize()) / static_cast<double>(std::max<size_t>(1, column_data->size()));
+            if (column_size.data_uncompressed)
+                info.bytes_per_row_global = static_cast<double>(column_size.data_uncompressed) / static_cast<double>(number_of_rows_in_part);
+            else if (part_bytes_per_row > 0 && column_from_part && !info.is_subcolumn && columns_estimated_by_part_size
+                     && columns_estimated_by_part_size->contains(column_name))
+                info.bytes_per_row_global = part_bytes_per_row;
+            else
+                info.bytes_per_row_global = static_cast<double>(column_data->byteSize()) / static_cast<double>(std::max<size_t>(1, column_data->size()));
 
             dynamic_columns_infos.emplace_back(info);
         }
diff --git a/src/Storages/MergeTree/MergeTreeBlockReadUtils.h b/src/Storages/MergeTree/MergeTreeBlockReadUtils.h
index f41e99856b8..8dfff200d31 100644
--- a/src/Storages/MergeTree/MergeTreeBlockReadUtils.h
+++ b/src/Storages/MergeTree/MergeTreeBlockReadUtils.h
@@ -53,7 +53,15 @@ MergeTreeReadTaskColumns getReadTaskColumnsForMerge(
 
 struct MergeTreeBlockSizePredictor
 {
-    MergeTreeBlockSizePredictor(const MergeTreeDataPartInfoForReaderPtr & data_part_, const Names & columns, const Block & sample_block, bool allow_subcolumns_sizes_calculation);
+    /// A compact part has no sizes of individual columns, so a column of variable size is estimated as zero bytes
+    /// until the first block is read. The columns of variable size in `columns_estimated_by_part_size` start from
+    /// the uncompressed size of all columns of the compact part per row instead, an upper bound for any of them.
+    MergeTreeBlockSizePredictor(
+        const MergeTreeDataPartInfoForReaderPtr & data_part_,
+        const Names & columns,
+        const Block & sample_block,
+        bool allow_subcolumns_sizes_calculation,
+        const NameSet & columns_estimated_by_part_size = {});
 
     /// Reset some values for correct statistics calculating
     void startBlock();
@@ -139,7 +147,13 @@ protected:
     bool is_initialized_in_update = false;
     bool allow_subcolumns_sizes_calculation = false;
 
-    void initialize(const Block & sample_block, const Columns & columns, const Names & names, bool from_update = false);
+    void initialize(
+        const Block & sample_block,
+        const Columns & columns,
+        const Names & names,
+        bool from_update = false,
+        const NameSet * columns_estimated_by_part_size = nullptr,
+        double part_bytes_per_row = 0);
 
 public:
 
diff --git a/src/Storages/MergeTree/MergeTreeReadPoolBase.cpp b/src/Storages/MergeTree/MergeTreeReadPoolBase.cpp
index 76268926f7f..b0b387e9c96 100644
--- a/src/Storages/MergeTree/MergeTreeReadPoolBase.cpp
+++ b/src/Storages/MergeTree/MergeTreeReadPoolBase.cpp
@@ -542,11 +542,21 @@ MergeTreeReadPoolBase::buildReadTaskInfo(const RangesInDataPart & part_with_rang
                 sample_block_from_part.insert(ColumnWithTypeAndName(column_in_part->type->createColumn(), column_in_part->type, column_in_part->name));
         }
 
+        /// Without sizes of individual columns, the first block of every task of a compact part has `max_block_size` rows
+        /// regardless of `preferred_block_size_bytes`. Estimate the columns of the main step by the size of the part, they
+        /// are measured from the first block. Columns of `PREWHERE` steps are left as they are: a column read only by
+        /// `PREWHERE` is never measured, so an upper bound would make all blocks of a narrow column small. A part with
+        /// at most `max_block_size` rows is left as well: it is read in one block per task, which is not worth splitting.
+        NameSet columns_estimated_by_part_size;
+        if (data_part_info->isCompactPart() && data_part_info->getRowCount() > block_size_params.max_block_size_rows)
+            columns_estimated_by_part_size.insert(result_column_names.begin(), result_column_names.end());
+
         read_task_info.shared_size_predictor = std::make_unique<MergeTreeBlockSizePredictor>(
             data_part_info,
             Names(all_column_names.begin(), all_column_names.end()),
             sample_block_from_part,
-            settings[Setting::allow_calculating_subcolumns_sizes_for_merge_tree_reading]);
+            settings[Setting::allow_calculating_subcolumns_sizes_for_merge_tree_reading],
+            columns_estimated_by_part_size);
     }
 
     read_task_info.deserialization_prefixes_cache = std::make_shared<DeserializationPrefixesCache>();
diff --git a/tests/queries/0_stateless/05814_block_size_predictor_compact_part.reference b/tests/queries/0_stateless/05814_block_size_predictor_compact_part.reference
new file mode 100644
index 00000000000..ba0827f6ed9
--- /dev/null
+++ b/tests/queries/0_stateless/05814_block_size_predictor_compact_part.reference
@@ -0,0 +1,4 @@
+Compact
+1	199990000	1
+1	199990000	1
+1	90000
diff --git a/tests/queries/0_stateless/05814_block_size_predictor_compact_part.sql b/tests/queries/0_stateless/05814_block_size_predictor_compact_part.sql
new file mode 100644
index 00000000000..6a66d82b149
--- /dev/null
+++ b/tests/queries/0_stateless/05814_block_size_predictor_compact_part.sql
@@ -0,0 +1,34 @@
+-- A compact part stores all columns in one file and has no sizes of individual columns, so the block size
+-- predictor estimated a column of variable size as zero bytes until the first block was read: the first block
+-- of every read task had `max_block_size` rows regardless of `preferred_block_size_bytes`.
+-- The columns of the main read step start from the size of all columns of the part per row instead.
+
+DROP TABLE IF EXISTS t_block_size_compact;
+
+-- Compact parts need adaptive granularity; the byte limit is high enough that a granule always has 256 rows.
+CREATE TABLE t_block_size_compact (k UInt64, x UInt64, n String, s String)
+ENGINE = MergeTree ORDER BY k
+SETTINGS index_granularity = 256, index_granularity_bytes = '100Mi', min_bytes_for_wide_part = '10G', min_rows_for_wide_part = 1000000000;
+
+INSERT INTO t_block_size_compact SELECT number, number, toString(number % 10), repeat('a', 2000) FROM numbers(20000);
+
+SELECT part_type FROM system.parts WHERE database = currentDatabase() AND table = 't_block_size_compact' AND active;
+
+-- `s` is about 2000 bytes per row, so the quota allows about 100 rows per block (rounded up to a granule),
+-- far below `max_block_size`. This holds for the first block as well. (`length(s)` would read only the `s.size` subcolumn.)
+SELECT max(blockSize()) < 2048, sum(k), max(s) = repeat('a', 2000)
+FROM t_block_size_compact
+SETTINGS max_threads = 1, max_block_size = 8192, preferred_block_size_bytes = 200000;
+
+-- The wide column is read by the main step after a `PREWHERE` on a narrow one.
+SELECT max(blockSize()) < 2048, sum(x), max(s) = repeat('a', 2000)
+FROM t_block_size_compact
+PREWHERE k >= 0
+SETTINGS max_threads = 1, max_block_size = 8192, preferred_block_size_bytes = 200000, query_plan_remove_unused_columns = 1;
+
+-- A narrow column of variable size gets `max_block_size` rows once the first block measured its real size.
+SELECT max(blockSize()) = 8192, sum(toUInt64(n))
+FROM t_block_size_compact
+SETTINGS max_threads = 1, max_block_size = 8192, preferred_block_size_bytes = 200000;
+
+DROP TABLE t_block_size_compact;

@snelheidai

Copy link
Copy Markdown

Measuring the columns that only PREWHERE reads also fixes map_subcolumns_prewhere #5. The patch below replaces the one in my previous comment and adds that measurement to it. Same setup as before: master 30c7f43 and local Release builds on a 32-vCPU x86 VM, 15 paired runs, server time.

Query master patched change [95% CI]
#5 compact, PREWHERE on 16 keys 554 ms 341 ms −39.0% [−40.6, −37.2]
#1 compact, SELECT 16 keys 427 ms 318 ms −25.1% [−27.5, −22.6]
#3 compact, WHERE on 16 keys 414 ms 333 ms −21.2% [−23.6, −18.8]
#0, #2, #4, #6, #7, #8 (wide) no significant change
One 10M-row compact part, narrow column read only by PREWHERE: count() WHERE s3 LIKE '%_42_%', 32 / 1 threads 59 / 628 ms 59 / 632 ms −0.9% / +0.6%, not significant
Same part, wide column read only by PREWHERE: count() WHERE s4 LIKE '%ABC%', 32 / 1 threads 33 / 415 ms 33 / 413 ms −0.5% / −0.6%, not significant
200 compact parts of 50k rows: count() WHERE s3 LIKE '%_42_%' 53 ms 52 ms −0.5%, not significant

For #5, peak memory falls from 1.6 GB to 0.2 GB. With caches dropped, #5 takes 332 ms instead of 553 ms and reads the same bytes. With 8 concurrent clients it gets 29% more QPS (2.45 → 3.17). The other rows of the previous table keep their results, except that the single-thread count() WHERE s1 = '42' measured +3.5% [+1.2, +5.7]. That query has no PREWHERE step, so it runs the same code as with the previous patch, which measured no significant change for it; a 30-run recheck gave +1.6% [−0.9, +4.2].

The readers chain already passes the columns that each step has read to a callback, which the runtime dataflow statistics use. When the part has no column sizes (a compact part) and the task has PREWHERE steps, MergeTreeReadTask now also gives these columns to MergeTreeBlockSizePredictor::updateColumnsReadOnlyByPrewhere. That function measures the ones absent from the result block in the same way as update measures the others: the first measurement replaces the estimate, and later ones are smoothed. Since such a column is now corrected after its first block, the starting estimate from the part size covers PREWHERE columns too. The first block of #5 is therefore small as well, and a narrow column read only by PREWHERE returns to max_block_size rows after one block. Columns whose size the part knows (wide parts) keep the part's estimate, as in #122919.

Query results are identical between master and the patch on 30 query variants, including 8 new PREWHERE variants on compact parts, and 115 related stateless tests have the same outcomes on both builds. 05814_block_size_predictor_compact_part gets two cases: a wide column read only by PREWHERE, which fails on master and with the previous patch, and a narrow one, which must return to max_block_size rows after the first block.

Updated patch (against master 30c7f43)
diff --git a/src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp b/src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp
index 3ac4ca8ab7d..60ea8a5fe20 100644
--- a/src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp
+++ b/src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp
@@ -253,20 +253,39 @@ NameSet injectRequiredColumns(
 }
 
 MergeTreeBlockSizePredictor::MergeTreeBlockSizePredictor(
-    const MergeTreeDataPartInfoForReaderPtr & data_part_, const Names & columns, const Block & sample_block, bool allow_subcolumns_sizes_calculation_)
+    const MergeTreeDataPartInfoForReaderPtr & data_part_,
+    const Names & columns,
+    const Block & sample_block,
+    bool allow_subcolumns_sizes_calculation_,
+    const NameSet & columns_estimated_by_part_size)
     : data_part(data_part_), allow_subcolumns_sizes_calculation(allow_subcolumns_sizes_calculation_)
 {
     number_of_rows_in_part = data_part->getRowCount();
 
+    double part_bytes_per_row = 0;
+    if (!columns_estimated_by_part_size.empty() && data_part->isCompactPart() && number_of_rows_in_part)
+    {
+        if (auto part = data_part->getDataPart())
+            part_bytes_per_row
+                = static_cast<double>(part->getTotalColumnsSize().data_uncompressed) / static_cast<double>(number_of_rows_in_part);
+    }
+
     /// Initialize with sample block until update won't called.
-    initialize(sample_block, {}, columns);
+    initialize(sample_block, {}, columns, /*from_update=*/ false, &columns_estimated_by_part_size, part_bytes_per_row);
 }
 
-void MergeTreeBlockSizePredictor::initialize(const Block & sample_block, const Columns & columns, const Names & names, bool from_update)
+void MergeTreeBlockSizePredictor::initialize(
+    const Block & sample_block,
+    const Columns & columns,
+    const Names & names,
+    bool from_update,
+    const NameSet * columns_estimated_by_part_size,
+    double part_bytes_per_row)
 {
     /// Columns that are read only by `PREWHERE` steps are absent from the result block (the header of the reading step
     /// contains only columns that are used later in the query), but they still occupy memory while the block is being read.
-    /// Their sizes cannot be measured in `update`, so they keep the estimation obtained from the part in the constructor.
+    /// Their sizes cannot be measured in `update`, so they keep their current estimation: the one obtained from the part
+    /// in the constructor, or the one measured by `updateColumnsReadOnlyByPrewhere` if the part has no size of the column.
     size_t prewhere_only_fixed_columns_bytes_per_row = 0;
     std::vector<ColumnInfo> prewhere_only_dynamic_columns_infos;
     if (from_update)
@@ -327,23 +346,80 @@ void MergeTreeBlockSizePredictor::initialize(const Block & sample_block, const C
             else
                 column_size = data_part->getColumnSize(column_from_part ? column_from_part->getNameInStorage() : column_name);
 
-            info.bytes_per_row_global = column_size.data_uncompressed
-                ? static_cast<double>(column_size.data_uncompressed) / static_cast<double>(number_of_rows_in_part)
-                : static_cast<double>(column_data->byteSize()) / static_cast<double>(std::max<size_t>(1, column_data->size()));
+            info.no_size_in_part = !column_size.data_uncompressed;
+            if (column_size.data_uncompressed)
+                info.bytes_per_row_global = static_cast<double>(column_size.data_uncompressed) / static_cast<double>(number_of_rows_in_part);
+            else if (part_bytes_per_row > 0 && column_from_part && !info.is_subcolumn && columns_estimated_by_part_size
+                     && columns_estimated_by_part_size->contains(column_name))
+                info.bytes_per_row_global = part_bytes_per_row;
+            else
+                info.bytes_per_row_global = static_cast<double>(column_data->byteSize()) / static_cast<double>(std::max<size_t>(1, column_data->size()));
 
+            info.bytes_per_row = info.bytes_per_row_global;
             dynamic_columns_infos.emplace_back(info);
         }
     }
 
     bytes_per_row_global = static_cast<double>(fixed_columns_bytes_per_row);
-    for (auto & info : dynamic_columns_infos)
+    bytes_per_row_current = static_cast<double>(fixed_columns_bytes_per_row);
+    for (const auto & info : dynamic_columns_infos)
     {
-        info.bytes_per_row = info.bytes_per_row_global;
         bytes_per_row_global += info.bytes_per_row_global;
+        bytes_per_row_current += info.bytes_per_row;
+
+        max_size_per_row_dynamic = std::max<double>(max_size_per_row_dynamic, info.bytes_per_row);
+    }
+}
+
+bool MergeTreeBlockSizePredictor::hasColumnsWithoutSizeInPart() const
+{
+    return std::ranges::any_of(dynamic_columns_infos, [](const auto & info) { return info.no_size_in_part; });
+}
+
+void MergeTreeBlockSizePredictor::updateColumnsReadOnlyByPrewhere(
+    const ColumnsWithTypeAndName & read_columns, const Block & result_header, double decay)
+{
+    bool updated = false;
+    for (const auto & read_column : read_columns)
+    {
+        /// Columns of the result are measured in `update`.
+        if (!read_column.column || read_column.column->empty() || result_header.has(read_column.name))
+            continue;
+
+        auto it = std::ranges::find_if(dynamic_columns_infos, [&](const auto & info) { return info.name == read_column.name; });
+        if (it == dynamic_columns_infos.end() || !it->no_size_in_part)
+            continue;
+
+        size_t num_rows = read_column.column->size();
+        double local_bytes_per_row = static_cast<double>(read_column.column->byteSize()) / static_cast<double>(num_rows);
+        if (it->measured_in_step)
+        {
+            double alpha = std::pow(1. - decay, num_rows);
+            it->bytes_per_row = alpha * it->bytes_per_row + (1. - alpha) * local_bytes_per_row;
+        }
+        else
+        {
+            /// The first measurement replaces the estimation, as the first block does for the columns of the result.
+            it->bytes_per_row = local_bytes_per_row;
+            it->measured_in_step = true;
+        }
 
+        if (it->is_subcolumn)
+            it->bytes_per_row = std::max(it->bytes_per_row, it->bytes_per_row_global);
+        updated = true;
+    }
+
+    if (!updated)
+        return;
+
+    /// `update` is not called for a block without columns in the result, so the estimation is recalculated here.
+    bytes_per_row_current = static_cast<double>(fixed_columns_bytes_per_row);
+    max_size_per_row_dynamic = 0;
+    for (const auto & info : dynamic_columns_infos)
+    {
+        bytes_per_row_current += info.bytes_per_row;
         max_size_per_row_dynamic = std::max<double>(max_size_per_row_dynamic, info.bytes_per_row);
     }
-    bytes_per_row_current = bytes_per_row_global;
 }
 
 void MergeTreeBlockSizePredictor::startBlock()
diff --git a/src/Storages/MergeTree/MergeTreeBlockReadUtils.h b/src/Storages/MergeTree/MergeTreeBlockReadUtils.h
index f41e99856b8..ce19e447c87 100644
--- a/src/Storages/MergeTree/MergeTreeBlockReadUtils.h
+++ b/src/Storages/MergeTree/MergeTreeBlockReadUtils.h
@@ -53,7 +53,15 @@ MergeTreeReadTaskColumns getReadTaskColumnsForMerge(
 
 struct MergeTreeBlockSizePredictor
 {
-    MergeTreeBlockSizePredictor(const MergeTreeDataPartInfoForReaderPtr & data_part_, const Names & columns, const Block & sample_block, bool allow_subcolumns_sizes_calculation);
+    /// A compact part has no sizes of individual columns, so a column of variable size is estimated as zero bytes
+    /// until it is measured. The columns of variable size in `columns_estimated_by_part_size` start from
+    /// the uncompressed size of all columns of the compact part per row instead, an upper bound for any of them.
+    MergeTreeBlockSizePredictor(
+        const MergeTreeDataPartInfoForReaderPtr & data_part_,
+        const Names & columns,
+        const Block & sample_block,
+        bool allow_subcolumns_sizes_calculation,
+        const NameSet & columns_estimated_by_part_size = {});
 
     /// Reset some values for correct statistics calculating
     void startBlock();
@@ -61,6 +69,15 @@ struct MergeTreeBlockSizePredictor
     /// Updates statistic for more accurate prediction
     void update(const Block & sample_block, const Columns & columns, size_t num_rows, double decay = calculateDecay());
 
+    /// Columns that are read only by `PREWHERE` steps are absent from the block passed to `update`. Such a column
+    /// without a size in the part (any column of a compact part) is measured in the block of the step that reads it:
+    /// `read_columns` are the columns read by one step, before filtering, and `result_header` is the header of the result.
+    void updateColumnsReadOnlyByPrewhere(
+        const ColumnsWithTypeAndName & read_columns, const Block & result_header, double decay = calculateDecay());
+
+    /// Whether some column of variable size has no size in the part, so `updateColumnsReadOnlyByPrewhere` may be needed.
+    [[nodiscard]] bool hasColumnsWithoutSizeInPart() const;
+
     /// Return current block size (after update())
     [[nodiscard]] size_t getBlockSize() const
     {
@@ -120,6 +137,10 @@ protected:
         /// read from disk (e.g. a Map subcolumn extracts one key but reads the whole Map).
         /// When set, `bytes_per_row` will not drop below `bytes_per_row_global`.
         bool is_subcolumn = false;
+        /// The part has no size of the column, so `bytes_per_row_global` is not a measurement of it.
+        bool no_size_in_part = false;
+        /// The column was measured by `updateColumnsReadOnlyByPrewhere`.
+        bool measured_in_step = false;
     };
 
     std::vector<ColumnInfo> dynamic_columns_infos;
@@ -139,7 +160,13 @@ protected:
     bool is_initialized_in_update = false;
     bool allow_subcolumns_sizes_calculation = false;
 
-    void initialize(const Block & sample_block, const Columns & columns, const Names & names, bool from_update = false);
+    void initialize(
+        const Block & sample_block,
+        const Columns & columns,
+        const Names & names,
+        bool from_update = false,
+        const NameSet * columns_estimated_by_part_size = nullptr,
+        double part_bytes_per_row = 0);
 
 public:
 
diff --git a/src/Storages/MergeTree/MergeTreeReadPoolBase.cpp b/src/Storages/MergeTree/MergeTreeReadPoolBase.cpp
index 76268926f7f..e1beff7fb74 100644
--- a/src/Storages/MergeTree/MergeTreeReadPoolBase.cpp
+++ b/src/Storages/MergeTree/MergeTreeReadPoolBase.cpp
@@ -542,11 +542,20 @@ MergeTreeReadPoolBase::buildReadTaskInfo(const RangesInDataPart & part_with_rang
                 sample_block_from_part.insert(ColumnWithTypeAndName(column_in_part->type->createColumn(), column_in_part->type, column_in_part->name));
         }
 
+        /// Without sizes of individual columns, the first block of every task of a compact part has `max_block_size` rows
+        /// regardless of `preferred_block_size_bytes`. Estimate the columns by the size of the part instead, they are
+        /// measured from the first block (a column read only by `PREWHERE` in the block of its step). A part with at most
+        /// `max_block_size` rows is left as it is: it is read in one block per task, which is not worth splitting.
+        NameSet columns_estimated_by_part_size;
+        if (data_part_info->isCompactPart() && data_part_info->getRowCount() > block_size_params.max_block_size_rows)
+            columns_estimated_by_part_size = all_column_names;
+
         read_task_info.shared_size_predictor = std::make_unique<MergeTreeBlockSizePredictor>(
             data_part_info,
             Names(all_column_names.begin(), all_column_names.end()),
             sample_block_from_part,
-            settings[Setting::allow_calculating_subcolumns_sizes_for_merge_tree_reading]);
+            settings[Setting::allow_calculating_subcolumns_sizes_for_merge_tree_reading],
+            columns_estimated_by_part_size);
     }
 
     read_task_info.deserialization_prefixes_cache = std::make_shared<DeserializationPrefixesCache>();
diff --git a/src/Storages/MergeTree/MergeTreeReadTask.cpp b/src/Storages/MergeTree/MergeTreeReadTask.cpp
index 5a6cc9ca147..d13c973b5f4 100644
--- a/src/Storages/MergeTree/MergeTreeReadTask.cpp
+++ b/src/Storages/MergeTree/MergeTreeReadTask.cpp
@@ -191,6 +191,21 @@ MergeTreeReadTask::MergeTreeReadTask(
                 should_continue_sampling);
         };
     }
+
+    /// Columns that are read only by `PREWHERE` steps are absent from the result block. If the part has no sizes of
+    /// columns (a compact part), the size predictor measures such columns in the columns read by each step.
+    if (size_predictor && !info->task_columns.pre_columns.empty() && size_predictor->hasColumnsWithoutSizeInPart())
+    {
+        read_step_callback = [this](const ColumnsWithTypeAndName & columns,
+                                    const NameSet & partially_read_columns,
+                                    size_t read_bytes,
+                                    std::optional<bool> & should_continue_sampling) -> void
+        {
+            size_predictor->updateColumnsReadOnlyByPrewhere(columns, readers_chain.getSampleBlock());
+            if (dataflow_cache_update_cb)
+                dataflow_cache_update_cb(columns, partially_read_columns, read_bytes, should_continue_sampling);
+        };
+    }
 }
 
 /// Returns pointer to the index if all columns in the read step belongs to the read step for that index.
@@ -528,7 +543,8 @@ MergeTreeReadTask::BlockAndProgress MergeTreeReadTask::read()
     UInt64 recommended_rows = estimateNumRows();
     UInt64 rows_to_read = std::max(static_cast<UInt64>(1), std::min(block_size_params.max_block_size_rows, recommended_rows));
 
-    auto read_result = readers_chain.read(rows_to_read, mark_ranges, patches_mark_ranges, dataflow_cache_update_cb, block_size_params.max_block_size_rows);
+    const auto & step_callback = read_step_callback ? read_step_callback : dataflow_cache_update_cb;
+    auto read_result = readers_chain.read(rows_to_read, mark_ranges, patches_mark_ranges, step_callback, block_size_params.max_block_size_rows);
 
     /// All rows were filtered. Repeat.
     if (read_result.num_rows == 0)
diff --git a/src/Storages/MergeTree/MergeTreeReadTask.h b/src/Storages/MergeTree/MergeTreeReadTask.h
index 51b83af0720..a6d8d392726 100644
--- a/src/Storages/MergeTree/MergeTreeReadTask.h
+++ b/src/Storages/MergeTree/MergeTreeReadTask.h
@@ -311,6 +311,10 @@ private:
 
     RuntimeDataflowStatisticsCacheUpdaterPtr updater;
     DataflowCacheUpdateCallback dataflow_cache_update_cb;
+
+    /// Passed to the readers chain instead of `dataflow_cache_update_cb` when the size predictor measures the columns
+    /// read by each step; calls `dataflow_cache_update_cb` as well.
+    DataflowCacheUpdateCallback read_step_callback;
 };
 
 using MergeTreeReadTaskPtr = std::unique_ptr<MergeTreeReadTask>;
diff --git a/tests/queries/0_stateless/05814_block_size_predictor_compact_part.reference b/tests/queries/0_stateless/05814_block_size_predictor_compact_part.reference
new file mode 100644
index 00000000000..a3ed9ec9781
--- /dev/null
+++ b/tests/queries/0_stateless/05814_block_size_predictor_compact_part.reference
@@ -0,0 +1,6 @@
+Compact
+1	199990000	1
+1	199990000	1
+1	90000
+1	199990000
+1	199990000
diff --git a/tests/queries/0_stateless/05814_block_size_predictor_compact_part.sql b/tests/queries/0_stateless/05814_block_size_predictor_compact_part.sql
new file mode 100644
index 00000000000..e1aa1c74715
--- /dev/null
+++ b/tests/queries/0_stateless/05814_block_size_predictor_compact_part.sql
@@ -0,0 +1,48 @@
+-- A compact part stores all columns in one file and has no sizes of individual columns, so the block size
+-- predictor estimated a column of variable size as zero bytes until the first block was read: the first block
+-- of every read task had `max_block_size` rows regardless of `preferred_block_size_bytes`.
+-- The columns start from the size of all columns of the part per row instead, and are measured from the first block.
+-- A column read only by `PREWHERE` is absent from the result block; it is measured in the block of its step.
+
+DROP TABLE IF EXISTS t_block_size_compact;
+
+-- Compact parts need adaptive granularity; the byte limit is high enough that a granule always has 256 rows.
+CREATE TABLE t_block_size_compact (k UInt64, x UInt64, n String, s String)
+ENGINE = MergeTree ORDER BY k
+SETTINGS index_granularity = 256, index_granularity_bytes = '100Mi', min_bytes_for_wide_part = '10G', min_rows_for_wide_part = 1000000000;
+
+INSERT INTO t_block_size_compact SELECT number, number, toString(number % 10), repeat('a', 2000) FROM numbers(20000);
+
+SELECT part_type FROM system.parts WHERE database = currentDatabase() AND table = 't_block_size_compact' AND active;
+
+-- `s` is about 2000 bytes per row, so the quota allows about 100 rows per block (rounded up to a granule),
+-- far below `max_block_size`. This holds for the first block as well. (`length(s)` would read only the `s.size` subcolumn.)
+SELECT max(blockSize()) < 2048, sum(k), max(s) = repeat('a', 2000)
+FROM t_block_size_compact
+SETTINGS max_threads = 1, max_block_size = 8192, preferred_block_size_bytes = 200000;
+
+-- The wide column is read by the main step after a `PREWHERE` on a narrow one.
+SELECT max(blockSize()) < 2048, sum(x), max(s) = repeat('a', 2000)
+FROM t_block_size_compact
+PREWHERE k >= 0
+SETTINGS max_threads = 1, max_block_size = 8192, preferred_block_size_bytes = 200000, query_plan_remove_unused_columns = 1;
+
+-- A narrow column of variable size gets `max_block_size` rows once the first block measured its real size.
+SELECT max(blockSize()) = 8192, sum(toUInt64(n))
+FROM t_block_size_compact
+SETTINGS max_threads = 1, max_block_size = 8192, preferred_block_size_bytes = 200000;
+
+-- The wide column is read only by `PREWHERE`: it is absent from the result, but its blocks stay small.
+-- (`s != ''` would read only the `s.size` subcolumn.)
+SELECT max(blockSize()) < 2048, sum(k)
+FROM t_block_size_compact
+PREWHERE s LIKE 'a%'
+SETTINGS max_threads = 1, max_block_size = 8192, preferred_block_size_bytes = 200000, query_plan_remove_unused_columns = 1;
+
+-- A narrow column read only by `PREWHERE` is measured as well and gets `max_block_size` rows after the first block.
+SELECT max(blockSize()) = 8192, sum(k)
+FROM t_block_size_compact
+PREWHERE n LIKE '_'
+SETTINGS max_threads = 1, max_block_size = 8192, preferred_block_size_bytes = 200000, query_plan_remove_unused_columns = 1;
+
+DROP TABLE t_block_size_compact;

@groeneai

Copy link
Copy Markdown
Collaborator Author

I opened #132445 for queries 1 and 3. It is narrower than the patch: the read pool computes the part's uncompressed size per row, and the predictor uses it as the minimum estimate of the first block only, for compact parts with more rows than max_block_size read without PREWHERE. Release build, 60 runs per side: query 1 0.72x, query 3 0.71x of master, peak memory 1350 -> 206 MB and 1247 -> 140 MB.

The measurement of columns read only by PREWHERE from the second patch (query 5) is not included: it is a different mechanism.

m7kss1 pushed a commit to m7kss1/ClickHouse that referenced this pull request Nov 22, 2026
… layout

Queries 0 and 1 of `prewhere_subcolumn_read_steps` (added in ClickHouse#124553) are
noisy on arm: on master between 2026-11-12 and 2026-11-21 the medians of
the two servers differ by more than 10% in 39% / 42% of 440 arm runs (81 CI
flags, 79 on arm), while the in-run spread is about 1%.

The two servers read different part layouts. perf.py fills both servers and
stops merges only after the whole setup, so the background merges of the
JSON table race the following `Map` INSERT: arm servers read 6 to 23 parts,
amd almost always 23. A zero-level part keeps the JSON shared data as
`map_with_buckets` (`object_shared_data_serialization_version_for_zero_level_parts`),
a merged one as `advanced`, and reading `j.kind` from the former decodes
the shared data of every row. In CI, arm query 1 used 97 ms of user CPU at
6 parts and 313 ms at 23. 97% of the arm runs over 10% had different part
counts on the two servers; with equal counts 2.7% were over 10%.
Measured locally on one server: 200 ms of user CPU with 23 zero-level
parts, 31 ms with one merged part, 34 ms with 23 zero-level parts written
as `advanced`.

The queries cannot be changed in place (their history would change level),
so they are disabled and appended as queries 3 and 4 on a new table,
`t_prewhere_json_v2`, whose merges are stopped before its INSERT. The INSERT
cuts the data by rows (48 blocks of 62500 rows, squashed in pairs), so every
server reads 24 zero-level parts of 125000 rows, which a `throwIf` on
`system.parts` asserts. The `Map` query and its table are unchanged.

Related: ClickHouse#100759
Co-Authored-By: Claude Opus 5.5 <[email protected]>
mosya415 pushed a commit to mosya415/ClickHouse that referenced this pull request Nov 22, 2026
The check of the tests a PR adds or changes (ClickHouse#129330) failed a PR only when
a query's time grows run over run on the tested server. A test whose runs
are noisy without a trend passed its own PR, and in master_head PR mode the
report's own unstable/changed verdict never fails a PR. That is how
system_clusters_replicated_databases (ClickHouse#122223) got in: tested-server
spread (stddevPop / median of its runs) 0.41-2.1 in its PR, now > 0.5 on
both master servers in about 99% of runs and the noisiest test on master.

The check now also fails on an unstable query of such a test:

- PR changes only files under tests/ and the reference is the performance
  reference build of the tested master commit's sources (find_prev_build's
  new third value; a reference of an older commit, as in about a quarter
  of PR jobs, does not count): both servers run the same code built the
  same way, so the report's verdict judges the test; fail on changed_fail
  or unstable_fail of report/all-queries.tsv. A query that failed on the
  reference server and ran only on the tested one is not in that file; it
  is judged by the rule below.
- Any other PR or reference (code changes, the official-build fallback, or
  an older reference): the report measures the PR's change, not the test
  (the floors flag 79% of the heads of the 214 code PRs that changed a
  perf test in 2026-11-12..21, their own speedups). Fail when stddevPop /
  median of the tested server's runs is above 0.5 (at least 5 runs). A
  spread the change causes also fails: after the merge both master servers
  run that code.

The bar 0.5 flags 0.5% of those code-PR heads and 0.2% of quiet tests'
master heads (CIDB backtest), and all 4 jobs of ClickHouse#122223. A query the trend
check already reports gets only its trend row. The reading loop of
find_run_trends moves to read_query_runs, shared by both checks;
run_trend_gate becomes changed_tests_gate.

Validated locally on downloaded job logs (no test of the test
infrastructure): ClickHouse#122223's 4 jobs fail (the old check passes them); the
new tests of ClickHouse#129328, ClickHouse#124553, ClickHouse#131203 (code PRs) and the tests-only
ClickHouse#130763, ClickHouse#129627 pass; the run-trend output is unchanged on all 1754 tests
of 14 jobs.

Related: ClickHouse#100759

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. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR 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.

PREWHERE combines toString on JSON in the same step as other conditions

7 participants