Skip to content

Push subcolumn reads down the query plan to the MergeTree read step - #129422

Open
groeneai wants to merge 23 commits into
ClickHouse:masterfrom
groeneai:subcolumns-push-down-to-reading
Open

groeneai wants to merge 23 commits into
ClickHouse:masterfrom
groeneai:subcolumns-push-down-to-reading

Conversation

@groeneai

@groeneai groeneai commented Nov 5, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #75538
Closes: #92455
Closes: #107038
Related: #112688

Changelog category (leave one):

  • Performance Improvement

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

Read only the requested subcolumns of columns returned by subqueries, CTEs, views, UNION ALL branches and the non-padded sides of a JOIN: for example, SELECT data.a FROM (SELECT * FROM t) and SELECT length(arr) FROM (SELECT * FROM t) now read only data.a and arr.size0 from a MergeTree table, and skip indexes and the primary key over a subcolumn are used through a view. It is controlled by query_plan_push_down_volume_reducing_functions.

Description

A re-implementation of #112688 as a query plan optimization, the design @ novikd proposed there. FunctionToSubcolumnsPass still rewrites direct reads.

Through a subquery, x.p is getSubcolumn(x, 'p') over the whole column, and FunctionToSubcolumnsPass rewrites length(arr), isNull(n), m['k'], ... only for direct reads, so ReadFromMergeTree reads the whole column (for JSON, all paths).

tryPushDownVolumeReducingFunction now first follows a column that only subcolumn reads use from the top Expression/Filter down through Expression, Filter, Sorting, Limit, Offset and the non-padded side of JoinStepLogical to ReadFromMergeTree, which then reads the subcolumns. The whole path is rewritten at once, so no other optimization sees an intermediate state. Residual functions (empty(arr) is arr.size0 = 0) stay in their step, and the top header is unchanged. UNION ALL branches are handled by liftUpUnion.

It is not applied (whole column read as before) to plans shipped to other servers, FINAL of engines that combine values, tables with changes applied on the fly (pending mutations with apply_mutations_on_fly, unmerged patch parts) or masking policies, parts whose stored type differs from the table's, compact parts without substream marks, padded JOIN sides, non-MergeTree sources, function forms over columns used by keys, skip indexes or projections, and plain reads over columns of the partition key, aggregate projections or set indexes.

Validation: 05507 compares the read columns and results with the setting off for each case; 05508 checks read bytes drop 10x. The tests of #112688 and #94105 give the same results with the setting on and off. Locally, SELECT data.k0 FROM (SELECT * FROM t WHERE key % 2 = 0) reads 63 MB instead of 507 MB.


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

groeneai and others added 8 commits November 4, 2026 17:25
- 04711: the two push-down rows pin serialize_query_plan = 0. The distributed plan CI suites set
  serialize_query_plan = 1 in the server profile (tests/config/users.d/distributed_plan.xml), and the
  push-down is off for plans that can be shipped, so the okv row printed 0 there.
- ReadFromMergeTree part guard: compare the types of the read columns only, instead of iterating
  every column of every part (parts x table columns).
- tryPushDownSubcolumnsToReading: return before cloning the DAG when no node of the step is a
  subcolumn read of an input (a necessary condition of collectSubcolumnReads).
- 05507: forced partition-key and set/text index checks through a subquery for k3, k3w, k5s, k5w.
- 05337: say why the last query disables the push-down.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
05507: the K3 (partition key over the whole tuple) and K5 (set index over the whole
tuple and over a Nullable) refusals get a plan check of the prewhere filter column,
which keeps getSubcolumn over the whole column when the plain read is refused. The
Output lines cannot show it, since the filter moves to PREWHERE.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove three comments in pushDownVolumeReducingFunctions.cpp that restate the code below them.

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

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (rounds 1-3 of this PR's review)
Finding Verdict
❌ 04711 new rows not pinned to serialize_query_plan = 0; the distributed plan suites set it in the profile, which turns the push-down off AGREE, fixed
⚠️ The part-type guard scanned every column of every part; now only the read columns AGREE, fixed
⚠️ No plan or forced-index rows for the partition-key and set-index refusals AGREE, fixed (PREWHERE column and forced-index rows added)
⚠️ A SETTINGS ... = 0 inside a subquery does not stop the rewrite DISAGREE: the plan is optimized once with the top-level settings, like every query plan optimization (InterpreterSelectQueryAnalyzer.cpp); results are identical
💡 Cheap check before cloning the step's DAG; a why for the 05337 pin AGREE, fixed
💡 getSubcolumn marked volume-reducing has no effect of its own DISAGREE: kept to follow the design's terms; no behaviour

@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On master 05508 prints 0 (the subquery read is not 10x smaller), 05507 fails at its first plan line, and the reproducers of #75538, #92455 and #107038 read the whole column or fail with INDEX_NOT_USED.
b Root cause explained? Through a subquery, CTE, view, UNION ALL branch or JOIN side, x.p is getSubcolumn(x, 'p') over the whole column, and FunctionToSubcolumnsPass only rewrites direct reads, so the read step reads the whole column.
c Fix matches root cause? Yes: the subcolumn read is moved to the step that reads the column, as part of the volume-reducing push-down. The guards cover cases where a direct subcolumn read would differ or an index/projection would no longer match.
d Test intent preserved / new tests added? New 05507 (positive, negative and index/projection cases, each compared with the setting off), 05508 (read bytes), a performance test extension. 04711 and 05337 keep their assertion with the setting pinned off.
e Both directions demonstrated? Yes: both new tests fail on master and pass with the change; 50 randomized runs of each pass.
f Fix is general across code paths? One mechanism for Expression, Filter, Sorting, Limit, Offset, JoinStepLogical and UNION ALL, every function form FunctionToSubcolumnsPass rewrites, and composed subcolumns.
g Fix generalizes across inputs (params/datatypes/wrappers)? Tuple, nested Tuple, Nullable, Array, Map, Variant, Dynamic, JSON paths, type hints and sub-objects; columns added later with constant, DEFAULT and MATERIALIZED expressions.
h Backward compatible? (maintainer-approved exception only) Yes: existing setting query_plan_push_down_volume_reducing_functions, no default change; = 0 gives the old plan. No format or protocol change.
i Invariants and contracts preserved? The top step's header is unchanged (checked before the rewrite, asserted after); results equal to the setting-off run in every case and in the 57 test files of #112688 and #94105.

Session id: cron:clickhouse-impl-slot-40:20261104-194200

@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @vdimir, could you review this and add the can be tested label so CI runs? It follows a column that only subcolumn reads use from the top Expression/Filter down through Expression, Filter, Sorting, Limit, Offset and the non-padded side of JoinStepLogical to ReadFromMergeTree, rewriting the whole path at once inside tryPushDownVolumeReducingFunction, so subqueries, views and UNION ALL read only the subcolumn.

@clickhouse-gh

clickhouse-gh Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bbdd89c]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, s3 storage, DBReplicated, sequential) FAIL
05339_filelog_shared_watch_thread FAIL cidb
Integration tests (arm_binary, 5/5) FAIL
test_storage_s3_queue/test_parallel_inserts.py::test_parallel_inserts_with_failures[1-exclusive] FAIL cidb
Upgrade check (amd_release) FAIL
Cannot check whether the row policies can be applied (see unchecked_row_policy_errors.txt) FAIL cidb

AI Review

Summary

Reviewed commit bbdd89c64cfb6694d71ed6156de3dcbf396389d7. The PR pushes eligible subcolumn reads through subqueries, views, unions, and joins into ReadFromMergeTree, preserving the existing setting to disable the optimization. All four previous findings are addressed in the current code; no new actionable findings remain. The three new 05507 stateless tests matched their references exactly with the PR-head Fast test binary, and additional comparisons found no SQL result differences with pushdown enabled versus disabled.

Final Verdict

Status: ✅ Approve.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Nov 5, 2026
@CLAassistant

CLAassistant commented Nov 5, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@clickhouse-gh clickhouse-gh Bot added can be tested Allows running workflows for external contributors comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... labels Nov 5, 2026
groeneai and others added 2 commits November 5, 2026 02:53
The byte limit checks read `min(length(s))` above the join so that the
1 KB column stays in the rows the join emits. With the subcolumn push-down
`length(s)` reads only `s.size` through the non-padded side of the join,
so the rows are 8 bytes and the padded blocks are no longer cut by
`max_joined_block_size_bytes` (Fast test: `unmatched probe rows, bytes`
and `unmatched build rows, bytes` print 0). The checks now compare the
whole column, which brings it back to the join (max block 9 rows, as on
master). The reference is unchanged.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=129422&sha=0ca909af4598d2dce65eefd65d0065d54e1c3ea8&name_0=PR

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`FunctionToSubcolumnsPass` reads `vec.N` for `tupleElement(vec, N)` (and
`vec.N`) over a `QBit` column read directly from a table, but through a
subquery the read still took the whole column. The plan-level matcher now
accepts that form too, with the same element name check
(`getElementSubcolumnName` for `QBit`) and the same storage substream check
as the direct rewrite. It is a function form, so the existing guards for
keys, skip indexes (including vector similarity ones), projections and
`FINAL` apply.

`05507` gets a case that reads `vec.1, vec.9` instead of `vec` with
identical results; the binary without this change prints `vec`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With `skip_empty_columns_on_insert = 1` and `serialization_info_version =
'with_missing_columns'`, a column whose values are all defaults is not
written to the part; `serialization.json` records it in `missing_columns`
with the type it had at write time, and `IMergeTreeReader` fills it with
that type's default and then converts it to the current type. After a
metadata-only type change (`MODIFY COLUMN data JSON(a String)` with
`enable_json_lazy_type_hints = 1` over a `JSON(a UInt32)` part) the whole
column reads `a = '0'`, while a subcolumn read takes `data.a.size` from
the frozen default and returns 0. The part guard skipped columns absent
from the part, so `length(data.a)` through a subquery returned 0 with the
push-down and 1 without it.

The guard now also compares the recorded type of an omitted column with
the metadata type, as it already does for a column the part stores.
Case N11b in 05507 is the reproducer (the binary before this change reads
`data.a.size` and prints `[(0),(0)]`).

Found by the clickhouse-gh review on ClickHouse#129422.

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

clickhouse-gh Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

⚠️ Significant changes: object file sizes.

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.

Object file sizes ⚠️

