Repository navigation
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 ClickHouse#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 ClickHouse#109188 was backported to 26.6.2, so 26.6.2+ and 26.7+ carry the regression. Closes ClickHouse#113202.
Internal second-model review (1 finding, adjudicated)An independent model reviewed this change cold against the PR contract. My own cold
|
Pre-PR validation gate (click to expand)
|
|
cc @vdimir @tavplubix, could you review this? |
|
Workflow [PR], commit [396d64a] Summary: ✅
AI ReviewSummaryThis PR memoizes per-storage subcolumn-capability probes inside Final Verdict✅ No blocking issues found. LLVM Coverage ReportMeasured on commit 396d64a.
Changed lines: Changed C/C++ lines covered: 60/61 (98.36%) · Uncovered code |
|
📊 Cloud Performance Report ✅ AI verdict: This PR caches storage-capability answers (supportsOptimizationToSubcolumns / supportsOptimizationToTupleElementSubcolumns) inside FunctionToSubcolumnsPass. That only matters for wrapper storages such as Merge that are visited from many nodes in one query. ClickBench Q30 (-14.4%) and Q31 (-11.1%) read a plain MergeTree table and contain no functions this pass rewrites. The check runs once at query analysis and takes microseconds, while CPU time fell only about 2-3% against a 30 ms wall-time drop. Both improvements are downgraded to not_sure, and this PR should be treated as having no measurable effect on query execution in these benchmarks. clickbenchFlagged queries (2 of 43)
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
|
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]>
CI finish ledger - 0fb1827Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Not caused by this PR. The diff is the memoization in Session id: cron:our-pr-ci-monitor:20260805-073000 |
|
Ledger correction for the That row named #107957 as the fixing PR. #107957 is now closed as superseded, so the owner for this signature is #113534, which fixes the same abort at the planning layer instead. I verified it against pristine master Nothing else in the ledger changes, and this failure remains unrelated to this PR. |
|
Fixing PR for the The stall is not a build error. apt's |
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.
CI finish ledger — c1d6804Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260817-210000 |
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.
|
Merged master to clear the conflict (the branch was 27.9 days behind). One conflict region, in Since the open question on this PR is whether keying the cache on the outer One thing I noticed and did not change: master's new Validation on the merged head: |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 12 s compile time in total, 7 of them have a recent master baseline. |
CI finish ledger -
|
| Check / test | Reason | Owner / fixing PR |
|---|---|---|
Stress test (amd_msan) / MemorySanitizer: use-of-uninitialized-value (STID: 0250-1463) |
not PR-caused, trunk defect in the sequenceMatch pattern matcher: backtrackingMatch bound-checks action_it only on loop entry (AggregateFunctionSequenceMatch.cpp:551-560), then increments and dereferences it, so a pattern whose trailing actions are all satisfiable at zero length (KleeneStar, TimeLessOrEqual, TimeLess, TimeGreaterOrEqual with extra == 0) reads one element past the end of the parsed pattern. The diff on this branch is FunctionToSubcolumnsPass.cpp plus its own 04692 test and cannot reach an aggregate function state machine. The same signature fired at unrelated heads on two other pull requests within the last 30 days (3 rows, 3 distinct pull requests, 0 on master), which places it in trunk rather than in this diff. |
#119871 (mine, open) |
#119871 is the remedy for this exact signature rather than a same-area coincidence: it rewrites the
loop at AggregateFunctionSequenceMatch.cpp:548-563, the frame MSan names in this report, and it
carries a stateless regression test for the trailing zero-length actions that trigger it.
Mergeable Check and PR are red only as the aggregate of that single job ("Failed: Stress test
(amd_msan)"), so they carry no separate owner. Nothing else failed at this head: 159 of 176
check-runs pass, 14 are skipped, and Config Workflow, Fast test, Style check, CH Inc sync
and Finish Workflow are all green.
Session id: cron:our-pr-ci-monitor:20260914-173053
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]>
CI finish ledger - 58977e1Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
All 146 check runs completed (109 passed, 35 not selected, 2 red) and Session id: cron:our-pr-ci-monitor:20260928-200457 |
Picks up ClickHouse#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.
CI finish ledger - 6b615deEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
146 of 146 check runs completed (110 passed, 35 not selected, 1 red: the shard above), Session id: cron:our-pr-ci-monitor:20260929-023049 |
Closes: #113202
Related: #109188
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Analysis of a query over a
Mergetable no longer traverses every child table for each query-tree node whenoptimize_functions_to_subcolumnsis enabled. The answer is now reused across the query tree, so analysis time grows with the query size plus the number of child tables instead of their product. Closes #113202.Description
IStorage::supportsOptimizationToSubcolumnsreads like a flag, butStorageMergeanswers it with a fulltraverseTablesUntilover every child (added in #109188), re-creating the database iterators and copying the table map per call.FunctionToSubcolumnsPassreads that predicate from two helpers reached from four per-query-tree-node call sites, before consulting the function name. A query with N function nodes over aMergewith T children therefore pays N traversals of T tables even when nothing is rewritable.positionis not rewritable, somerge_table_large_query(1504positioncalls, 500 children) paid ~750k child visits for nothing.The answer is a property of the storage, so both predicates (
supportsOptimizationToSubcolumnsandsupportsOptimizationToTupleElementSubcolumns) are memoized perconst IStorage *on each visitor. Every probe in the pass reads that memo, includingtupleElementNameIsOrdinalOnly, which asked the storage again for each positionaltupleElementthe second pass rewrote.TableNodepins theStoragePtrand noupdateStoragecaller runs inside a pass, so the key cannot go stale, and nothing is cached across queries or DDL. Every override of the two predicates is a pure read of table configuration, so only the number of computations changes.Measured on one Debug binary with the perf test's fixture by flipping
optimize_functions_to_subcolumns(QueryAnalysisMicroseconds, medians of 5 interleaved runs): before 90 807 off vs 403 557 on (4.44x); after 99 388 vs 99 853 (1.005x). A plainMergeTreedoes not move, and results are byte-identical in all four cells. A positionalt.1 + kquery (200 projections, 500 children) goes from 3.36x to 0.96x. A new stateless test asserts the memoized answer matches a fresh one on the supporting and fail-closed arms, including two storages that disagree within one query.Left alone:
DistanceTransposedPartialReadsPass(name-checked first and setting-gated) and theDatabaseTablesSnapshotIteratorcopy (a documented snapshot semantic). #109188 is in 26.6.2+ and 26.7+. Root cause reported by @ egor-click.Workflow [PR]
Sync PR [sync-upstream/pr/113367]
Version info
26.10.1.1173-master(included in26.10and later)