Skip to content

Push subcolumn reads into subqueries - #112688

Closed
alexey-milovidov wants to merge 129 commits into
masterfrom
json-subcolumn-pushdown
Closed

alexey-milovidov wants to merge 129 commits into
masterfrom
json-subcolumn-pushdown

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 30, 2026 •

Copy link
Copy Markdown
Member

Closes: #75538
Related: #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 requested subcolumns of columns exported by subqueries, CTEs and UNION ALL branches instead of the whole columns. Ordinary views benefit when analyzer_inline_views = 1. For example, SELECT data.a FROM (SELECT * FROM table) with a JSON column data now reads only the subcolumn data.a from the table. Controlled by the new setting optimize_push_subcolumns_into_subqueries (enabled by default).

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

When a subcolumn of a column exported by a subquery is requested, it is resolved into the getSubcolumn function over the whole column: SELECT data.a FROM (SELECT * FROM test) reads the whole data column from the table and extracts the subcolumn afterwards.

The new query tree pass PushSubcolumnsIntoSubqueries adds the subcolumn to the subquery projection and replaces the getSubcolumn function with a reference to it. If the whole column is not used anywhere else, it is then removed from the subquery projection by the subsequent RemoveUnusedProjectionColumns pass, so only the subcolumn is read from the table. The pushdown works through several levels of subqueries, CTEs and UNION ALL branches, and also applies to Tuple, Nullable, Array and other types with subcolumns. Ordinary views benefit when analyzer_inline_views = 1. UNION ALL subqueries are supported: the subcolumn is added to every branch at the same position, all-or-nothing, and only when the branch types match exactly (the subcolumn of the least supertype is not guaranteed to be the supertype of the branch subcolumns). The DISTINCT, INTERSECT and EXCEPT modes deduplicate or match rows over all projection columns, so such subqueries are not rewritten (nor are recursive CTEs).

