Skip to content

Add SubcolumnPushdownPass to enable subcolumn pruning for CTE/subqueries - #94105

Open
matanper wants to merge 62 commits into
ClickHouse:masterfrom
matanper:add-subcolumn-pushdown-pass
Open

matanper wants to merge 62 commits into
ClickHouse:masterfrom
matanper:add-subcolumn-pushdown-pass

Conversation

@matanper

@matanper matanper commented Jan 13, 2026 •

Copy link
Copy Markdown
Contributor

When a CTE or a subquery projects a whole compound column (Tuple, Map, JSON, ...) and the outer query only reads one subcolumn of it, the whole column was read:

  1. the CTE projects the full column, e.g. event;
  2. the outer query resolves event.class_name into getSubcolumn(event, 'class_name');
  3. column pruning sees event as used and reads the entire column.

The new query tree pass SubcolumnPushdownPass runs after FunctionToSubcolumnsPass and rewrites those getSubcolumn calls into direct column references, pushing the subcolumn access into the projection of the source subquery:

Before: WITH foo AS (SELECT event FROM t) SELECT event.class_name FROM foo
        -> getSubcolumn(event, 'class_name'), reads the entire `event` column

After:  WITH foo AS (SELECT event.class_name FROM t) SELECT event.class_name FROM foo
        -> a direct column read of `event.class_name`

The rewrite is skipped whenever it would change the rows the source query produces - DISTINCT, GROUP BY, LIMIT BY, window functions and QUALIFY all key off the projected expressions - and the base column is only dropped from the projection once every one of its references has been rewritten. The new setting optimize_push_subcolumns_into_subqueries (on by default) turns the pass off.

Related: #112688 implements the same optimization as PushSubcolumnsIntoSubqueriesPass; only one of the two should be merged.

Closes: #92455

Changelog category (leave one):

  • Performance Improvement

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

Read only the needed subcolumns of a compound column when it is selected through a CTE or a subquery, instead of the whole column.

🤖 Generated with Claude Code


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

When using a CTE with SELECT *, the entire compound column (Tuple, JSON, etc.)
was being read even when only a subcolumn was needed. This is because:
1. CTE projects the full column (e.g., 'event')
2. Outer query resolves 'event.class_name' as getSubcolumn(event, 'class_name')
3. Column pruning sees 'event' as used, reads entire column

This new pass (SubcolumnPushdownPass) runs before RemoveUnusedProjectionColumnsPass
and transforms getSubcolumn calls into direct column references by pushing the
subcolumn access into the source subquery's projection.

Example transformation:
  Before: WITH foo AS (SELECT event FROM t) SELECT event.class_name FROM foo
          -> getSubcolumn(event, 'class_name'), reads entire 'event' Tuple

  After:  WITH foo AS (SELECT event.class_name FROM t) SELECT event.class_name FROM foo
          -> direct column access, reads only 'event.class_name'

This enables proper subcolumn pruning for CTEs and subqueries, significantly
reducing I/O for queries that access only specific subcolumns of compound types.
@CLAassistant

CLAassistant commented Jan 13, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

Added a new analyzer pass that enables subcolumn pruning for CTEs and
subqueries with SELECT *. Queries accessing subcolumns of compound types
(Tuple, JSON, Map, Array, Nullable, Nested) through CTEs now read only
the needed subcolumn instead of the entire compound column.

Example: WITH foo AS (SELECT * FROM t) SELECT event.class_name FROM foo
now reads only 'event.class_name' instead of the full 'event' column.
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jan 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jan 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b54b7f9]

Summary: ❌

job_name test_name status info comment
Style check FAIL
settings_changes_history FAIL cidb
Code Review DROPPED
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_asan_ubsan) DROPPED
Build (arm_binary) DROPPED

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jan 13, 2026
…tionColumnsPass

Running SubcolumnPushdownPass before RemoveUnusedProjectionColumnsPass
was breaking column pruning for views queried via remote(). The
RemoveUnusedProjectionColumnsPass needs to run first to ensure only
required columns are read from views on shards.

This fixes the 03550_analyzer_remote_view_columns test failure.
FunctionToSubcolumnsPass converts functions like isNull() into subcolumn
accesses (e.g., column.null). These newly created subcolumn accesses need
to be pushed down into views and subqueries for proper optimization.

Running SubcolumnPushdownPass again after FunctionToSubcolumnsPass ensures
that all subcolumn accesses are properly handled.

Fixes test failure in 02932_refreshable_materialized_views_1.
Extend SubcolumnPushdownPass to handle not just getSubcolumn() function
calls, but also direct ColumnNode references with subcolumn names (e.g.,
column.null, tuple.a).

This is critical for handling subcolumn accesses created by
FunctionToSubcolumnsPass, which converts function calls like isNull(col)
into direct subcolumn references (col.null). These references need to be
pushed down into views and subqueries for proper optimization.

