Skip to content

Memoize supportsOptimizationToSubcolumns in FunctionToSubcolumnsPass - #113367

Merged
vdimir merged 11 commits into
ClickHouse:masterfrom
groeneai:groeneai-fix-113202-subcolumns-support-memo
Oct 1, 2026
Merged

vdimir merged 11 commits into
ClickHouse:masterfrom
groeneai:groeneai-fix-113202-subcolumns-support-memo

Conversation

@groeneai

@groeneai groeneai commented Aug 4, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #113202
Related: #109188

Changelog category (leave one):

  • Performance Improvement

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

Analysis of a query over a Merge table no longer traverses every child table for each query-tree node when optimize_functions_to_subcolumns is 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::supportsOptimizationToSubcolumns reads like a flag, but StorageMerge answers it with a full traverseTablesUntil over every child (added in #109188), re-creating the database iterators and copying the table map per call.

FunctionToSubcolumnsPass reads 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 a Merge with T children therefore pays N traversals of T tables even when nothing is rewritable. position is not rewritable, so merge_table_large_query (1504 position calls, 500 children) paid ~750k child visits for nothing.

The answer is a property of the storage, so both predicates (supportsOptimizationToSubcolumns and supportsOptimizationToTupleElementSubcolumns) are memoized per const IStorage * on each visitor. Every probe in the pass reads that memo, including tupleElementNameIsOrdinalOnly, which asked the storage again for each positional tupleElement the second pass rewrote. TableNode pins the StoragePtr and no updateStorage caller 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 plain MergeTree does not move, and results are byte-identical in all four cells. A positional t.1 + k query (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 the DatabaseTablesSnapshotIterator copy (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

  • Merged into: 26.10.1.1173-master (included in 26.10 and later)

…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.
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (1 finding, adjudicated)

An independent model reviewed this change cold against the PR contract. My own cold
review ran first and separately. One finding, plus three of my own nits.

⚠️ The new stateless test does not observe memoization (major) - DISAGREE

The factual half is right and the commit message already says it: 04692 is a
semantics-preservation test, green with and without this change, and its liveness rests
on mutation testing (a mutant that ignores the cache key and a mutant that always
reports support are both caught). What I disagree with is the conclusion that the
Performance Improvement contract is therefore unguarded.

The guard already exists upstream, and it is the metric that flagged this regression:
tests/performance/merge_table_large_query.xml - 501 create_query, one 77 719-byte
query with 1504 position calls over ENGINE = Merge(currentDatabase(), '^merge_perf_t').
It runs on a change of this shape: ci/workflows/pull_request.py:186 includes the
performance-comparison jobs unconditionally, and PRs touching only src/ and
tests/queries/ do produce its rows (checked three recent ones). Over the last 7 days
it reported 2847 success and 3 unstable per arm, so it is live rather than dormant.

Both suggested remedies are weaker than that. Deterministic call-count instrumentation
does not exist to reuse - there are no ProfileEvents in StorageMerge.cpp or in the
getDatabaseIterators path, and the reporter's own probe shows ContextLock is flat
across the two releases (1048 = 1048), so no existing counter tracks the traversal;
adding one purely for test observability is a production change for a test's benefit.
A wall-clock analysis-time benchmark inside a stateless test is the shape of
04053_merge_table_large_query_performance: one sample per side against a ratio its own
comment calls "a loose 20x" (:190), which had one-sided-noise flakiness and needed
#104275 to stabilise - and a 20x threshold would not see the 4.44x analysis-phase ratio
this change is about.

So the split is deliberate: the upstream perf test owns the timing contract, and the new
stateless test owns the semantics contract with mutation-proven liveness.

💡 My own nits

  • The helper's lead comment says the answer is memoized "for the lifetime of one pass
    run"; each visitor holds its own cache, so per-visitor is the exact scope. The two
    member comments beside the fields say so, and one pass run is a correct upper bound,
    so this is left as written.
  • Title shortened to 68 characters before publishing. The commit subject is unchanged
    (no amend on a branch).
  • I withdrew one of my own nits on re-derivation: the exact count() = 1 assertion in
    the two-storage case looked brittle next to the count() > 0 arms, but it is the only
    assertion that can catch a key-ignored cache, so exactness is the point.

Verdicts: 2 AGREE (both nits, one fixed here), 1 DISAGREE with evidence, 1 dropped.

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On one Debug binary, run the merge_table_large_query fixture (500 MergeTree children + Merge, 1000 rows) and flip optimize_functions_to_subcolumns 1/0, reading QueryAnalysisMicroseconds from system.query_log. Unpatched: 403 557 vs 90 807 us (4.44x), 5 interleaved rounds per arm. Not a rate, reproducible on demand.
b Root cause explained? Yes. StorageMerge::supportsOptimizationToSubcolumns answers by traverseTablesUntil over every child, re-creating the database iterators per call while DatabaseTablesSnapshotIterator copies the table map. FunctionToSubcolumnsPass reads that predicate from two helpers at four per-query-tree-node call sites, and reads it before the function-name check, so N function nodes over T children cost N traversals of T tables. position is not rewritable, so all 1504 nodes paid for a rewrite that cannot fire: O(nodes x children) instead of O(nodes).
c Fix matches root cause? Yes. It memoizes exactly the predicate identified in (b) for the lifetime of one pass run. No widened bound, no no-random-* tag, no reduced dataset, no defensive guard; the traversal itself is unchanged, only its repetition count.
d Test intent preserved / new tests added? Yes. No existing test weakened. One new stateless test with six assertions (mixed rewritability, opting-out File child, two storages that disagree in one query in both orders, empty match set, nested Merge). It is a semantics-preservation test, so its liveness was proven by mutation rather than assumed: mutant "cache ignores the key" and mutant "cache always true" are both caught. The first version of the test did NOT catch the key mutant (single-storage cases make a wrong key unobservable), which is why the two-storage assertion exists. 02346_text_index_bug108874 remains the fail-closed arm and passes.
e Both directions demonstrated? Yes. Same probe on both binaries, Build IDs verified live via SELECT buildId(): unpatched 4.44x, patched 1.005x (99 388 vs 99 853). Query result byte-identical in all four cells (md5 56abc147...). Must-not-move control (same query over a plain MergeTree) stays at 1.07x/1.02x on both builds.
f Fix is general across code paths? Yes. All 12 carriers of the predicate enumerated by grep this run (IStorage, StorageMerge, StorageBuffer, StorageMaterializedView, StorageProxy, StorageAlias, and six constant-false storages); every one is a pure read of storage configuration, so memoizing cannot change an answer. Both helpers and all four call sites converted, leaving no raw read in the pass. DistanceTransposedPartialReadsPass is the only other consumer and is deliberately excluded: it checks the function name first, needs a UInt64 constant precision, and is setting-gated, so it cannot exhibit this blow-up.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, measured. A 28-cell matrix (14 expressions x {Merge over MergeTree, Merge with an opting-out File child}) covering Array, Nullable(String), LowCardinality(String), LowCardinality(Nullable(String)), Map, Tuple, String, empty array and count(), run on both binaries against the identical fixture with the live buildId() asserted per arm: all 28 cells identical. LowCardinality and count() answer "not rewritten" on both builds, which is pre-existing behavior and untouched here.
h Backward compatible? (maintainer-approved exception only) Yes, trivially. No setting added or defaulted differently, so no SettingsChangesHistory.cpp entry is required; no serialization, format, ABI or protocol change; no new experimental surface. Observable behavior is identical (see e, g).
i Invariants and contracts preserved? Yes. The cache is read at exactly the two points where the raw predicate was read, so every early return in both helpers is unchanged. The key is a const IStorage * that TableNode pins for the whole pass, and no updateStorage caller runs inside a query-tree pass, so it cannot be recycled mid-run. Each cache is a non-static visitor member, constructed in run() and visited single-threaded, so there is no sharing and no static state. emplace may throw bad_alloc, which propagates like any other allocation in the pass. Recursion for a Merge over a Merge happens inside the child's own check, below the memo, so it is unaffected.

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @tavplubix, could you review this? StorageMerge::supportsOptimizationToSubcolumns answers by traversing every child table, and FunctionToSubcolumnsPass read it once per query-tree node before checking the function name, so analysis over a Merge became O(nodes x children); this memoizes the answer per storage for one pass run, which is safe because every implementation of that predicate is a pure read of storage configuration and TableNode pins the StoragePtr for the whole pass.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [396d64a]

Summary: ✅


AI Review

Summary

This PR memoizes per-storage subcolumn-capability probes inside FunctionToSubcolumnsPass, including the unnamed-Tuple ordinal check, and extends the stateless coverage to mixed-capability and nested Merge cases. I did not find a new correctness, compatibility, or test-coverage issue in the current head; the previously open concern about wrapper-storage races reduces to the same advisory, unsynchronized capability sampling that StorageMerge already accepts for other planner decisions, so I did not keep it as an open finding.

Final Verdict

✅ No blocking issues found.

LLVM Coverage Report

Measured on commit 396d64a.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.60% 79.60% +0.00%

Changed lines: Changed C/C++ lines covered: 60/61 (98.36%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 30 not_sure 229 196 -14.4% <0.0001 aggregation: This PR only caches storage capability checks in an analyzer pass that runs once per query and costs microseconds on MergeTree. It cannot remove 33 ms from a GROUP BY scan, and CPU time barely moved.
⚠️ 31 not_sure 271 241 -11.1% <0.0001 aggregation: This query has no subcolumn-rewritable functions, and the changed analyzer check is a trivial call on MergeTree. A -11.1% wall-time drop with only about 3% less CPU does not come from this 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: a3694c63-69f7-4551-8599-aaacfc4b1c5f
  • MIRAI run: 0f929757-f095-4968-bfac-25b50a2bf3ae
  • PR check IDs:
    • clickbench_2559362_1790789346
    • clickbench_2559368_1790789346
    • clickbench_2559380_1790789347
    • tpch_adapted_1_official_2559391_1790789345
    • tpch_adapted_1_official_2559418_1790789345
    • tpch_adapted_1_official_2559432_1790789345

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]>
@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0fb1827

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (arm_debug) / Logical error: '(isConst() || isSparse() || isReplicated() || rhs.isConst() || rhs.isSparse() || rhs.isReplicated()) ? getDataType() == rhs.getDataType() : typeid(*this) == typeid(rhs)' (STID 2508-2e0c) Trunk bug in HashJoin. Frame-verified as the known family rather than a same-code lookalike: IColumn.h:941 assertTypeEquality <- inlined IColumn.h:255 insertFrom <- HashJoinMethodsImpl.h:807 buildAdditionalFilter <- :997 joinRightColumnsWithAdditionalFilter (JoinKind 1 / JoinStrictness 2) <- SpillingHashJoin.cpp:312. Breadth 26 rows / 25 distinct unrelated PRs / 1 master run in 30d #107957 (mine, open)
Docker server image Infra stall, and a hang rather than a build error: the arm64 leg entered the apt-get update layer at 01:49:28Z, emitted its last apt line at 01:51:57Z, then produced no output for 4h36m until the 18000s job cap fired (exit code [-15]). Breadth 2 rows / 1 PR (this one) / 0 master in 30d against 119100 successes a fix task is created (investigating at full effort - fixing-PR link to follow here)
Build (arm_release) / Post Hooks The build_profile_hook telemetry INSERT INTO build_time_trace gets HTTP 500 from LogCluster. The check's own check_status is success and the hook is non-gating a fix task is moved to pending (investigating at full effort - fixing-PR link to follow here)

Not caused by this PR. The diff is the memoization in FunctionToSubcolumnsPass.cpp plus one added SET
line in a stateless test. No frame of it appears in the HashJoin abort; nothing in it can reach a
Dockerfile apt layer or the build-profile telemetry hook.

Session id: cron:our-pr-ci-monitor:20260805-073000

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

Ledger correction for the IColumn::assertTypeEquality row above (HashJoin::buildAdditionalFilter, HashJoinMethodsImpl.h:807).

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 2169bf5d402de64: the failing dictionary shapes abort without it and return correct results with it.

Nothing else in the ledger changes, and this failure remains unrelated to this PR.

@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Docker server image row of the CI finish ledger above: #113869

The stall is not a build error. apt's Acquire::http::Timeout is an inactivity timeout, so a mirror that keeps trickling bytes is never bounded by it, and the retry already configured for these builds could never fire because the command never returns. Each docker buildx invocation is now bounded by GNU timeout, with the deadline shrinking so the whole job stays inside its own cap.

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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — c1d6804

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (arm_asan_ubsan) / UndefinedBehaviorSanitizer STID 3587-3c65 UBSan float-to-Int64 overflow at WorkloadSettings.cpp:366 on a huge max_concurrent_threads_ratio_to_cores; trunk bug, 4 unrelated PRs in 30 days, 0 on master; this branch touches only FunctionToSubcolumnsPass.cpp plus its own new 04692 test #113206 (ours, open)
Build profile diff Job died in praktika's own auth step (runner.py:321 GH auth failed - required by job) after 23 s, before any build comparison; job-level only, no test ran. Trunk-wide: 96 error rows across 70 distinct PRs today alone Investigated and closed without a code change; refutation and one disclosed residual in #113939 (comment)

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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master to clear the conflict (the branch was 27.9 days behind). One conflict region, in FunctionToSubcolumnsVisitorFirstPass::enterImpl: master added the chained_pattern_inner_nodes early return, and my side had touched the same lines only to pass the memoization cache into getTypedNodesForOptimization. I kept master's guard verbatim and re-applied the cache argument on top of it, so nothing of master's new work is reverted here.

Since the open question on this PR is whether keying the cache on the outer IStorage * is sound, I re-checked that against master's reworked file (it grew from 1300 to 1601 lines, and canOptimizeToExpectedSubcolumn gained a column context). The three things the key depends on are unchanged: the call-site topology is identical (the same four getTypedNodes* sites and two storageAllowsTransformer sites), storageAllowsTransformer still has no caller outside this pass, and TableNode still owns both StoragePtr and TableLockHolder, so every keyed storage still outlives the pass. Master has not memoized this predicate itself, so the change is still needed.

One thing I noticed and did not change: master's new tupleElementNameIsOrdinalOnly probes supportsOptimizationToSubcolumns() uncached for unnamed tuples, so positional tupleElement does not benefit from this cache. That is master's own path rather than something this PR regresses, and I have no before/after measurement for caching it, so I left it alone rather than widening ColumnContext here. Happy to do it in a follow-up if you would like it.

Validation on the merged head: 04692_functions_to_subcolumns_merge_support 50/50 with randomization active (90 to 101 settings per query), and 266 of the subcolumn/tuple_element/map_contains tests pass. The only failures in that suite need servers on 127.0.0.2 and 127.0.0.3, which my sandbox does not bind, and none of them reports an output mismatch.

@clickhouse-gh

clickhouse-gh Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 396d64a7e with master 120be6b5f (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 8dc18243e; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

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.

Compile time of recompiled translation units

7 translation units recompiled, 12 s compile time in total, 7 of them have a recent master baseline.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 28ee85ec4abdb251b671c366c3f0b8aa566a685d

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

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.

Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=113367&sha=28ee85ec4abdb251b671c366c3f0b8aa566a685d&name_0=PR&name_1=Stress%20test%20%28amd_msan%29

Session id: cron:our-pr-ci-monitor:20260914-173053

groeneai and others added 3 commits September 28, 2026 12:24
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]>
@groeneai
groeneai requested a review from egor-click September 28, 2026 13:57
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 58977e1

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_debug, parallel) / 04633_async_insert_select_late_bound_catalog flaky: Timeout waiting for query insert_case1_... to start, and the runner's rerun with the same randomized settings passed 11 of 11. This PR does not touch async inserts. In 30 days the test failed on one other pull request (today) and on no master run #122659 (mine, merged 2026-09-28 15:48Z): wait_for_query_to_start now stops waiting once the insert has already exited. It is absent from the tree this job built (2259b7cecf8a), so I will merge master to pick it up
Performance Comparison (amd_release, master_head, 3/6) / join_main_loop #11 dashboard confirmed_regression, client_time 0.070 -> 0.151 s (+116.9%). The shard's own report calls #9, #10 and #11 slower, and all three reproduced after the harness restart. The query is a hash join of numbers_mt(1e8) with numbers_mt(1e5), so it has no subcolumn to rewrite, and this PR only caches a per-storage answer during query analysis. In 14 days #11 moved by more than 15% in 6 of 669 amd runs (this one included), 3 of them master-vs-master a fix task is created (its fix direction awaits a maintainer decision; fixing-PR link to follow on this PR)
Mergeable Check, PR rollups, red only because of the two rows above #122659 (mine, merged) owns the stateless row, and a fix task is created for the performance row
Sync - CH Inc sync (private, not actionable by me)

All 146 check runs completed (109 passed, 35 not selected, 2 red) and Finish Workflow is green.
CIDB has no other FAIL or ERROR test row on this head.

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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6b615de

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 4/6) / direct_dictionary #8 dashboard confirmed_regression, client_time 0.2926 -> 0.3379 s (+15.4%); the new server was slower in 7 of 7 samples. The shard's own report did not flag this query, so the harness restart never re-ran it (it re-ran only #7, which did not reproduce). The query calls dictGet with keys from rand64() and reads no column of system.numbers, so FunctionToSubcolumnsPass, whose storage check this PR memoizes, has nothing to rewrite in it. This slow mode is arm-only and belongs to the server process, not to one binary: #8 moved by more than 10% in 9 of 195 master-vs-master arm runs since 2026-09-16, against 3 of 310 before 2026-09-09, and in 0 of 605 amd runs since 2026-08-15 a fix task is created (its fix direction awaits a maintainer decision; fixing-PR link to follow on this PR)
Mergeable Check, PR rollups, red only because of the row above a fix task is created (the same one as for the row above)

146 of 146 check runs completed (110 passed, 35 not selected, 1 red: the shard above), Finish Workflow is green and CH Inc sync passed. The slower row on min_max_index_with_cast #0 in the green 3/6 shard does not fail a master_head shard. CIDB has no FAIL or ERROR test row on this head.

Session id: cron:our-pr-ci-monitor:20260929-023049

@vdimir
vdimir added this pull request to the merge queue Oct 1, 2026
Merged via the queue into ClickHouse:master with commit cea47f5 Oct 1, 2026
149 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 1, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 10, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 29, 2026
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). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.8-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

merge_table_large_query +33% — planning over Merge tables became O(nodes × child tables) in 26.7

7 participants