The pushdown is skipped when it could change the query result:

  • when the subquery uses DISTINCT, GROUP BY, aggregate functions, or ORDER BY ... WITH FILL (an added projection column would change the result or would not be valid);
  • when the subquery is on a side of a JOIN that can be filled with default values for non-matched rows (getSubcolumn of a default value is not always equal to the default value of the subcolumn type, e.g. for the null subcolumn of Nullable columns); a shared subquery node (an ordinary CTE referenced several times) found in any such position is ineligible for all of its occurrences;
  • in the outer query with aggregation, an occurrence of getSubcolumn is only replaced when it is evaluated before the aggregation step (WHERE, JOIN ON, arguments of aggregate functions) or when the whole expression is an aggregation key (but not under ROLLUP, CUBE and GROUPING SETS, where keys replaced with the same pushed column would be merged);
  • when a wrapper (Buffer, MaterializedView, Merge, ...) exposes the column with another type than the storage it forwards the read to;
  • when the column types diverge, e.g. under join_use_nulls or group_by_use_nulls;
  • when the whole column is also read in the outer query, including uses by correlated subqueries and uses under a different exported name of the same physical column (SELECT tup AS x, tup FROM t, or a trivial ALIAS storage column next to its base column), and uses of an exported column the pushed subcolumn is a part of (SELECT x.b, tup FROM (SELECT tup.a AS x, tup FROM t), where the live tup export already reads everything tup.a.b reads; an export of a sibling or of a deeper subcolumn does not block the pushdown, it reads less than the whole column): the subquery would then read both the whole column and the subcolumn from the table, while extracting the subcolumn from the already read column is cheaper. For a UNION ALL target the alias equivalence of exported names is detected in every branch (the pushdown is applied to all branches or to none), so a single branch exporting the same physical column under another name that stays alive blocks the rewrite. The decision counts only sibling subcolumns that are validated as actually pushable into the target (in a side-effect-free dry run): when two subcolumns of the same exported column are requested and only one of them can be pushed (e.g. the other is shadowed by a same-named storage column inside the subquery), nothing is pushed, since the unpushable sibling keeps the whole column alive.
  • when the target subquery itself reads a column containing the pushed subcolumn outside of its projection (e.g. WHERE cityHash64(tup) > 0): the subcolumn is then extracted from the value that is read anyway;
  • when a filter attached during planning (a row policy or additional_table_filters, with ALIAS columns expanded) reads a column containing the pushed subcolumn;
  • for a direct read from a MergeTree table some of whose parts store the JSON column with another type than the metadata (after a lazy type hint change): a subcolumn read from such a part gives defaults (Lazy JSON type hint subcolumns return defaults on pre-ALTER parts #123339), so the subcolumn is extracted from the whole column there;
  • for references of a reused MATERIALIZED CTE (enable_materialized_cte): the temporary table serves all references of the CTE, so pruning the parent column there would require proving that no reference needs the whole column. Single-use materialized CTEs are inlined by the analyzer and take the ordinary subquery path (subcolumn reads over materialized CTEs are currently broken on master independently of this change, see Materialized CTE: subcolumn reads fail with NOT_FOUND_COLUMN_IN_BLOCK #113623).

Besides the plain subcolumn reads (getSubcolumn, tupleElement, variantElement, mapKeys, mapValues, m['key'], length, isNull), the forms that FunctionToSubcolumns rewrites into an expression over a subcolumn are pushed as well: empty / notEmpty of a String, Array or Map become a comparison of the size subcolumn with zero, isNotNull becomes not of the null subcolumn, mapContainsKey becomes has over the keys subcolumn, count of a Nullable becomes sum(not(<column>.null)), and tupleElement of a QBit reads the bit-plane subcolumn. FunctionToSubcolumns only rewrites columns read directly from a table, and it runs after this pass, so without this these forms would keep reading the whole parent column through every subquery, CTE and UNION ALL layer. Different functions of the same subcolumn share one pushed projection column, e.g. length(a) and empty(a) both read a single a.size0. The remaining guards of FunctionToSubcolumns are mirrored: a function-form carrier (anything but a plain getSubcolumn) is not rewritten into a direct subcolumn read of a table with FINAL, because the rewrite may alter the special merging algorithms (a plain subcolumn access stays pushable under FINAL — the analyzer itself resolves it into a direct subcolumn read there); the carrier origin of a pushed getSubcolumn projection is remembered, so the restriction survives multi-level pushdown. tupleElement with a positional index over an unnamed tuple is not pushed into tuple-element-only readers that match the flattened t.1 against the real field names of a file (e.g. file(..., Parquet/ORC) with a positional structure hint). A Map with Enum keys converts the key (a name or a numeric value) through the enum before serializing the key subcolumn, and a value that is not a member is not rewritten; a String key whose length differs from a FixedString map key is not rewritten either, because the padded key would turn a missing-key lookup into a match. The chained Dynamic/JSON-array access x.a[1].b reads only the path json.a through the ordinary getSubcolumn pushdown; it is deliberately not rewritten into arrayElement over the typed nested subcolumn json.a.:`Array(JSON)`.b, because that subcolumn holds only the arrays stored as Array(JSON) and would lose the values of the other runtime alternatives of the Dynamic path (Array(Nullable(JSON)), Array(Dynamic), nested arrays).

Subqueries spelled with an alias list, e.g. SELECT x.a FROM (SELECT json FROM t) AS s(x), are supported. Trivial ALIAS columns (an ALIAS whose body is just another column of the same table, possibly chained) exported by a subquery are followed down to the underlying storage column. A subquery can also export a derived subcolumn (e.g. SELECT json.a AS x FROM ... over a deeper subquery keeps a getSubcolumn(json, 'a') projection expression); reading a subcolumn of such an export composes the paths (a + b -> a.b), so the pushdown continues through derived exports down to the base table. The composition is applied only when the flat name resolves to the same substreams and type as the structured extraction, so a sibling tuple element literally named a.b or a typed JSON path a.Int64 is never read instead. Conversely, when no name of such an alias-equivalent class of exports remains referenced in the outer queries, the never-referenced sibling exports are dead together with the replaced ones (all of them are removed by RemoveUnusedProjectionColumns), so they do not block the pushdown through the deeper levels of subqueries; the alias-equivalent classes are taken from every branch of a UNION ALL target.


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

New query tree pass PushSubcolumnsIntoSubqueries: when a subcolumn of a
column exported by a subquery, CTE or view is requested (resolved into
the `getSubcolumn` function over the whole column), add the subcolumn
to the subquery projection and replace the function with a reference to
it. If the whole column is not used anywhere else, it is then removed
from the subquery projection by the RemoveUnusedProjectionColumns pass,
and only the subcolumn is read from the table.

Controlled by the new setting optimize_push_subcolumns_into_subqueries
(enabled by default).

Closes #75538

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [69843c3]

Summary: ✅


AI Review

Summary

The PR pushes subcolumn reads through subqueries, CTEs and UNION ALL branches. Review of head 69843c39deb18873dc687611bcce2b87db8d7b26 found three reproduced regressions: local distributed query execution fails, explicit indexed getSubcolumn predicates lose index matching, and candidate validation adds substantial query-analysis overhead. Changes are required.

Findings

❌ Blockers

  • PushSubcolumnsIntoSubqueriesPass.cpp:2356: The secondary-query guard misses local shard plans, which retain the initiating query kind and run this non-idempotent pass through ignoreASTOptimizations. With two localhost shards, a two-row table containing c1 Tuple(Nullable(Int32)), and SELECT sum(r.c1.1 IS NULL) FROM d AS l CROSS JOIN (SELECT c1 FROM raw) AS r WHERE l.id = 0, pushdown disabled returns 2; enabled raises THERE_IS_NO_COLUMN. The expected aggregate header contains isNull(c1.1), while the local plan produces notEquals(c1.1.null, 0). Remote execution succeeds. Skip the rewrite for already-optimized local shard plans and add a stateless regression.

  • PushSubcolumnsIntoSubqueriesPass.cpp:1326: Index protection excludes explicit getSubcolumn expressions. For ORDER BY getSubcolumn(n, 'null'), an outer WHERE getSubcolumn(n, 'null') = 0 over a subquery changes from 8/781 to 781/781 granules when pushdown is enabled. With force_primary_key = 1, the previously successful query raises INDEX_NOT_USED. Preserve literal indexed expressions across this rewrite. The existing index-preservation thread was reopened with the exact-head reproducer.

⚠️ Majors

  • PushSubcolumnsIntoSubqueriesPass.cpp:1012: Validation scans every physical column of every active part for each candidate, even for ordinary String columns and candidates later rejected by liveness checks. On 1,000 compact parts and 129 columns, EXPLAIN QUERY TREE selecting 32 strings alongside their lengths increases from a warm median 6 ms disabled to 79 ms enabled, although no rewrite occurs. The subcolumn-only case increases from 5 ms to 75 ms. Inspect only the relevant physical column, reuse safety-check results, and avoid unnecessary part scans.
Tests
  • ⚠️ 05447_mysql_prepared_statement_metadata.py:267: The new provenance regression selects both length(a) and whole a, which prevents pushdown. Exact-head query trees confirm this test does not exercise the rewritten metadata path. Use SELECT length(a) AS len FROM (SELECT a FROM arrays) with pushdown explicitly enabled for both text queries and prepared statements.
Final Verdict

❌ Block. Protect local shard headers and explicit indexed expressions, remove the repeated full-part column scans, and make the provenance regression exercise pushdown.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jul 30, 2026
alexey-milovidov and others added 3 commits July 31, 2026 13:54
…eExpressionNode join tree accessors

Co-Authored-By: Claude Fable 5 <[email protected]>
`QueryTreePassManager::runOnlyResolve` ran a hardcoded number of the first
passes (4), which was meant to cover `QueryAnalysisPass`,
`GroupingFunctionsResolvePass`, `AutoFinalOnQueryPass` and
`RemoveUnusedProjectionColumnsPass`. Inserting `PushSubcolumnsIntoSubqueriesPass`
before `RemoveUnusedProjectionColumnsPass` shifted the latter out of that range,
so the secondary queries on the shards stopped pruning unused projection columns
of `VIEW`s and read all the columns of the underlying table. This broke
`03550_analyzer_remote_view_columns`.

Look up the index of `RemoveUnusedProjectionColumnsPass` by name instead of
hardcoding it, so that adding a pass before it does not silently exclude it.
@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR adds an analyzer pass that pushes subcolumn reads (Map keys/values, Nullable null maps, tuple elements, JSON paths) into subqueries, and moves a helper out of FunctionToSubcolumnsPass. The pass only matches when a column comes from a subquery or UNION. ClickBench Q32 (+14.8%) and Q33 (+8.6%) are plain single-table aggregations with neither, so the pass cannot change their plans or execution. Both stay within master's recent variance range, and the deterministic suppression agrees with the diff. CPU time is higher on both, which fits the source run sharing its host with the TPC-H benchmark rather than a code effect, so no performance change is attributed to this PR.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 32 not_sure 722 828 +14.8% <0.0001 aggregation: Large GROUP BY over a single table with no subqueries or subcolumn access, so the new pushdown pass never matches it. The +14.8% stays inside master's recent range and cannot be attributed to this PR.
⚠️ 33 not_sure 1161 1261 +8.6% <0.0001 aggregation: Single-table GROUP BY with no subqueries, so the subcolumn pushdown pass does nothing here. The +8.6% stays inside master's recent range and is not attributable to the diff.

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

🟢 No significant changes

Debug info
  • StressHouse run: 0e9d4791-88ff-4ab2-9fe5-d329c44c66a0
  • MIRAI run: 33d408dc-88d4-4557-945c-594fcd8fe267
  • PR check IDs:
    • clickbench_3453632_1791247235
    • clickbench_3453853_1791247485
    • clickbench_3453955_1791247505
    • tpch_adapted_1_official_3454068_1791247539
    • tpch_adapted_1_official_3454260_1791247568
    • tpch_adapted_1_official_3454373_1791247595

…subcolumn pushdown

- Gate the table branch of `buildSubcolumnProjectionNode` on
  `supportsOptimizationToSubcolumns` instead of `supportsSubcolumns`, so
  storages that expose subcolumns syntactically but opt out of rewriting
  column reads into direct subcolumn reads (`StorageFile`, `StorageURL`,
  `StorageDistributed`, object storage engines) are not affected. Also skip
  virtual columns, aligned with `FunctionToSubcolumnsPass`.
- Filter `eligible_targets` by each target subquery's own value of
  `optimize_push_subcolumns_into_subqueries`, so disabling the setting
  inside a subquery or CTE via a `SETTINGS` clause protects that subquery
  from being rewritten by its parent, and use the subquery's own context
  when building deeper `getSubcolumn` nodes.
- Add the test `04665_push_subcolumns_into_subqueries_guards` covering both
  contracts.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 256/275 (93.09%) · Uncovered code

Full report · Diff report

…tion

Two tests requested in the review:

- `04667_push_subcolumns_into_subqueries_view_source` covers a dependent
  materialized view whose query reads a subcolumn through a subquery and
  through a CTE. On that path the source table is represented by
  `StorageValues` holding the inserted block. `StorageValues` reads
  subcolumns of the block with `getColumnOrSubcolumnByName`, so the
  pushdown is safe there; the test pins that behavior.

- `04668_push_subcolumns_into_subqueries_read_bytes` measures `read_bytes`
  of the same query with `optimize_push_subcolumns_into_subqueries` off and
  on: reading `tup.a` of a `Tuple(a UInt32, b String)` through a subquery
  reads 400 KB instead of 21 MB (53 times less) on 100000 rows.
@clickhouse-gh

clickhouse-gh Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 69843c39d with master 51c63967d (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 ⚠️

14 object files changed (+565.14 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Analyzer/Passes/PushSubcolumnsIntoSubqueriesPass.cpp.o new 587.82 KiB +587.82 KiB
src/CMakeFiles/dbms.dir/Analyzer/QueryTreePassManager.cpp.o 86.53 KiB 59.40 KiB -27.12 KiB (-31.35%)

719 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.

Compile time of recompiled translation units

126 translation units recompiled, 831 s compile time in total, 125 of them have a recent master baseline.

Translation units without a recent master baseline:

  • src/Analyzer/Passes/PushSubcolumnsIntoSubqueriesPass.cpp: 12.4 s

Job report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The only failure in the last public CI run, 04357_distributed_alias_same_expression in Stateless tests (amd_debug, parallel), is unrelated to this PR: it is the known flaky wrong-result issue with duplicate ALIAS columns under two-level aggregation over Distributed tables, tracked in #112987 with a fix in progress in #108855. The CH Inc sync failures (test_azure_blob_storage_native_copy client timeout under TSan and a 04411_distinct_partitions_independently timeout under MSan) both passed on their automatic reruns and were classified as transient. Merged current master and pushed to re-run CI.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Both remaining CI failures on commit 2b4e2e7 are unrelated to this PR (the analyzer pass only rewrites subcolumn reads over subqueries/CTEs; both failures come from fuzzed/stress queries that never touch it, and both signatures occur on master and on dozens of other PRs):

  1. Stress test (amd_tsan): logical error Reading from materialized CTE 'ct' before its materialization completed - DelayedPortsProcessor gate is missing in the query plan, raised while ReadFromMerge::createChildrenPlans optimizes a child plan of a fuzzed query over the experimental materialized-CTE feature. This is the known master-wide class tracked in Materialized CTE over Distributed: 49 LOGICAL_ERROR "Reading from materialized CTE before its materialization completed - DelayedPortsProcessor gate is missing" survives the #108924 fix #113184 and Logical error Reading from materialized CTE before its materialization completed under EXPLAIN ANALYZE with chained materialized CTEs and WITH TOTALS #110176, with fixes in progress: Fix materialized CTE "gate is missing" error with extremes and UNION #113043 and Fix materialized CTE "gate is missing" error with WITH TOTALS #111194. The same signature failed on master itself (AST fuzzer amd_msan, 2026-08-04 03:23) and on many unrelated PRs over the last days. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112688&sha=2b4e2e7ee2285c94f8605bf67bbb7c98d1860be5&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29

  2. Stress test (amd_msan): Hung check failed, possible deadlock found. Not a deadlock: the single "hung" query is an already-cancelled (is_cancelled = 1) INSERT INTO ... SELECT ... toJSONString(...) from 03278_json_subcolumns_in_skipping_indexes.gen.sql, whose writer thread is still actively burning CPU inside MSan-instrumented SerializationVariant/SerializationDynamic stream enumeration in MergeTreeDataPartWriterWide::writeSingleGranule — an uninterruptible CPU-bound write path under MSan, same class as Uninterruptible CPU-bound function evaluation over a large value #112203. This hung check has failed on master (2026-08-03 22:34, amd_msan) and on ~20 unrelated PRs in the last two days alone. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112688&sha=2b4e2e7ee2285c94f8605bf67bbb7c98d1860be5&name_0=PR&name_1=Stress%20test%20%28amd_msan%29

@groeneai, investigate the MSan hung-check flood (item 2): the cancelled INSERT keeps writing because the wide-part write path does not check the cancellation flag between granules, which under MSan takes longer than the hung-check timeout. If a fix or tracking issue already exists beyond #112203, link it here; otherwise provide a fix in a separate PR.

@Avogar Avogar self-assigned this Aug 4, 2026
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator

Investigated item 2. An owner exists for the writer path you describe, but the flood you are pointing at is mostly a different mechanism, which I think matters for what to fix.

The writer path: #108357 owns it. "Make column data write during INSERT respond to query cancellation" (open, external) adds MergeTreeDataPartWriterOnDisk::checkWriteCancellation and calls it per granule from MergeTreeDataPartWriterWide::writeColumn and MergeTreeDataPartWriterCompact::writeDataBlock. That is the granularity your description asks for, and you already reviewed it and pushed ac7290c5fb1 yourself. I measured it earlier on an almost identical row: the same fuzzed INSERT at max_execution_time = 10, real server, 3 runs each, went from 38.4 / 38.1 / 38.7 s on pristine master to 10.8 / 10.8 / 11.0 s with #108357 applied, ending at the limit with TIMEOUT_EXCEEDED. So nothing new is needed beyond it, and per-granule is fine-grained enough here: this row wrote 65536 rows at index_granularity = 1, so ~65537 granules, and reproducing that shape locally gives 0.058 ms per granule (3.8 s for the whole insert on a debug build). Even a 20x MSan factor leaves a single granule ~4 orders of magnitude below the 90 s hung-check window, so a checkpoint at the granule-loop head closes the gap rather than shrinking it. It is the writer path and not #112203, which is about evaluating one large value inside a function.

But this row is not representative of the flood. I pulled hung_check.log for every Stress test (*_msan) hung check in the last 3 days and bucketed them by the hung query's own stack, parsed per processlist row:

bucket rows
ReadFromMerge::createChildrenPlans inside QueryPlan::optimize 20
MergeTreeDataPartWriterWide::writeColumn (this row's class) 2
other analyzer / misc 5

All 20 are a fuzzer-generated merge(REGEXP(...), ...) query wedged in query planning, which is exactly what your own #113140 ("Fix cubic complexity of planning a JOIN with a merge table") fixes. The master row you cite as evidence, bffd1f1bc64a0d8c11066ca1852b534b043a99a6 at 2026-08-03 22:34, is one of them: SELECT count(), sum(cityHash64(*)) FROM merge(REGEXP('t.*'), '.+') ARRAY JOIN n, elapsed 1612 s, ReadFromMerge and QueryPlan::optimize on the stack, no writer frame. So the flood is dominated by #113140, and #108357 covers the tail your PR happened to hit.

One correction to the CPU claim, because it changes which fix helps: this query was not burning CPU for the full 1893 s. UserTimeMicroseconds + SystemTimeMicroseconds is 8.55 s against 1893 s elapsed, and RealTimeMicroseconds is 22.05 s, so the counters stopped being flushed about 22 s in and the thread was ~39% CPU inside that counted window. The stack is real and the path is uninterruptible, but the writer had already finished its 65536 rows (written_rows = 65536, written_bytes = 7.95M, MergeTreeDataWriterBlocks = 2); what is stuck for the remaining ~1870 s is the pipeline not observing the cancellation, not a granule loop still grinding. That is #47272's general shape.

Nothing here is attributable to this PR: no PushSubcolumnsIntoSubqueries frame appears anywhere in the log, and 03278_json_subcolumns_in_skipping_indexes.sql.j2 is untouched by your diff.

I am not opening anything new, since #108357 and #113140 between them own 22 of the 27 rows. Happy to file a tracking issue for the residual 5 if you want one.

… materialized CTEs

Support the subcolumn pushdown for subqueries spelled with an alias list,
e.g. `SELECT x.a FROM (SELECT json FROM t) AS s(x)`: the overridden names
are already baked into the projection columns after analysis, so the pass
only needs to keep `projection_aliases_to_override` in sync when
`QueryNode::addProjectionColumn` appends a column. The blanket rejection
of such subqueries in `canAddProjectionColumns` is removed, and the new
test `04813_push_subcolumns_into_subqueries_alias_list` checks that only
the subcolumn is read for several alias-list shapes.

Reused `MATERIALIZED` CTEs stay TableNode references over the temporary
table that serves all references of the CTE, so pruning the parent column
there would require proving that no reference needs the whole column, and
adding the subcolumn without removing the parent column would only make
the materialized table bigger. Such references are deliberately left as
is; this is now documented in `matchCandidate`, and the new test
`04814_push_subcolumns_into_subqueries_materialized_cte` checks that
subcolumn reads over reused materialized CTEs stay correct with the
optimization enabled. Subcolumn reads over materialized CTEs are broken
on master in ways independent of this change (any subcolumn of a
single-use materialized CTE, `Tuple` subcolumns of reused ones), see
issue #113623.

Co-Authored-By: Claude Fable 5 <[email protected]>

@novikd novikd left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks very overcomplicated

Comment thread src/Analyzer/QueryTreePassManager.cpp Resolved
…mns into subqueries

Move the helper `resolveTrivialAliasChain` from `FunctionToSubcolumnsPass` to
`Analyzer/Utils` so that `PushSubcolumnsIntoSubqueriesPass` can reuse it: an
exported ALIAS column whose body is just another column of the same table
(possibly chained) is semantically the underlying storage column, so the
subcolumn can be read directly from the table instead of keeping `getSubcolumn`
over the whole column above the subquery.

Co-Authored-By: Claude Fable 5 <[email protected]>
alexey-milovidov and others added 4 commits October 29, 2026 11:04
…lazy `JSON` type hints

- A `tupleElement` whose element name is a nested path of another element when flattened
  (`a.b` next to `a`) is no longer a pushdown candidate. Every form of the pushdown names the
  element by its flattened name: a direct subcolumn read was already guarded, but the
  intermediate `getSubcolumn(c, 'a.b')` built for a deeper subquery read `a`.`b` instead of the
  literal element `a.b` (3 instead of 99 through two subquery layers, also for a positional
  selector and for function-form exports).
- `hiddenFilterReadsContainingColumn` expands `ALIAS` columns of the table (recursively) in a
  row policy or `additional_table_filters`, as the planner does, so `cityHash64(a1) > 0` with
  `a1 ALIAS tup` keeps `tup` read and the subcolumn is extracted from it.
- A subcolumn of a `JSON` column is not read directly from a `MergeTree` table while some of
  its parts store the column with another type than the metadata (a lazy type hint change).
  The reader resolves the subcolumn against the type of the old part and returns defaults
  (#123339), so the pass newly turned a correct
  whole-column extraction into `NULL`. The override of the setting in
  `05301_json_shared_typed_paths_alter` is removed: the test passes with the pushdown enabled.

Regressions are in `05456_push_subcolumns_into_subqueries_review_fixes_7`.

#112688

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

The depth of the read step under `UNION DISTINCT` in `EXPLAIN` varies between runs
(`│        Output: tup` vs `│     Output: tup`), which made the test flaky. Collapse the
spaces after the plan tree marker; the order of the `Output` lines still shows the
rewrite.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=112688&sha=b46a82a6cdadad921c5c299fb559ed0989403f92&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29
#112688

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

Master added another test with the number `05456`.

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

Copy link
Copy Markdown
Member Author

🕵 Addressed the three new review threads (719d242) and merged master. 04836_push_subcolumns_into_subqueries_union failed because the EXPLAIN indentation under UNION DISTINCT varies between runs. c6614e6 collapses that indentation.

@groeneai, investigate the failure: Stress test (amd_debug), a segmentation fault in DB::IOutputFormat::flushImpl (__dynamic_cast) called from ClientBase::resetOutput in ClientEmbedded (https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=112688&sha=b46a82a6cdadad921c5c299fb559ed0989403f92&name_0=PR&name_1=Stress%20test%20%28amd_debug%29). It is on the client side and unrelated to this PR. Please provide a fix in a separate PR. If the fix is already in progress, link it here. #126142 may be related. Thanks for #127925 for 05227_mutate_part_ahead_of_table_metadata_version_mergetree. Build profile diff failed with LogClusterNotReady, an infrastructure problem.

@groeneai

Copy link
Copy Markdown
Collaborator

Fixed by #127912, merged yesterday at 15:13 UTC. This run built b46a82a merged into master 079b5ce, which predates the fix; the current run for ffc1256 builds on 6624a33, which contains it, so nothing is needed in this PR.

The cause is the one described in #111985 (comment) (the catch in ClientBase::initOutputFormat destroyed the output buffers but kept output_format, then resetOutput finalized it into freed memory). #126142 is a different defect on the same resetOutput path (finalizing into a canceled buffer) and does not cover this one. No run whose build contains the fix has shown this stack so far.

alexey-milovidov and others added 2 commits October 30, 2026 09:24
…or secondary queries

Address review: the guards for columns used by keys, indices and projections and for parts
with a lazily changed `JSON` type hint checked only the storage read by the query. `Merge`,
`MaterializedView`, `Buffer`, `Alias` and storage proxies forward the read with the requested
subcolumns to underlying tables, whose keys and parts were not inspected. Now the guards are
applied to every underlying storage as well, failing closed when it cannot be determined.

`PushSubcolumnsIntoSubqueriesPass` is no longer run for secondary queries. The query sent to a
shard or a parallel replica already carries the pushed subcolumns, and a second run is not
idempotent: it lowered `isNull(c1.1)` over the pushed `c1.1` into `notEquals(c1.1.null, 0)`,
so the header of the replica did not match the initiator (`NOT_FOUND_COLUMN_IN_BLOCK` in
`04869_sparse_tuple_element_missing_column_read` with parallel replicas).

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=112688&sha=ffc1256b783d9f15d29e9d34d2951686474abb68&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel%29

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

Copy link
Copy Markdown
Member Author

🕵 Status 2026-10-30: merged current master (clean) and pushed ebe5008:

  • 04869_sparse_tuple_element_missing_column_read (ParallelReplicas) failed with NOT_FOUND_COLUMN_IN_BLOCK whenever a remote replica returned data: the replica re-ran PushSubcolumnsIntoSubqueriesPass on the already pushed query and lowered isNull(c1.1) into notEquals(c1.1.null, 0), changing its header. The pass is now skipped for secondary queries; reproduced deterministically with parallel_replicas_local_plan = 0 and fixed (covered in the new 05459_push_subcolumns_into_subqueries_wrappers).
  • Both review threads about Merge / materialized view wrappers are addressed: the index/projection and lazy JSON type hint guards now look through the storages the read is forwarded to.
  • 05397_clickhouse_local_locked_path_untouched on arm_darwin is unrelated; it is skipped on macOS on master since 59f220c, which this merge pulls in.

alexey-milovidov and others added 2 commits October 31, 2026 05:14
… in the pushdown guard

A row policy of a child of `Merge` (or of the target of a materialized view,
`Buffer`, `Alias`, a proxy) is attached when the wrapper builds the read of
that table, after the pushdown decision. `hiddenFilterReadsContainingColumn`
now walks the underlying storages with `anyStorageReadFrom` and checks their
effective row policies (with `ALIAS` expansion against their own metadata).
If such a policy reads the whole column, the subcolumn is not pushed and is
extracted from the value already read.

Regression: `05462_push_subcolumns_into_subqueries_merge_child_row_policy`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits November 1, 2026 05:17
…down

Resolve the conflict in `QueryTreePassManager`: master added `runFrom` and a static
`resolve_passes_count = 4`, while this PR computes the count of resolve passes dynamically
(it includes `PushSubcolumnsIntoSubqueriesPass`). Keep the dynamic member, expose it via
`getResolvePassesCount` and use it in `InterpreterSelectQueryAnalyzer`.
…onversions of wrappers

- With `ROLLUP`, `CUBE` and `GROUPING SETS`, different grouping keys (`length(arr)` and `arr.size0`)
  replaced with the same pushed column were deduplicated, which changed the grouping sets and the
  masks of `grouping`. Keys are no longer replaced under these modifiers.
- A `Buffer`, `MaterializedView` or `Merge` table can expose a column with another type than the
  storage it forwards the read to; reading the whole column converts it, while a forwarded subcolumn
  of the wrapper type (`n.null` of `Nullable(UInt8)` over `UInt8`) may not exist there, so `Buffer`
  silently skipped the destination. Such subcolumns are no longer pushed down.

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=112688&sha=8fd4787f1cf25de5a059d13ab8dae204aaae112f&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29 (Equal values are not contiguous within the range assumed to be sorted, STID: 2508-31ed) and provide a fix in a separate PR. If the fix is already in progress, link it here. The fuzzed query (SELECT DISTINCT x, s FROM (SELECT 1 AS x, 'Hello' AS s ORDER BY x WITH FILL ... INTERPOLATE (s AS ...)) ORDER BY s) uses no subcolumns; it looks like #118077 (DISTINCT with WITH FILL).

@groeneai

groeneai commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator

This is the WITH FILL UInt8 wrap again: 1 AS x is UInt8 and TO 65537 does not fit it, so the fill emits ..., 254, 255, 0, 1, ..., the subquery output is no longer sorted by x, and the in-order DISTINCT on top trips the assertion. INTERPOLATE and the outer ORDER BY s do not matter (without them master aborts the same way). Not #118077; it is covered by your #112650 (open).

Measured with clickhouse local and the exact failing query:

No separate PR from me.

alexey-milovidov and others added 2 commits November 2, 2026 06:52
…s_into_subqueries_grouping_modifiers_and_wrapper_types`

The `Buffer` table in the test has a column type that differs from its
destination table on purpose, so the server logs a warning that the Fast test
reports as unexpected stderr.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=112688&sha=4ea4a7224b9dae9a69edc62c3daadb0cad310aa6&name_0=PR&name_1=Fast%20test
#112688

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

Copy link
Copy Markdown
Member Author

🕵 Status 2026-11-02: pushed f22cdbf.

  • Fast test failed in 05479_push_subcolumns_into_subqueries_grouping_modifiers_and_wrapper_types only because of stderr: the test deliberately creates a Buffer table whose column type differs from its destination, and StorageBuffer logs a warning about that. The test now sets send_logs_level = 'error' (a079f11). The query results were already correct.
  • Merged current master (clean merge).
  • @groeneai, thanks for tracking down the AST fuzzer (amd_debug, targeted) failure. It is the WITH FILL UInt8 wrap that Reject WITH FILL bounds that do not fit the ORDER BY column type #112650 covers, so this PR needs no change for it.

Comment thread src/Analyzer/QueryTreePassManager.cpp Resolved
# Conflicts:
#	tests/queries/0_stateless/05337_parallel_join_max_joined_block_size.sql
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The Stress test (arm_release) failure (Logical error: 'Cannot write to canceled buffer' in ClientBase::resetOutput -> JSONRowOutputFormat::writeSuffix, https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=112688&sha=f22cdbf64ebd812a8d7544f0f5ef97168b3bb186&name_0=PR&name_1=Stress%20test%20%28arm_release%29) is unrelated to this PR: it is the known issue #125973, with a fix in progress in #126142.

…ntoSubqueriesPass`

The origins were collected after `runOnlyResolve`, which now includes
`PushSubcolumnsIntoSubqueriesPass`. That pass can rewrite an expression over a
subquery column (e.g. `length(a)` in `SELECT length(a) AS len FROM (SELECT a FROM t)`)
into the subcolumn `a.size0`, so the MySQL metadata reported `org_table = t` and
`org_name = a.size0` for a computed result. Now the origins are collected right
after the passes that only resolve the query tree, before any pass that can
rewrite an expression into a column. The MySQL metadata test covers the
subquery case.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
/// plan. The pass is not idempotent: a function-form carrier over a pushed subcolumn
/// (`isNull(c1.1)` over the pushed `c1.1`) is lowered only by a second run, which would change the
/// header of the secondary query (`notEquals(c1.1.null, 0)`) and break the reading of its result.
if (context->getClientInfo().query_kind == ClientInfo::QueryKind::SECONDARY_QUERY)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Skip the non-idempotent pass when building local shard plans

Checking only SECONDARY_QUERY misses local shards: createLocalPlan copies the initiating context and uses ignoreASTOptimizations, so its query kind remains INITIAL_QUERY. The resolve-only range still executes this pass, lowering an already-pushed expression a second time and changing the aggregate header.

Reproduced on 69843c39deb1 with two localhost shards in local_two and default optimization settings:

CREATE TABLE raw (id UInt64, c1 Tuple(Nullable(Int32)))
ENGINE = MergeTree ORDER BY id;
INSERT INTO raw VALUES (0, (1)), (1, (NULL));
CREATE TABLE d AS raw
ENGINE = Distributed(local_two, currentDatabase(), raw);

SELECT sum(r.c1.1 IS NULL)
FROM d AS l CROSS JOIN (SELECT c1 FROM raw) AS r
WHERE l.id = 0
SETTINGS optimize_push_subcolumns_into_subqueries = 1;

Pushdown disabled returns 2; enabled raises THERE_IS_NO_COLUMN: the initiator expects sum(isNull(...c1.1)), but the local plan produces sum(notEquals(...c1.1.null, 0)). Setting prefer_localhost_replica = 0 also restores the result. Please suppress this pass for already-optimized local shard plans as well, and cover this local execution path in a focused stateless regression.

const auto & columns = storage_snapshot->metadata->getColumns();
auto part_has_different_type = [&](const MergeTreeData::DataPartPtr & part)
{
for (const auto & part_column : part->getColumns())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Avoid a full parts-and-columns scan for every candidate

This loops over every physical column of every active part for each candidate, including ordinary String columns. It runs during validateGroup, before the whole-column liveness guard can reject the rewrite. Consequently even a query whose plan remains unchanged pays O(candidates × parts × physical columns) work.

On the exact-head Fast test binary, a table with 1,000 compact parts and 129 columns (id plus 128 String columns), queried with EXPLAIN QUERY TREE SELECT c0, length(c0), ... c31, length(c31) FROM (SELECT * FROM t), takes a warm median 6 ms with pushdown disabled versus 79 ms enabled. None of the 32 candidates is ultimately pushed because the whole columns remain selected. The subcolumn-only variant also increases from 5 ms to 75 ms. These are analysis timings, without data reads.

Please resolve the relevant physical column once and inspect only its type, reuse safety-check results within the query, and avoid scanning parts when their layout cannot affect the rewrite. Add a focused analysis-time comparison for a wide table with many parts; the existing bytes-read regression does not exercise this cost.

@alexey-milovidov alexey-milovidov self-assigned this Nov 4, 2026
@alexey-milovidov

alexey-milovidov commented Nov 4, 2026 •

Copy link
Copy Markdown
Member Author

@novikd provided a comment:

I think it is a bad idea to implement it as it is in the PR right now. I had plans for 26.12 as well to implement it as a volume-reducing function optimization on top of the plan (query_plan_push_down_volume_reducing_functions).
It would allow us to get rid of all the problems with FunctionToSubcolumnsPass and cover all the cases.
@KochetovNicolai also thinks that this is the right approach.

@groeneai, submit a PR with a complete re-implementation using @novikd's idea.
It's okay if Dmitry also planned to implement it - you can submit your implementation independently, so we will hedge the completion.

@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator

Acknowledged. I'll submit an independent re-implementation as a query plan optimization on top of the volume-reducing functions push-down (query_plan_push_down_volume_reducing_functions), and I'll post the PR link here.

@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator

I opened #129422: it re-implements this as a query plan optimization inside query_plan_push_down_volume_reducing_functions, pushing subcolumn reads down to ReadFromMergeTree through subqueries, views, UNION ALL and the non-padded side of a JOIN.

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

Labels

comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Replace JSON column in the subquery to requested subcolumns

4 participants