83 object files changed (+625.29 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/pushDownVolumeReducingFunctions.cpp.o 129.35 KiB 607.27 KiB +477.91 KiB (+369.47%)
src/CMakeFiles/dbms.dir/Analyzer/Passes/getSubcolumnOfFunction.cpp.o new 99.93 KiB +99.93 KiB
src/CMakeFiles/dbms.dir/Processors/QueryPlan/ReadFromMergeTree.cpp.o 2.57 MiB 2.62 MiB +45.89 KiB (+1.74%)
src/CMakeFiles/dbms.dir/Analyzer/Passes/FunctionToSubcolumnsPass.cpp.o 466.76 KiB 421.27 KiB -45.49 KiB (-9.75%)

711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.58, programs/clickhouse-keeper ×0.59 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 6.4 s 10.5 s +6.8 s (+181%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.5 s 7.2 s +5.1 s (+250%)
Compile time of recompiled translation units

232 translation units recompiled, 2330 s compile time in total, 231 of them have a recent master baseline.

Translation unit Master PR Δ vs median
src/Processors/QueryPlan/Optimizations/pushDownVolumeReducingFunctions.cpp 4.3 s 13.8 s +9.6 s (+228%)

Job report

The flaky check runs each changed test in 8 parallel copies with the thread
fuzzer on, and 05507 took 187-217 s per run in the amd_debug, amd_binary and
amd_asan_ubsan flaky checks, over the 180 s limit. Its 617 statements are
evenly cheap (the job's query_log shows no dominant query), so the cost is the
statement count.

The cases are moved, not changed, into three files along their fixtures:
plan cases on the basic shapes (P1-N-ADD, N-ADD2), on-the-fly changes, part
formats, projections and read in order (N9-N31), and keys, indexes and
projections (K1-K8, P36-P39). Every statement of the old file appears exactly
once, and the three references reassemble into the old reference; the only
new line is a label for the K8 projection check, which moved next to K8.

Locally, at 8 concurrent copies with the thread fuzzer's sleeps, the old
file took 27.1 s (median of 8) and the new ones 11.2, 6.6 and 9.2 s.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A Map key of type LowCardinality(FixedString(N)) passed the width check,
so `m['ab']` over `Map(LowCardinality(FixedString(4)), V)` read through a
subquery was rewritten to the subcolumn `m.key_ab\0\0`: the constant is
padded to the key width, and a key 'ab\0\0' then matched although
`arrayElement` returns the default for it (99 instead of 0). The same for
a FixedString constant of another width (`m[toFixedString('ab', 3)]`).

Reported by the AI review on ClickHouse#129422. Test cases N19b (refused short key)
and P41 (a full-width key is still read as the key subcolumn).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The part check of `canReadSubcolumnsOfColumn` looks only at the parts of
the planning snapshot, but a `STREAM` read also reads the parts committed
later. A compact part without substream marks inserted into a running
stream cannot read `s.null` of a sparse `Nullable` alone, so
`SELECT s.null FROM (SELECT * FROM t STREAM)` failed with NOT_IMPLEMENTED
while the same query with the push-down off returned all rows. Refuse the
rewrite for every stream read.

05509 inserts such a part after the stream has read the first one: it
fails with the error on the previous commit and returns the rows now.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@yariks5s yariks5s self-assigned this Nov 5, 2026
The push-down of subcolumn reads is off when parallel replicas are used,
so in the ParallelReplicas CI job (parallel replicas on in the server
profile) the row that expects `arr.size0` in the plan of a read through
`okv` printed 0. Pin the setting on that row and on its negative pair
for `vw`, like `serialize_query_plan = 0` is already pinned for the
distributed plan jobs.

Reproduced locally with the job's settings at both
`parallel_replicas_local_plan` values: the old rows fail with the same
diff, the pinned rows pass (also 50/50 randomized with and without
parallel replicas), and dropping the pin fails again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai and others added 4 commits November 5, 2026 22:08
…n-to-reading

Needed for the bucketed-only gate of ClickHouse#124553 (`IStorage::hasBucketedMapSerialization`), which the
push-down of `m['key']` to a key subcolumn has to apply as well: with it merged, a basic `Map`
read through the push-down gets the key-subcolumn rewrite again (Fast test 03989 and 05340).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ClickHouse#124553 rewrites `m['key']` to the key subcolumn `m.key_<key>` only when the table writes Maps with
buckets: with the basic serialization the key subcolumn reads the whole Map anyway. The push-down
matched `m['key']` regardless, so on a basic Map it brought the rewrite back, both for a read through
a subquery and for a direct read whose rewrite FunctionToSubcolumnsPass had just declined (Fast test
03989 and 05340 on the merge with master).

Refuse the key-subcolumn form unless `MergeTreeData::hasBucketedMapSerialization`. 05507: the tables
whose cases expect `m.key_*` pin both Map serialization settings to `with_buckets` (clickhouse-test
randomizes them), and a new case N32 reads `m['k1']` of a basic Map through a subquery.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The filter push-down can move `WHERE s.tup.a` below a join as a filter whose
filter column is the subcolumn read `getSubcolumn(__table1.tup, 'a')` itself,
removed after filtering, while the step above the join reads the same
subcolumn again. The rewrite turned both reads into one carried column and
made the join return it, but the filter still removed it, so the join's input
had no column for its DAG input: `The header [__table1.id] has a column for
only 1 of the DAG's 2 inputs` (AST fuzzer, STID 2728-49fe), and
NOT_FOUND_COLUMN_IN_BLOCK when building the join pipeline.

Refuse the rewrite when a filter on the path removes a filter column that a
step above reads as a carried column. Other columns of the same read are
still pushed down (N33: `n` is read whole, `tup.a` as a subcolumn).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`SELECT tup.a FROM (SELECT * FROM t PREWHERE tup.a < 3)` aborted in
`tryPushDownSubcolumnsToReading` with `std::out_of_range`
(`unordered_map::at: key not found`), AST fuzzer STID 2508-34fb.

PREWHERE `tup.a < 3` makes `ReadFromMergeTree` read the subcolumn `tup.a`
itself and drop it after the filter, so its output has `tup` but not
`tup.a`. `addReadColumn` returns early for a column the read already reads,
so it does not pass `tup.a` through the PREWHERE actions, and after
`readSubcolumnsInsteadOfColumn` the output still lacks it. A row policy on
the subcolumn (`row_level_filter`) does the same.

Refuse the push-down when a subcolumn it would read is already read but
missing from the read's output. The query then reads the whole column, as
master does. Cases that read the subcolumn for the first time are unchanged.

New cases in 05507: N34 (PREWHERE on `tup.a` two subqueries down) and N35
(row policy on `t2` using `tup.a`). Both abort the pre-fix server.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai and others added 2 commits November 6, 2026 05:50
`tryPushDownSubcolumnsToReading` rewrote one column per call and returned,
so a query reading subcolumns of N columns through a subquery applied the
optimization N times, and each time cloned and re-analysed every step of the
path for each column: planning time grew quadratically with the projection
width. With 1000 `String` columns, `EXPLAIN SELECT length(s0), ...,
length(s999) FROM (SELECT * FROM t)` took 11.0 s instead of 0.08 s (debug
build), and a query with enough such columns failed with
TOO_MANY_QUERY_PLAN_OPTIMIZATIONS.

The columns are now followed down the plan together and grouped by the read
and the path they come from. A group is analysed in one pass over the steps
of the path: a column that fails a check is dropped and the others are
analysed again, and the rest are rewritten at once, with one `Read
subcolumns` step and one pruning of the read
(`ReadFromMergeTree::readSubcolumnsInsteadOfColumns`). If the steps take
each column alone but not all of them together, the columns are tried one
by one, as before.

Planning time on vs off (debug, EXPLAIN): 1000 String columns 0.085 s vs
0.072 s, 2000 columns 0.182 s vs 0.153 s, `.a` of 1000 Tuple columns
0.103 s vs 0.097 s.

05507 P42: all 40 columns are pushed down with
`query_plan_max_optimizations_to_apply = 10`; before, EXPLAIN pushed 4 of
them and the query failed with TOO_MANY_QUERY_PLAN_OPTIMIZATIONS. P31 now
has one `Read subcolumns` step for its two columns.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The table that this PR added to push_down_volume_reducing_functions.xml has a
`JSON` column, which the Iceberg rewrite of the perf runner cannot map, so all
six `Performance Comparison (..., iceberg_local|iceberg_s3, k/3)` jobs failed
with `IcebergRewriteError: Column data of type JSON has no Iceberg equivalent`.

Skipping push_down_volume_reducing_functions.xml would also stop the Iceberg
configuration from measuring its existing queries, which it runs today. So the
new table and its four queries move unchanged into
push_down_subcolumns_to_reading.xml, which is added to iceberg_skip_list.txt
with the reason `JSON column`, and push_down_volume_reducing_functions.xml is
back to its master content. The push-down reads subcolumns only from
MergeTree, so nothing of it is measurable on Iceberg tables anyway.

The new file does not inherit `optimize_functions_to_subcolumns = 0` from the
old one. The three plain subcolumn reads do not depend on it (`getSubcolumn` is
matched before the function-form check, and their query trees are identical
with 0 and 1), and the `length(arr)` query keeps its own
`optimize_functions_to_subcolumns = 1`.

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

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - bf32767

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) / 05401_quota_on_profile_events_query_result_cache flaky, not in this PR's diff: Code: 201, Quota ... has been exceeded: SelectQuery = 2/1 because the quota user inherits parallel replicas from the job's default profile; 51 of 51 reruns passed. The same test failed on master and on about 25 other PRs today. The fix merged at 13:24Z, after this run (12:39Z), so the tested tree does not contain it #129672 (mine, merged)
Mergeable Check / PR praktika rollups of the row above #129672 (mine, merged)
CH Inc sync private sync CH Inc sync (private, not actionable by me)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261106-150005

@novikd novikd self-assigned this Nov 9, 2026
@nickitat

Copy link
Copy Markdown
Member

🕵 Merged master into this branch and resolved the conflicts caused by #129617 (the switch to the -WithMemoryTracking containers). I also added a small commit that switches the new code to the -WithMemoryTracking types where it meets the APIs changed there, so that it compiles. This update was made automatically.

This branch has not been deployed

No deployments
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-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... pr-performance Pull request with some performance improvements

Projects

None yet

5 participants