Skip to content

Support safe type conversions in correlated subquery equivalence substitution - #115493

Merged
vdimir merged 20 commits into
masterfrom
fix-correlated-substitution-types
Aug 31, 2026
Merged

vdimir merged 20 commits into
masterfrom
fix-correlated-substitution-types

Conversation

@novikd

@novikd novikd commented Aug 19, 2026 •

Copy link
Copy Markdown
Member

Closes: #113407
Related: #101863

Changelog category (leave one):

  • Performance Improvement

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

Correlated subqueries with an equality on columns that differ only in nullability (e.g. Int64 vs Nullable(Int64) under data_type_default_nullable = 1, as in TPC-DS Q35), or on native-number columns having a least common type (e.g. Int32 vs Int64), are now decorrelated via equivalent-expression substitution instead of falling back to a CROSS JOIN with a post-join filter, avoiding severe memory growth on such queries. Closes #113407.


Motivation

The equivalent-expression substitution in PlannerCorrelatedSubqueries recorded an equivalence only when both sides of the correlated equals had exactly the same type. A correlated EXISTS whose join condition compares Int64 with Nullable(Int64) therefore decorrelated through the CROSS JOIN fallback; at TPC-DS SF100 (Q35 with data_type_default_nullable = 1) the cross-joined intermediate grew without bound (35+ GiB and climbing before being killed, versus 1.72 s / 1.70 GiB with aligned column types).

Approach

The exact-type guard was load-bearing: correlated columns are PLACEHOLDER nodes typed with the outer column's type, and every decorrelated DAG declares that type for its inputs, so a substituted column of a different runtime type is a logical error during execution. The substitution therefore cannot simply alias a column of another type, nor cast to the common supertype — it must produce exactly the placeholder's type.

Equivalence classes now track (column name, type) pairs. The recording guard admits, besides equal types, two verified-safe families:

  • nullability-only differences (any base type) — the equality predicate rejects NULLs;
  • native-number pairs with a least supertype — for them equals is mathematically exact (9007199254740993 :: Int64 = 9007199254740992.0 :: Float64 is 0), the supertype exists only when every type embeds losslessly, and accurateCastOrNull is exactness-checking, so value equivalence is transitive across a class.

At substitution the chosen equivalent column is converted to exactly the correlated type: toNullable / lossless CAST when widening, assumeNotNull / accurateCastOrNull when narrowing. For the narrowing conversions a FilterStep is inserted below the renaming that drops rows whose value is NULL or does not convert exactly — such rows can never satisfy the recorded equality (a top-level AND-conjunct of an ancestor filter), and dropping them before assumeNotNull is required so that its arbitrary result for non-converting values cannot leak into aggregation keys (the aggregation decorrelation appends correlated identifiers as group keys).

Pairs whose comparison semantics are not consistent with CAST keep the previous CROSS JOIN fallback: Decimal vs Float (comparison converts to Float and is inexact), String vs FixedString (comparison ignores padding), and supertype-less numeric pairs such as Int64 vs UInt64 or Int64 vs Float64.

Substitution additionally applies only when the correlated column's sole uses inside the subquery (per UNION-arm scope) are the recorded equality conjuncts; any other expression over it would be evaluated on the substituted inner values — including rows that never match any outer value, so e.g. a division that is safe over the outer domain could throw — and therefore keeps the CROSS JOIN fallback.

Verification

  • The issue's reproducer plans with zero cross nodes and returns the same result as the fallback.
  • New stateless test 05023_correlated_subquery_equivalence_type_conversion (12 cases: both nullability directions, widening/narrowing/sideways/float numerics with adversarial boundary values, scalar-subquery aggregation with an outer 0 vs inner NULL, guarded fallbacks) passed 6/6 runs under harness setting randomization.
  • A cross-check over 16 type pairs compared EXISTS / NOT EXISTS / scalar count() results between substitution and the CROSS JOIN fallback on value pools with boundary values (2^31±1, 2^32±1, 2^53, 2^53+1, non-integer floats) and NULLs — identical everywhere, and plan probes confirmed the substitution fires exactly for the admitted pairs.
  • The existing correlated stateless subset passes (3 environment-only failures in the local scratch setup: MinIO, test cluster, writable access storage).

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