Changes:
- Added processSubcolumnNode() to detect and handle direct subcolumn refs
- Refactored shared logic into pushdownSubcolumn() helper method
- processGetSubcolumnFunction() handles explicit getSubcolumn() calls
- Both types now correctly push down through QueryNode sources

Fixes the error "Not found column __table2.column.null in block" that
occurred when querying views with IS NULL conditions.

Tested with:
- 02932_refreshable_materialized_views_1 (IS NULL through views)
- 03790_cte_subcolumn_pruning (tuple subcolumns through CTEs)
- 03550_analyzer_remote_view_columns (column pruning through views)
@novikd novikd self-assigned this Jan 14, 2026
- Skip optimization for tables that don't support subcolumns (e.g., system tables)
- Clone non-CTE QueryNodes before modification to avoid shared state corruption
- Check optimization feasibility before making any modifications
- Add VIEW tests (optimized user table and non-optimized system table)
- Rename test file to reflect broader coverage (CTE, subquery, VIEW)
- Add detailed comments explaining each conditional check
Cloning a child of a JoinNode would invalidate column references in the
ON clause, causing LOGICAL_ERROR "does not have valid source node".

Skip the subcolumn pushdown optimization for sources inside JOINs since
cloning one side would leave the join condition columns pointing to the
deallocated original node.
Two issues fixed:
1. Cloning a child of a JoinNode would invalidate column references in the
   ON clause, causing LOGICAL_ERROR "does not have valid source node".
2. Always clone the source QueryNode before modifying (including CTEs) to
   avoid modifying shared state that might be used in multiple contexts
   (e.g., EXPLAIN, caching).

Added safety check for projection size to prevent undefined behavior if
projection nodes and columns get out of sync.
…hrough JOINs

Two issues fixed:
1. Cloning a child of a JoinNode would invalidate column references in the
   ON clause, causing LOGICAL_ERROR "does not have valid source node".
2. Always clone the source QueryNode before modifying (including CTEs) to
   avoid modifying shared state that might be used in multiple contexts
   (e.g., EXPLAIN, caching).

Added safety check for projection size to prevent undefined behavior if
projection nodes and columns get out of sync.
Refactored SubcolumnPushdownPass to use a two-pass approach:
1. First pass collects all getSubcolumn calls grouped by source
2. Second pass clones each source once and adds all needed subcolumns

This fixes the LOGICAL_ERROR that occurred when accessing multiple
subcolumns from the same base column (e.g., ProfileEvents.keys and
ProfileEvents.values) through CTEs or UNIONs.

Also moved RemoveUnusedProjectionColumnsPass to run after
SubcolumnPushdownPass so it can clean up unused base columns.

Added tests for multi-subcolumn access patterns.
@matanper
matanper force-pushed the add-subcolumn-pushdown-pass branch from 3394414 to 00e5625 Compare January 15, 2026 21:58
- Remove unused base columns directly in the pass instead of relying
  on a second RemoveUnusedProjectionColumnsPass
- Add explanatory comments above each conditional check
Use std::greater<>() instead of std::greater<size_t>() for transparent functor.
@matanper
matanper force-pushed the add-subcolumn-pushdown-pass branch from fa1ddf8 to 7b313ae Compare January 16, 2026 21:28
When cloning a source for subcolumn pushdown optimization, all columns
referencing that source must be updated to point to the cloned source.
Previously only subcolumn access columns were updated, leaving other
columns (e.g., `id` in `SELECT id, data.a FROM view`) with orphaned
source references, causing LOGICAL_ERROR.
@abashkeev abashkeev added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 3, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (clean, no conflicts) in bbe2a81. The merged tree builds, and all 8 tests of the PR pass locally. No review threads are open.

alexey-milovidov and others added 3 commits October 28, 2026 03:55
…ion rewrites in `SubcolumnPushdownPass`

Both boundary predicates are evaluated after the aggregation, so a `getSubcolumn` there must not be replaced by a standalone subcolumn when the query groups by the parent column (`NOT_FOUND_COLUMN_IN_BLOCK`).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The scalar subquery `(SELECT sum(json.b.:Int64) FROM (SELECT json FROM p_w))` is there to read the whole `json` column, in contrast to the direct typed subcolumn read. With `optimize_push_subcolumns_into_subqueries` the subcolumn is pushed into the subquery, so it reads as `NULL` the same as the direct read. Disable the pushdown for that query to keep its intent.

https://s3.amazonaws.com/clickhouse-test-reports/PRs/94105/bbe2a8104bc1f14c9707baead8d71cb76dfad65f/pr/result_stateless_tests_arm_binary_parallel.json

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 4 commits October 29, 2026 00:00
…arts

After a lazy `JSON` type hint change (`enable_json_lazy_type_hints`), reading the whole column from an old part converts it to the new type, while reading the subcolumn exposes the old type, so `optimize_push_subcolumns_into_subqueries` changed the result (e.g. `NULL` instead of `15` for `j.b.:Int64` after removing the hint `b UInt64`).

Push a subcolumn of a column with dynamic subcolumns only if every part of the `MergeTree` table stores the column under exactly the type of the table metadata, or the storage is `Memory` or a `Log` engine. Restore `05301_json_shared_typed_paths_alter` with the pushdown enabled and add a focused off/on regression test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…torage-cast)`

A lazily loaded table is reached through a storage proxy whose snapshot carries
no parts, so the cast is expected to fail for it and the pushdown of `JSON`
subcolumns is skipped (fail-close). Fixes the `storage_casts` style check:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=94105&sha=c16459d7d598ce6c48e024e2261f10fcb4b81d56&name_0=PR&name_1=Style%20check
PR: ClickHouse#94105

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With `apply_mutations_on_fly = 1` the pending mutations are applied to the
whole column, but not to a subcolumn read directly, so `SubcolumnPushdownPass`
exposed the old values (`sum(tup.a)` returned `3` instead of `84` after a
pending `ALTER TABLE t UPDATE tup = tuple(42, 'z')`). Keep the extraction from
the parent for the columns the mutations snapshot reports as changed on the fly,
and for storages other than `MergeTree` when mutations are applied on the fly.

Address review: ClickHouse#94105 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…he source query settings

`SubcolumnPushdownPass` decided whether a column may be changed on the fly only by the explicit
assignment targets of the pending mutations, but `MutationsInterpreter` also recalculates the
`MATERIALIZED` columns depending on them (directly or through `ALIAS` and other `MATERIALIZED`
columns). Use `MaterializedColumnDependencies::findColumnsToRecalculate`, the same check
`AlterConversions` uses for the read, to reject those columns too.

The storage check also used the context of the outer query, while the table is read with the
settings of the source subquery, so a subquery enabling `apply_mutations_on_fly` locally bypassed
the guard for `Merge` and other proxy storages. Use the context of the source query instead.

Extend `05459_subcolumn_pushdown_mutations_on_fly` with both cases.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (clean, no conflicts) in d3504fe. The merged tree builds, and all 11 tests of the PR (plus 04873_tuple_subcolumn_pushdown_case_insensitive_collision from master) pass locally. No review threads are open.

alexey-milovidov and others added 3 commits November 10, 2026 20:18
Index analysis matches primary key, partition key and skip index expressions
against the query, so replacing `getSubcolumn(tup, 'a')` with a direct read of
`tup.a` broke pruning by a key defined over `getSubcolumn(tup, 'a')`. Skip
columns used by keys and secondary indices, as `FunctionToSubcolumnsPass` does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Include `ExpressionActions.h` for the secondary index check, and add a test
that the primary key and a skip index over `getSubcolumn(tup, 'a')` still prune
granules with `optimize_push_subcolumns_into_subqueries` enabled.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… when the parent stays read

`SubcolumnPushdownPass` validated a subcolumn only against the metadata of the storage in the
subquery. A forwarding storage (`Merge`, `Buffer`, `MaterializedView`, `Alias`, a lazily loaded
table, ...) passes the flattened name `tup.a` to the underlying table, where it can resolve to a
declared column `tup.a`, skip a conversion of the whole column, or bypass a primary key or skip
index that the forwarding storage's metadata does not have. Only storages that read their own data
(`MergeTree` family, `Memory`, the `Log` family, `file`, `url` and object storages) are accepted now.

The pass also added a subcolumn read even when the whole column was still read by the subquery
(another projection column, `WHERE`, ...) or referenced directly by the outer query, which reads
more and prunes nothing. Now the subcolumns of a column are pushed down only if every reference to
it is a pushed subcolumn access and the subquery reads the column nowhere else.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 4 commits November 14, 2026 01:01
Projections are matched against the expressions of the query, so a
projection defined over `getSubcolumn(t, 'a')` is not selected for a
query that reads the column `t.a` directly. `isKeyColumn` now also
checks `ProjectionDescription::getRequiredColumns` of every projection,
so both aggregate projection selection and normal projection key pruning
keep working when `optimize_push_subcolumns_into_subqueries` is enabled.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
After merging `master`, `FunctionNode::isAggregateFunction` no longer exists: it was
replaced by `isAggregationCall`, which has the same meaning here (an aggregate function
that is not a window call).

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (no textual conflicts) in 05a5809. The merge had one semantic conflict: FunctionNode::isAggregateFunction was removed on master (f7c43a1), so SubcolumnPushdownPass now uses isAggregationCall, which has the same meaning there (b54b7f9). The merged tree builds, and all 15 tests of the PR pass locally. No review threads are open.

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-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). external Author is not a member of the ClickHouse organization pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

CTE with SELECT * prevents subcolumns pruning

7 participants