Skip to content

Cherry pick #113367 to 26.8: Memoize supportsOptimizationToSubcolumns in FunctionToSubcolumnsPass - #125099

Closed
robot-ch-test-poll wants to merge 12 commits into
backport/26.8/113367from
cherrypick/26.8/113367
Closed

robot-ch-test-poll wants to merge 12 commits into
backport/26.8/113367from
cherrypick/26.8/113367

Conversation

@robot-ch-test-poll

Copy link
Copy Markdown
Contributor

Original pull-request #113367

Do not merge this PR manually

This pull-request is a first step of an automated backporting.
It contains changes similar to calling git cherry-pick locally.
If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.

The check results does not matter at this step - you can safely ignore them.

Before you resolve anything

Conflicts are often caused by a prerequisite change that has not been backported yet, rather than by a real divergence. The bot re-tries this cherry-pick against the release branch on every run, so if that is the case here it will merge itself as soon as the prerequisite lands, and you will see a comment saying so. Manual resolution is only needed while the conflict persists.

Troubleshooting

If the conflicts were resolved in a wrong way

If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:

  • delete the pr-cherrypick label from the PR
  • delete this branch from the repository

You also need to check the Original pull-request for pr-backports-created label, and delete if it's presented there

The PR source

The PR is created in the CI job

groeneai and others added 12 commits August 4, 2026 16:51
…bcolumnsPass