Version info

  • Merged into: 26.9.1.431 (included in 26.9 and later)

…titution

The equivalent-expression substitution in `PlannerCorrelatedSubqueries`
recorded an equivalence only when both sides of `equals` had exactly the same
type, so a correlated `EXISTS` whose equality columns differ only in
nullability (e.g. outer `Int64` vs inner `Nullable(Int64)` under
`data_type_default_nullable=1`, as in TPC-DS Q35) fell back to CROSS JOIN
decorrelation with severe memory growth.

Track column types in the equivalence classes and substitute across compatible
types: nullability-only differences (any base type) and native-number pairs
with a least supertype. The substituted column is converted to exactly the
correlated placeholder type (`toNullable`, `assumeNotNull`, lossless `CAST`,
or `accurateCastOrNull`), and rows whose value cannot match any outer value
are pre-filtered before the conversion. Pairs whose comparison semantics are
not consistent with `CAST` (`Decimal` vs `Float`, `String` vs `FixedString`,
`Int64` vs `UInt64`, `Int64` vs `Float64`, ...) keep the previous fallback.

Closes: #113407

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

clickhouse-gh Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [db2f9f6]

Summary: ✅


AI Review

Summary

This PR extends correlated-subquery equivalent-expression substitution across safe nullability and numeric conversions, adds several correctness guards around floats, Bool, and semantic type attributes, and backs that up with substantial stateless coverage. I found one remaining regression path: the new substitution branch can bypass the existing clear rejection for nested correlations that skip their immediate outer scope, so a cross-type variant now falls through to a later missing-column failure instead of the intended NOT_IMPLEMENTED.

Findings

⚠️ Majors

  • [src/Planner/PlannerCorrelatedSubqueries.cpp:464] Returning from the substitution path before the input_header->has(column) validation at lines 600-611 regresses deep-nested cross-type correlations from a clear unsupported-shape error into a late NOT_FOUND_COLUMN_IN_BLOCK. A 04502-style query where the innermost equality is newly substitutable (Nullable(UInt32) vs UInt32, or Int32 vs Int64) now fills expression_renamings here, skips the explicit scope check, and only fails later when buildLogicalJoin still tries to look up the skipped-scope identifier in the immediate outer header. Suggested fix: run the immediate-scope availability validation before both the substitution and CROSS JOIN branches, or otherwise prove that the substitution path can safely materialize skipped-scope identifiers for the final join.
Tests
  • ⚠️ Add a focused variant of 04502_correlated_subquery_deep_nested_reference where the innermost equality is one of the newly admitted cross-type pairs. That is the smallest regression test that proves this PR preserves the intended NOT_IMPLEMENTED for skipped-scope references instead of failing later in buildLogicalJoin.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: preserve the skipped-immediate-scope rejection on the substitution path for newly admitted type pairs, and add a regression test covering that deep-nested cross-type shape.

LLVM Coverage Report

Measured on commit db2f9f6.

Metric Baseline Current Δ
Lines 88.60% 88.60% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 80.90% 81.00% +0.10%

Changed lines: Changed C/C++ lines covered: 243/258 (94.19%) · Uncovered code

Full report · Diff report

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

clickhouse-gh Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing db2f9f6e6 with master bb113c384 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of d469feea5; 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.

Object file sizes

3 object files changed (+69.36 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Planner/PlannerCorrelatedSubqueries.cpp.o 320.46 KiB 389.81 KiB +69.35 KiB (+21.64%)

716 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

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

Job report

@clickhouse-gh

clickhouse-gh Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: e4a6f11e-86ce-4e2a-86c5-d80445abe33b
  • MIRAI run: 3dffc4e7-e201-481f-ab92-790ce5887926
  • PR check IDs:
    • clickbench_534373_1788145419
    • clickbench_534379_1788145419
    • clickbench_534385_1788145419
    • tpch_adapted_1_official_534396_1788145419
    • tpch_adapted_1_official_534408_1788145419
    • tpch_adapted_1_official_534445_1788145419

The execution-correctness cases checked only query results, which stay
correct through the CROSS JOIN fallback, so the test could not detect the
optimization silently not firing. Every admitted case now also asserts the
plan via step descriptions in `EXPLAIN PLAN actions = 1`: the renaming step
is present, and the NULL pre-filter step is present exactly for the
`assumeNotNull`/`accurateCastOrNull` conversions. The guarded fallback cases
assert that the renaming step is absent.

In the issue reproducer the pre-filter is pushed past the subquery join into
the `store_sales` Prewhere, so only the two-column probe is asserted there;
`query_plan_optimize_prewhere` and `optimize_move_to_prewhere` are pinned
because Prewhere relocation changes which step descriptions are visible.

Co-Authored-By: Claude Fable 5 <[email protected]>
@vdimir vdimir self-assigned this Aug 20, 2026
Restructure the test for readability: each case prints a header line, a
single probe line (`plan: cross_joins=N substituted=N null_prefiltered=N`)
proving from `EXPLAIN PLAN actions = 1` that the substitution step (and the
NULL pre-filter, exactly for the `assumeNotNull`/`accurateCastOrNull`
conversions) is present in the plan, and then the query results. The echoed
multi-line `countIf` probes are gone; tables and data are grouped with their
case. The three guarded pairs assert `substituted=0`.

Verified at the action level per case: `toNullable`, `assumeNotNull` (used
as the aggregation key in the scalar case), lossless `_CAST`, and
`isNotNull(accurateCastOrNull(...))` + `assumeNotNull` all appear, joined as
`Type: RIGHT, Strictness: SEMI` on the substituted column; with the setting
off the plan flips to the buffered decorrelation fallback.

Co-Authored-By: Claude Fable 5 <[email protected]>
novikd and others added 2 commits August 20, 2026 22:17
Address review feedback: `LowCardinality` and `Nullable` are value-transparent
wrappers whose comparison semantics are consistent with `CAST`, so the
recording guard and the substitution now classify on the base types
`removeNullable(removeLowCardinality(T))` (checked empirically:
`toLowCardinality('a') = 'a'` is exact, unlike the still-excluded
`FixedString`). This covers `LowCardinality(String)` vs `String`,
`LowCardinality(Nullable(T))` vs `T`, and LC-wrapped numeric pairs.

The five-value `ConversionRule` enum is replaced by a uniform conversion
pipeline: optional `accurateCastOrNull` to the correlated base type, optional
`assumeNotNull`, and a final lossless named `CAST` to the exact correlated
type (subsuming the former `toNullable` and lossless-cast rules). A comment
now documents why `assumeNotNull`/`accurateCastOrNull` are used instead of a
throwing `CAST`: merged filter+expression steps compute expressions on
not-yet-filtered rows, so conversions must not throw on rows the pre-filter
drops. The accurate-cast path now pre-filters also when the correlated type
is Nullable (always sound, uniform invariant).

Test extended with LC cases 16-21 (both string directions,
`LowCardinality(Nullable(String))`, LC-Nullable numeric widening in both
directions, guarded `LowCardinality(FixedString(2))`).

Co-Authored-By: Claude Fable 5 <[email protected]>
…pre-filter comment

Add scalar `count()` cases with an outer 0 and non-convertible inner values
(5000000000 through Int64 narrowing, 0.5/1.5 through the float-to-int cast):
the counts prove per row that non-convertible values are filtered out and
never fold into the default-valued aggregation key.

While validating the review comment, the pre-filter rationale in the code
turned out to be overstated: even without the pre-filter the retained
recorded-equality FilterStep sits between the conversion and any aggregation
and re-evaluates to false/NULL on exactly those rows, so no key corruption
could occur. The comment now states the actual invariant: the pre-filter
guarantees the assumeNotNull default values never exist in any downstream
step, independently of step merging, short-circuit settings, and other
expressions over the correlated column.

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

Address review feedback about signed zero: `equals` merges `-0.0` and `+0.0`
while hash joins and aggregation compare floats bitwise, so a reconstructed
float correlated column diverges from the non-substituted plan. Reproduced
two ways: outer `Float64` vs inner `Int32` loses the `-0.0` outer row at the
top-level hash join (the reconstructed `+0.0` does not match it), and outer
`Float64` vs inner `Nullable(Float64)` splits the scalar `count()` of the
zeros (bitwise grouping counts 1 where the fallback's `equals` counts 2).
Exact-type float substitution stays: there the fallback also converts the
equality into a bitwise hash-join key, so both plans agree.

`classifySubstitutionConversion` now rejects any non-exact conversion whose
correlated base is a float. Integer and string bases have unique value
representations and are unaffected; float member bases with an integer
correlated base remain allowed because `accurateCastOrNull` canonicalizes
`-0.0` to `0` (verified identical to the fallback).

Test: case 12 (outer `Float64` vs inner `Int32`) becomes a guarded case with
a `-0.0` row demonstrating the fallback semantics, case 11 gains an inner
`-0.0` that must match outer `0` through the accurate cast, and new case 24
pins the `Nullable(Float64)` count semantics (ordered by `toString(x)` —
the relative order of `-0.0` and `0.0` under a float ORDER BY is
comparator-dependent).

Co-Authored-By: Claude Fable 5 <[email protected]>
novikd and others added 2 commits August 24, 2026 12:03
The CI flaky check randomizes settings, and the combination
`query_plan_merge_filters = 0` with a non-default
`query_plan_optimize_join_order_limit` reorganizes the plan steps so the
step descriptions the test's plan probes match disappear (the substitution
itself still applies: the conversion actions are present, there is no cross
join, and the results stay correct). Pin both settings to their defaults,
like the already-pinned prewhere pair.

Verified by injecting the failing combinations via
`clickhouse-test --client-option`: the test reproduces the CI diff without
the pins and passes with them.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115493&sha=latest&name_0=PR
Related: #115493

Co-Authored-By: Claude Fable 5 <[email protected]>
Address review feedback: `Bool` passed the native-number guard (its type
index is `UInt8`), but `accurateCastOrNull` to `Bool` maps every non-zero
value to `true` instead of checking exactness. The claimed wrong result is
not reachable — the retained recorded equality re-evaluates
`equals(reconstructed, member)` numerically and drops the mismatched rows —
yet that made `Bool` the one admitted case whose correctness rested solely
on the retained-equality defense instead of a faithful conversion, so it is
excluded next to the float correlated bases. The member-side direction
stays: `CAST` from `Bool` to an integer is lossless.

Test: guarded case 25 (outer `Bool` vs inner `Int32` with an inner 2 that
must never count into `true`) and substituted case 26 (outer `Int32` vs
inner `Bool`, lossless, no pre-filter).

Related: #115493

Co-Authored-By: Claude Fable 5 <[email protected]>
@novikd
novikd added this pull request to the merge queue Aug 24, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Aug 24, 2026
novikd and others added 2 commits August 24, 2026 20:15
Master commit 76be7b5 taught `query_plan_merge_filter_into_join_condition`
to handle equalities with a common supertype — the same cross-type pairs the
correlated-subquery substitution targets — and the two changes first met in
the merge queue. No wrong results; two plan-semantics pins resolve it:

- `04654_merge_filter_into_join_condition_common_supertype` pins the fallback
  decorrelation shape its correlated section was written to verify, so the
  substitution is disabled for that section.
- `05023_correlated_subquery_equivalence_type_conversion` pins
  `query_plan_merge_filter_into_join_condition = 0`: merging a cross-type
  equality into a join condition makes the fallback compare floats bitwise,
  which would change the guarded cases' documented `equals` semantics (the
  case 12 `-0` row and case 24 zero counts) depending on a randomized setting.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=gh-readonly-queue/master/pr-115493-b969510547ed79e8268ba3c61e38607169879176&sha=438dc390ffdb8c4a2f581bd2d5a3fc7bccf6d0ab&name_0=MergeQueueCI&name_1=Fast%20test
