Repository navigation
Support safe type conversions in correlated subquery equivalence substitution - #115493
Conversation
…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]>
|
Workflow [PR], commit [db2f9f6] Summary: ✅
AI ReviewSummaryThis PR extends correlated-subquery equivalent-expression substitution across safe nullability and numeric conversions, adds several correctness guards around floats, Findings
Tests
Final Verdict
LLVM Coverage ReportMeasured on commit db2f9f6.
Changed lines: Changed C/C++ lines covered: 243/258 (94.19%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes3 object files changed (+69.36 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units7 translation units recompiled, 13 s compile time in total, 7 of them have a recent master baseline. |
|
📊 Cloud Performance Report ✅ AI verdict: 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
|
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]>
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]>
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]>
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]>
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]>
|
The merge-queue Fast test failure was a semantic conflict with 76be7b5 (
Verified on the merged tree: both tests green 3/3 with unchanged references, including an adversarial run forcing the conflicting settings via |
…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]>
…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]>
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()) |
There was a problem hiding this comment.
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.
|
The new refusal of float correlated bases in |
Closes: #113407
Related: #101863
Changelog category (leave one):
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.
Int64vsNullable(Int64)underdata_type_default_nullable = 1, as in TPC-DS Q35), or on native-number columns having a least common type (e.g.Int32vsInt64), 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
PlannerCorrelatedSubqueriesrecorded an equivalence only when both sides of the correlatedequalshad exactly the same type. A correlatedEXISTSwhose join condition comparesInt64withNullable(Int64)therefore decorrelated through the CROSS JOIN fallback; at TPC-DS SF100 (Q35 withdata_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
PLACEHOLDERnodes 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:NULLs;equalsis mathematically exact (9007199254740993 :: Int64 = 9007199254740992.0 :: Float64is0), the supertype exists only when every type embeds losslessly, andaccurateCastOrNullis exactness-checking, so value equivalence is transitive across a class.At substitution the chosen equivalent column is converted to exactly the correlated type:
toNullable/ losslessCASTwhen widening,assumeNotNull/accurateCastOrNullwhen narrowing. For the narrowing conversions aFilterStepis inserted below the renaming that drops rows whose value isNULLor does not convert exactly — such rows can never satisfy the recorded equality (a top-level AND-conjunct of an ancestor filter), and dropping them beforeassumeNotNullis 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
CASTkeep the previous CROSS JOIN fallback:DecimalvsFloat(comparison converts toFloatand is inexact),StringvsFixedString(comparison ignores padding), and supertype-less numeric pairs such asInt64vsUInt64orInt64vsFloat64.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
crossnodes and returns the same result as the fallback.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 outer0vs innerNULL, guarded fallbacks) passed 6/6 runs under harness setting randomization.EXISTS/NOT EXISTS/ scalarcount()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) andNULLs — identical everywhere, and plan probes confirmed the substitution fires exactly for the admitted pairs.correlatedstateless 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
26.9.1.431(included in26.9and later)