Repository navigation
Cherry pick #113367 to 26.8: Memoize supportsOptimizationToSubcolumns in FunctionToSubcolumnsPass - #125099
Cherry pick #113367 to 26.8: Memoize supportsOptimizationToSubcolumns in FunctionToSubcolumnsPass#125099robot-ch-test-poll wants to merge 12 commits into
Conversation
…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
|
All conflicts are in
Nothing from those PRs is imported. The new test merges cleanly. What I checked:
@fm4v, I have After that the robot merges this PR and opens the 26.8 backport PR itself. |
|
@groeneai resolve conflicts please |
|
I don't have push access to this repository, so I can't update The 26.9 cherry-pick #125100 has the same at |
7e6a0a4 to
ccdf2d5
Compare
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-picklocally.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:
pr-cherrypicklabel from the PRYou also need to check the Original pull-request for
pr-backports-createdlabel, and delete if it's presented thereThe PR source
The PR is created in the CI job