Related: #115493

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

novikd commented Aug 24, 2026

Copy link
Copy Markdown
Member Author

The merge-queue Fast test failure was a semantic conflict with 76be7b5 (query_plan_merge_filter_into_join_condition extended to common-supertype equalities — the same cross-type pairs this PR substitutes), which landed after this branch's base; both changes were green independently and first met in the queue. No wrong results — two plan-semantics pins in 6faf898 (on top of a fresh master merge):

  • 04654_merge_filter_into_join_condition_common_supertype: its correlated section pins the fallback decorrelation shape (joins_with_conditions=2) that this PR's substitution plans away, so the substitution is disabled for that section — preserving exactly the scenario the test verifies.
  • 05023_...: pinned query_plan_merge_filter_into_join_condition = 0 — merging a cross-type equality into a join condition makes the fallback compare floats bitwise, which changed the guarded ±0 cases' documented equals semantics depending on a randomized setting. (Notably, the fallback thereby moved toward the same bitwise behavior that motivated guarding float substitution here.)

Verified on the merged tree: both tests green 3/3 with unchanged references, including an adversarial run forcing the conflicting settings via --client-option.

…ions

Address two review findings. First, a real wrong result: an exact-type
`Float64` member reached through a numeric bridge (`i.a = o.x AND i.a = i.b`)
bypassed the float guard via the exact-match early return, and the
reconstructed `+0.0` failed the bitwise top join while the fallback's
cross-type `equals` kept the outer `-0.0`. The equivalence classes are flat,
so a bridged member cannot be told apart from a direct one — the float check
now precedes the exact-match return, making float correlated bases unusable
for any substitution. This also retires the pre-existing direct exact-float
substitution, which was itself inconsistent with the fallback under
`query_plan_merge_filter_into_join_condition = 0`.

Second, the `Bool` exclusion was too broad: wrapper-only conversions
(`Bool` vs `Nullable(Bool)`/`LowCardinality(Bool)`) never use the inexact
cast into `Bool` and preserve the canonical 0/1 values, so the `Bool` check
moves into the cross-base branch and those cases substitute again.

Test: guarded case 27 (the bridge counterexample, `-0` kept through the
fallback) and substituted case 28 (`Bool` vs `Nullable(Bool)` scalar count
with an inner NULL).

Related: #115493

Co-Authored-By: Claude Fable 5 <[email protected]>
Address review feedback: `Bool` is a custom-named `UInt8` and
`IDataType::equals` does not distinguish them, so a plain `UInt8` member took
the exact/equal-base substitution paths for a `Bool` correlated column and
aliased non-canonical values like `2` into it. The reviewer's
`throwIf(o.x NOT IN (0, 1))` trigger is constant-folded away by the
analyzer's own `Bool` domain reasoning — itself evidence of the violated
invariant — but a non-foldable observable reproduces a real divergence:
`intDiv(1, 2 - o.x)` is safe over the genuine `Bool` domain yet threw with
the smuggled `2` under substitution. Reconstruction into `Bool` now requires
a `Bool` member (checked before the exact-match fast path, subsuming the
previous cross-base check); `Bool` members substituting into non-`Bool`
integer columns stay, as their canonical 0/1 values are faithful in any
integer domain.

Test: guarded case 29 (outer `Bool` vs inner `UInt8` with the `intDiv`
observable).

Related: #115493

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

Address review feedback generalizing the `Bool` finding: `IDataType::equals`
compares the storage type and ignores semantically significant attributes
such as `DateTime` timezones and custom names, so the exact/equal-base paths
could alias a correlated column into a different semantic type. Reproduced
as a wrong result: outer `DateTime('UTC')` vs inner `DateTime('Asia/Tokyo')`
with epoch-0 rows and `toHour(o.ts) = 0` — the substituted plan lost the row
(the aliased column made `toHour` see hour 9) while the fallback kept it.

The exact fast path and the equal-base wrapper check now compare `getName()`
("same meaning"), and the renaming-loop `chassert` is strengthened likewise.
Attribute-mismatched non-numeric pairs fall through to the cross-base branch
and thus to the CROSS JOIN fallback — conservative; a lossless
timezone-reinterpreting `CAST` could be a future improvement.

Test: guarded case 30 (the timezone reproduction) and substituted case 31
(same-timezone `Nullable(DateTime('UTC'))` wrapper stays admitted).

Related: #115493

Co-Authored-By: Claude Fable 5 <[email protected]>
novikd and others added 2 commits August 25, 2026 19:02
…ack cases

Review feedback pointed out that under the default
`query_plan_merge_filter_into_join_condition = 1` the guarded float cases'
fallback loses the `-0.0` matches, so pinning the setting looked like hiding
a gap. The divergence reproduces with the substitution disabled — it is
master's own decorrelation fallback interacting with the common-supertype
condition merging, now tracked as issue #116358 (caused by PR #112630, the
fix belongs in `tryMergeFilterIntoJoinCondition`, not in the decorrelation).
The pin stays for test determinism; the pin comment and the case 12/24
headers now reference the tracked issue instead of implying the `equals`
fallback semantics are the production default.

Related: #116358
Related: #115493

Co-Authored-By: Claude Fable 5 <[email protected]>
The test grew to 31 cases through review rounds, and one amd_debug flaky
check run exceeded the 180 s per-run budget under expensive randomized
settings (`fsync_metadata`, JIT compilation thresholds). Cases 1-15 (the
original nullability and numeric-conversion set) stay in
`05023_correlated_subquery_equivalence_type_conversion`; cases 16-31 (the
review-driven `LowCardinality`, scalar `count()`, `Bool`, signed-zero, and
`DateTime` attribute cases) move verbatim to
`05042_correlated_subquery_equivalence_type_conversion_2` with the same
pinned-settings header. Case numbering is preserved so the review-thread
references stay meaningful, and the two regenerated references concatenate
byte-for-byte into the previous combined one.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115493&sha=latest&name_0=PR
Related: #115493

Co-Authored-By: Claude Fable 5 <[email protected]>
Address review feedback: the renaming loop still decided between `CAST` and
alias via `IDataType::equals`, which cannot tell `Bool` from `UInt8`, so a
`Bool` member substituting into a `UInt8` correlated column was aliased and
smuggled its custom name into the correlated column — reproduced as a wrong
result (`toString(o.x)` rendered `true` instead of `1`, dropping the row the
fallback keeps). The decision now compares `getName()` like
`classifySubstitutionConversion`, so such storage-equal pairs get the
value-identity `CAST` that normalizes the name; the `getName`-based
`chassert` below it would already have caught this on debug builds.

Test: case 32 in part 2 (outer `UInt8` vs inner `Bool` with the `toString`
observable).

Related: #115493

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

After substitution, retained expressions over the correlated column are
evaluated on the inner values, including rows that never match any outer
value, so e.g. a division that is safe over the outer domain could throw
(reachable under default short-circuit evaluation via the merged Prewhere).
The channel does not depend on the cross-type conversion: the exact-type
shape admitted by the pre-existing substitution throws identically.

A correlated identifier is now substituted only when its only uses inside
the current UNION-arm scope are the recorded equality conjuncts. Uses are
collected at handler entry (FilterStep non-equality consumers of
placeholders, ExpressionStep placeholder uses, user aggregation keys and
aggregate arguments); UNION arms keep fresh equivalence classes but inherit
the parent scope's usage set by copy, because a use in a shared ancestor
step receives the arm's substituted column through the union output.

The UNION test cases pin the default `right` join kind: the CROSS JOIN
fallback inside a correlated `UNION ALL` is broken independently of this
change under the non-default `left` kind (a fallback arm loses rows, two
fallback arms cannot build a pipeline) and under `right` without the
in-memory buffer.

Review comment: #115493 (comment)

Co-Authored-By: Claude Fable 5 <[email protected]>
The UnionStep decorrelation handler rebuilt the union from only
children.front() and children.back(), silently dropping the middle arms
of a correlated UNION ALL with three or more arms: a query where only a
middle arm matches the outer row returned no rows, and the middle arm's
table was absent from the decorrelated plan entirely. The defect dates
to the introduction of correlated UnionStep support (9f57194) and
reproduces with correlated_subqueries_substitute_equivalent_expressions
disabled.

Decorrelate all children in a loop; everything downstream
(buildCommonHeaderForUnion, the header conversion, updateInputHeaders,
unitePlans) is already N-ary. The per-arm scope discipline (fresh
equivalence classes, inherited usage set) applies to every arm through
the same lambda.

Review comment: #115493 (comment)

Co-Authored-By: Claude Fable 5 <[email protected]>
novikd and others added 2 commits August 27, 2026 16:38
An equality recorded above a correlated UNION (u.x = o.x over a derived
table) could not enable substitution inside the arms: the arms get fresh
equivalence classes, so every arm kept the buffered CROSS JOIN fallback
even when each arm could reconstruct the correlated column from its own
output. The behavior predates this PR (arms never saw parent classes),
but the substitution machinery of this PR makes fixing it natural.

Two pieces make the parent equality reachable from the arms. The
ExpressionStep handler records pure renames (an alias output and its
underlying input are the same value with the same type) as equivalences,
which bridges the derived table's column identifier to the union output
name. The UnionStep handler then seeds each arm scope: every member of a
correlated identifier's parent class that names a union output column is
mapped into the arm positionally (arms may keep different column
identifiers), traced down the arm's correlated chain through pure
renames to the uncorrelated boundary, re-checked against the recording
type guard with the boundary type, and only then recorded arm-locally.
Computed union columns and coercion functions are never traced —
such arms conservatively keep the fallback.

Review comment: #115493 (comment)

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

/// If all columns from outer query have equivalent expressions in the current subplan,
/// we can safely replace them and avoid introduction of CROSS JOIN.
if (context.correlated_subquery.correlated_column_identifiers.size() == expression_renamings.size())

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.

This early substitution return now runs before the explicit skipped-scope rejection below at src/Planner/PlannerCorrelatedSubqueries.cpp:600-611. That makes a new cross-type nested case regress from the intended NOT_IMPLEMENTED to a later NOT_FOUND_COLUMN_IN_BLOCK: take the existing 04502 shape, but make the innermost equality newly substitutable (for example ref_3.vkey Nullable(UInt32) = ref_1.vkey UInt32, or Int32 = Int64). expression_renamings fills here, so we return without ever checking that context.query_plan for the immediate outer scope actually contains ref_1.vkey; then buildLogicalJoin still unconditionally does findNode(get_rhs_column_name(column_name), /* is_input = */ true) for every correlated_column_identifier and fails deep in JoinExpressionActions.

I think the immediate-scope availability check needs to stay in front of both the substitution and CROSS JOIN paths, plus a focused regression test for a substitutable deep-nested equality so 04502's clear error is preserved for the newly admitted type pairs.

@vdimir
vdimir added this pull request to the merge queue Aug 31, 2026
Merged via the queue into master with commit 6747c8b Aug 31, 2026
176 checks passed
@vdimir
vdimir deleted the fix-correlated-substitution-types branch August 31, 2026 12:00
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 31, 2026
@zlareb1

zlareb1 commented Aug 31, 2026

Copy link
Copy Markdown
Member

The new refusal of float correlated bases in classifySubstitutionConversion tests only the top-level base type, so a float nested in a composite still takes the exact-type substitution path: Array(Float64), Tuple(Float64, Int32), and Map(String, Float64) correlated columns substitute and lose signed-zero matches ([0.0] no longer matches [-0.0]) on this PR's head build, while the scalar Float64 spelling is fixed by it. Filed #117334 with the isolated reproducer (query_plan_merge_filter_into_join_condition = 0 to keep #116358 out of the picture).

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

Labels

pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Correlated EXISTS decorrelates to a CROSS JOIN with severe memory growth when equality columns differ only in nullability

5 participants