IStorage::supportsOptimizationToSubcolumns reads like a flag, but wrapper storages
answer it by traversing what they wrap. StorageMerge overrides it with a full
traverseTablesUntil over every child table (added by b2be878, PR #109188),
traverseTablesUntilImpl re-creates the database iterators on every invocation, and
DatabaseTablesSnapshotIterator holds the table map by value, so each call also copies
it.

FunctionToSubcolumnsPass reads that predicate from getTypedNodesForOptimization and
getTypedNodesForChainedOptimization, which are reached from four per-query-tree-node
call sites, and it reads it before the function name is consulted (the name check
happens later in enterImpl). A query with N function nodes over a Merge table with T
children therefore paid N traversals of T tables even when no function is rewritable.
The rewritable set is 13 names and includes neither position nor multiIf, so the
merge_table_large_query perf test (1504 position calls over 500 children) performed
roughly 750k child visits for a rewrite that can never fire. Analysis became
O(query-tree nodes x child tables) where it used to be O(nodes).

The answer is a property of the storage, so this memoizes it in an
unordered_map<const IStorage *, bool> held by each visitor, i.e. for the lifetime of
one pass run. TableNode holds the StoragePtr by value and no updateStorage caller runs
inside a query tree pass, so the key cannot be recycled mid-run; nothing is cached
across queries or DDL, so there is no invalidation story. All twelve carriers of the
predicate are pure reads of storage configuration, so only the number of computations
changes, never the answer.

Measured on one Debug binary with the perf test's own fixture, flipping
optimize_functions_to_subcolumns (QueryAnalysisMicroseconds, medians of 5 interleaved
runs): before, 90807 us with the pass off vs 403557 us with it on (4.44x); after,
99388 vs 99853 (1.005x). The same query over a plain MergeTree does not move on either
build (1.07x / 1.02x), and the query result is byte-identical in all four cells. A
28-cell matrix over Array, Nullable, LowCardinality, LowCardinality(Nullable), Map,
Tuple, String, empty array and count(), against both a supporting and an opting-out
Merge, is identical on both builds.

The new stateless test asserts that the memoized answer equals a fresh one on both the
supporting and the fail-closed arm, including two storages whose answers differ within
one query, an empty match set, and a Merge over a Merge. Because it is a
semantics-preservation test it is green with and without this change, so its liveness
was established by mutation: a mutant that ignores the cache key and a mutant that
always reports support are both caught.

DistanceTransposedPartialReadsPass reads the same predicate per node but checks the
function name first, requires a UInt64 constant precision, and is gated on
optimize_qbit_distance_function_reads, so it cannot exhibit this blow-up and is left
alone. Not copying the table map in DatabaseTablesSnapshotIterator would help all
traverseTablesUntil callers, but it changes a documented snapshot semantic in every
database engine and is a separate concern.

PR #109188 was backported to 26.6.2, so 26.6.2+ and 26.7+ carry the regression.

Closes #113202.
Every assertion in this test is built on EXPLAIN QUERY TREE, which is
rejected with NOT_IMPLEMENTED when the analyzer is disabled. The test had
no explicit SET, so it inherited the server profile and failed 3 out of 3
reruns in the `old analyzer` stateless job, where tests/config/users.d/
analyzer.xml sets allow_experimental_analyzer to 0.

A test-level SET wins over that profile default, which is what 83 of the
90 stateless .sql tests using EXPLAIN QUERY TREE already do. The oracle is
unchanged: with the analyzer forced on under the old-analyzer server
config, the output is byte-identical to the analyzer-on run and matches
the reference, and flipping optimize_functions_to_subcolumns off under the
same config still reddens five assertions, so the memoized-equals-fresh
contract is still what is being measured.

Co-Authored-By: Claude Fable 5 <[email protected]>
Master restructured the predicate read in FunctionToSubcolumnsPass into
storageAllowsTransformer, which now consults two storage predicates:
supportsOptimizationToSubcolumns and, as a narrower fallback for tuple
element access, supportsOptimizationToTupleElementSubcolumns. Both are
full child traversals on StorageMerge, so the memo now caches both
answers per storage instead of only the first, keeping the whole
predicate read off the per-node path.

The second answer is computed lazily: a storage that allows every
transformer never pays for it, which matches the short-circuit order of
the function master introduced. Master's rename of the returned table
node to column_source and its TableExpressionNodePtr signature are taken
as-is; the cache is threaded through as an extra argument.
The comment named only supportsOptimizationToSubcolumns; the cache now
also holds the tuple-element answer.
A File storage refuses every transformer except tuple element access, so
its two support predicates disagree. Nothing in the test covered that
split: a cache that stored the final storageAllowsTransformer result
instead of the two answers passed the whole file, while it rewrote
length() on a File in one node order and dropped the tuple element
rewrite in the other. The new assertions run both orders in one query
and fail on that mutation.
The branch was 27.9 days behind and conflicted in
src/Analyzer/Passes/FunctionToSubcolumnsPass.cpp.

One conflict region, in FunctionToSubcolumnsVisitorFirstPass::enterImpl.
Master added a chained_pattern_inner_nodes guard that returns early for nodes
which are inner parts of an already-matched chained pattern, so that inner
functions in multi-level chains are not counted twice. My side had changed the
same lines only to thread the memoization cache into
getTypedNodesForOptimization. I kept master's guard verbatim and re-applied the
cache argument on top of it, rather than restoring my older copy of the
surrounding code.

Re-checked that the cache key is still correct after master's rework of this
file (the file grew from 1300 to 1601 lines, and canOptimizeToExpectedSubcolumn
gained a column context). The call-site topology is unchanged: the same four
getTypedNodes* call sites, the same two storageAllowsTransformer call sites, and
storageAllowsTransformer still has no caller outside this pass, so a cache held
per visitor cannot outlive the answers it stores. TableNode still owns both
StoragePtr and TableLockHolder, so every keyed storage still outlives the pass
and a raw IStorage * key cannot dangle or be recycled into a false hit. Master
has not memoized this predicate itself, so the change is still needed.
The branch was 14 days behind and conflicted in
src/Analyzer/Passes/FunctionToSubcolumnsPass.cpp.

Master changed storageAllowsTransformer to take the column's IDataType instead
of its TypeIndex, so that a tupleElement over a Nullable(Tuple) column is
treated as a tuple element too (isTuple(removeNullable(type))). My side had
added the per-visitor memoization cache to the same function and to its two
call sites. I kept master's signature and type check verbatim and re-applied
the cache on top of them. The second pass also gained master's
correlated_columns member next to the cache member; both are kept.

The cache key is still sound after master's changes: the only change to an
overrider of the two predicates since the previous merge is StorageHive, which
now returns constants; the wrapper storages (Merge, Buffer, MaterializedView,
Alias, Proxy) delegate exactly as before; TableNode still owns StoragePtr and
TableLockHolder; and every TableNode::updateStorage caller (materialized CTE
finalize/adopt, CTE and recursive CTE substitution) runs during query analysis
or execution, never inside a FunctionToSubcolumnsPass run. Master still does
not memoize this predicate, so the change is still needed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The two member comments restated what the declaration already says, so they
are removed. The comment on SubcolumnSupportAnswers is shortened to one line.
The detail it dropped is that StorageMerge answers each predicate by walking
every child table, and that is why an uncached probe per query tree node made
analysis over a Merge table O(nodes x children).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Master added tupleElementNameIsOrdinalOnly, which asks the storage
supportsOptimizationToSubcolumns() for every tupleElement over an unnamed
tuple that the second pass rewrites. Over a Merge table that is a traversal
of every child table per rewritten node, so a query with many positional
tuple element accesses still paid O(nodes x children) analysis time.

The check now reads the same per-visitor answer as storageAllowsTransformer.
ColumnContext carries a reference to the second visitor's cache, and the
find-or-emplace lookup moves into getSubcolumnSupportAnswers, shared by both
call sites. Each storage is still keyed by its own pointer, so the answer
stays per storage, and the check can no longer disagree with the answer the
same pass already used to allow the rewrite.

Measured on a Debug build, Merge over 500 MergeTree children, 200
`t.1 + k` projections over an unnamed Tuple, QueryAnalysisMicroseconds median
of 5 interleaved runs, optimize_functions_to_subcolumns on vs off:
before 26432 vs 7859 us (3.36x), after 8342 vs 8656 us (0.96x). The
`position(s, k)` query of the original report is unchanged (1.05x / 1.07x).

04692 gains an unnamed tuple case: a MergeTree and a File storage in one
query, in both orders, where only the MergeTree side may be rewritten. It
fails when only this check is made to share one answer across storages, while
every older line of the test still passes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Picks up #122659, which fixes the 04633_async_insert_select_late_bound_catalog
wait timeout that failed this PR's last CI run. No conflicts; the PR's own
change (FunctionToSubcolumnsPass.cpp and the 04692 test) is unchanged.
…ns-support-memo

Memoize supportsOptimizationToSubcolumns in FunctionToSubcolumnsPass
@robot-ch-test-poll robot-ch-test-poll added pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only! do not test disable testing on pull request labels Oct 10, 2026
@groeneai

Copy link
Copy Markdown
Collaborator

All conflicts are in FunctionToSubcolumnsPass.cpp and come from three master PRs that are not on 26.8 and have no backport label, so the bot's retry will not clear them:

Nothing from those PRs is imported. The new test merges cleanly.

What I checked:

  • git diff backport/26.8/113367 <resolution> touches the same 3 files as Memoize supportsOptimizationToSubcolumns in FunctionToSubcolumnsPass #113367, with the same added and removed lines except the 4 that keep 26.8's TypeIndex form, plus one blank line.
  • A Debug build of the resolved tree with clang-22 (the 26.8 toolset): 04692_functions_to_subcolumns_merge_support passes 50/50 with randomized settings and 50/50 without. Of the subcolumn and Merge tests, 350 pass, 5 are skipped, and 11 need ZooKeeper, S3 or test clusters missing from my local config; those 11 fail the same way on a build without the change.
  • EXPLAIN QUERY TREE of the merge_table_large_query perf test query over its 500-table Merge takes about 0.17 s instead of 1.1 s on the same build without the change, and prints an identical tree.
  • The resolution's first parent is cea47f5faf9f, this PR's head, so applying it is a fast-forward.

@fm4v, I have triage but not push on this repository, so I cannot update cherrypick/26.8/113367 myself. Applying it takes two commands:

git fetch https://github.com/groeneai/ClickHouse resolve-26.8-cherrypick-113367
git push origin FETCH_HEAD:cherrypick/26.8/113367

After that the robot merges this PR and opens the 26.8 backport PR itself.

@robot-ch-test-poll2

Copy link
Copy Markdown
Contributor

Dear @vdimir, @groeneai, this cherry-pick PR has not been updated for 3d0h3m22s. Please resolve the conflicts to backport #113367, or close this PR if the backport is no longer needed. This PR will be automatically closed after 7 days of inactivity.

@vdimir

vdimir commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

@groeneai resolve conflicts please

@groeneai

Copy link
Copy Markdown
Collaborator

I don't have push access to this repository, so I can't update cherrypick/26.8/113367 myself. The resolution is on my fork and is still a fast-forward of this PR's head (cea47f5faf9f, and backport/26.8/113367 is unchanged at 7e6a0a402398). What it keeps and drops is in my comment above. To apply it:

git fetch https://github.com/groeneai/ClickHouse resolve-26.8-cherrypick-113367
git push origin FETCH_HEAD:cherrypick/26.8/113367

The 26.9 cherry-pick #125100 has the same at resolve-26.9-cherrypick-113367 (push to cherrypick/26.9/113367). The bot will close that one tonight after 7 days of inactivity.

@robot-ch-test-poll4

Copy link
Copy Markdown
Contributor

Dear @vdimir, @groeneai, this cherry-pick PR has not been updated for 7d0h1m49s. Closing automatically. If you still want to backport #113367, please resolve the conflicts and reopen this PR.

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

Labels

do not test disable testing on pull request pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only!

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants