Skip to content

Fix coalesce type mismatch exception with FULL OUTER JOIN - #101788

Closed
Onyx2406 wants to merge 9 commits into
ClickHouse:masterfrom
Onyx2406:fix/coalesce-join-type-cast
Closed

Onyx2406 wants to merge 9 commits into
ClickHouse:masterfrom
Onyx2406:fix/coalesce-join-type-cast

Conversation

@Onyx2406

@Onyx2406 Onyx2406 commented Apr 4, 2026

Copy link
Copy Markdown
Contributor

What this PR does

When coalesce filtered down to a single argument whose type was narrower than the expected result type (e.g., UInt16 vs UInt32 from a multi-table JOIN), it returned the column without casting. Added a cast when types differ.

Fixes #89407

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry:

Fixed logical error "Unexpected return type from coalesce" when using FULL OUTER JOIN with columns of different numeric types.

  • Documentation is written (no docs needed)

Onyx2406 added 3 commits April 4, 2026 18:46
When `coalesce` filtered down to a single argument whose type was
narrower than the expected result type (e.g., UInt16 vs UInt32 from
a multi-table JOIN), it returned the column without casting, causing
"Unexpected return type" exception. Add a cast when types differ.

Fixes ClickHouse#89407
Renumber `04072_coalesce_join_type_mismatch` to `04077` to avoid
collision with `04072_jit_decimal_expressions`, and update table name
suffixes from `_04076` to `_04077` for consistency.
… table suffixes to avoid number collision with upstream master
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Apr 5, 2026
return multi_if_args.front().column;
{
const auto & src = multi_if_args.front();
if (!src.type->equals(*result_type))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why was it wrong in the first place? Shouldn't we find the root cause?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I dug into this and the root cause is upstream of coalesce, not inside it.

In the original report (issue #89407, master ~2025-11), the legacy JoinStep was producing a result block where the runtime column types didn't match what the analyzer had declared for the function call. The action graph for coalesce(t2.x, t1.x) carried result_type = UInt32 (the least common type across the three USING columns), but the post-join block produced __table2.x as UInt16 and __table1.x as UInt32 — the type-aligning CAST on the t2 side was missing. coalesce then forwarded a UInt16 column out and the executor caught the mismatch (Unexpected return type from coalesce. Expected UInt32. Got UInt16.).

On current master that branch is gone. The plan now emits an explicit _CAST(__table1.x, 'UInt32') / _CAST(__table2.x, 'UInt32') in Post Join Actions before the coalesce, so both inputs arrive at coalesce already typed as UInt32:

Expression (Post Join Actions)
Actions: INPUT : 0 -> _CAST(__table1.x, 'UInt32'_String) UInt32 : 0
         INPUT : 1 -> _CAST(__table2.x, 'UInt32'_String) UInt32 : 1
...
FUNCTION coalesce(__table2.x :: 1, __table1.x :: 0) -> coalesce(__table2.x, __table1.x) UInt32

This was fixed upstream by the new logical JOIN step refactor — query_plan_use_new_logical_join_step is now an obsolete alias (d4b469e03a9, 2026-05-04) and the new step always inserts the type-aligning CASTs. I confirmed by reverting coalesce.cpp to its master version (no fix) and rerunning the issue's exact query — it no longer raises LOGICAL_ERROR. That's also why Bugfix validation fails on this PR: the test passes on master without the patch, because the bug is no longer reproducible by that query.

So the situation is:

  1. The reported bug's root cause was a missing type-aligning CAST in the legacy JoinStep, not in coalesce. That has been fixed independently.
  2. The multi_if_args.size() == 1 branch in coalesce was theoretically lying about its return type (returning the surviving column verbatim with no check against result_type), but I couldn't construct any current query that reaches that branch with a type mismatch — getReturnTypeImpl and executeImpl apply the same onlyNull filter, and the analyzer no longer produces planner-level constant-NULL substitutions that would diverge between the two.

Given that, my recommendation is to close this PR:

  • Adding a silent cast here would be a fallback path that hides any future JOIN-side regression — it would silently downgrade a regressed LOGICAL_ERROR into a slow CAST, exactly what the codebase tries to avoid.
  • The bug it claimed to fix is already fixed elsewhere; there is no remaining reproducer.
  • The test no longer validates anything — Bugfix validation correctly flags this.

If we ever want belt-and-suspenders in coalesce, the right shape is a chassert(src.type->equals(*result_type)) so the invariant breaks loudly in debug builds rather than a runtime cast that papers over upstream bugs.

@Onyx2406 thanks for chasing this — sorry it converged on "no longer needed".

@clickhouse-gh

clickhouse-gh Bot commented Apr 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c0c37ad]

Summary: ❌

job_name test_name status info comment
Bugfix validation (functional tests) FAIL
04089_coalesce_join_type_mismatch FAIL cidb
Performance Comparison (arm_release, master_head, 3/6) FAIL
Check Results FAIL

AI Review

Summary

This PR fixes coalesce for a real execution-path mismatch: when runtime filtering leaves a single surviving argument whose type is narrower than the precomputed result_type, the old code could return a mismatched column type and trigger Unexpected return type from coalesce. The added conditional cast in the single-argument fast path is correct and the new stateless regression test reproduces the reported case (#89407). I found no correctness, safety, or performance blockers in the patch itself.

Missing context
  • ⚠️ Full CI results and job logs were not yet available at review time (Code Review, Fast test, Build (arm_tidy), and Bugfix validation (functional tests) were still running).
ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Apr 5, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix.

@alexey-milovidov

Copy link
Copy Markdown
Member

The failures of "Flaky check" in "functions_bad_arguments" will be fixed by #101994.

@alexey-milovidov

Copy link
Copy Markdown
Member

The MSan stress test failure (MemorySanitizer: use-of-uninitialized-value, STID 4179-5154 or 4148-3044) is a known pre-existing issue unrelated to this PR. Fix: #102158

alexey-milovidov and others added 4 commits April 9, 2026 00:33
The old analyzer does not support chaining multiple `FULL OUTER JOIN ... USING`
clauses, so the repro query throws `Multiple USING statements are not supported`
before `coalesce` is even evaluated. That caused the Stateless (old analyzer)
shard to fail on this PR. Add `SETTINGS enable_analyzer = 1` to the repro so the
test exercises the fix rather than hitting a parser limitation.
Alexey asked why `coalesce` was returning the wrong type in the first
place. Add an inline comment that spells it out so future readers (and
reviewers) don't have to reconstruct the reasoning:

`getReturnTypeImpl` computes `result_type` from the full, analyzer-time
argument list. The planner can later replace some of those arguments with
const-null columns whose type is `Nullable(Nothing)` — this happens
routinely in `FULL OUTER JOIN` over columns of different widths, where
the non-matching side is materialised as a pure NULL. The filtering loop
at the top of `executeImpl` drops every such `onlyNull` argument, so a
single surviving argument may have a narrower type than `result_type`.
Returning its column unchanged violates the contract that the output
matches the declared return type, which triggers the
`Unexpected return type from coalesce` exception.

The cast on mismatch is the correct fix at this layer: the deeper issue
is that the planner changes the effective argument list after analysis,
and coalesce's contract is to honour the declared return type regardless.
@Onyx2406

Onyx2406 commented Apr 18, 2026 •

Copy link
Copy Markdown
Contributor Author

@alexey-milovidov Root cause explanation (also added as inline docs in coalesce.cpp in commit c0c37ad8e6):

getReturnTypeImpl computes result_type from the full analyzer-time argument list. For coalesce(t2.x, t1.x) with t2.x: Nullable(UInt32) and t1.x: Nullable(UInt16) that's Nullable(UInt32).

In the planner, the non-matching side of a FULL OUTER JOIN across columns of different widths gets materialised as a const-NULL column whose type is Nullable(Nothing). So by the time executeImpl runs, one of the two arguments looks onlyNull to the filter loop at the top and gets dropped. The single surviving argument is t1.x with type Nullable(UInt16).

Returning that column verbatim violates the contract that the output matches the declared result_type the assertion downstream then raises Unexpected return type from coalesce. The cast on mismatch is the right fix at this layer: the deeper issue is that the planner changes the effective argument list after analysis, but coalesce has to honour its declared return type regardless of which path the planner took.

Note this only manifests with query_plan_use_new_logical_join_step = 0; the new logical join step handles the post-JOIN type unification upstream and doesn't surface the narrower-type argument here.

@clickhouse-gh

clickhouse-gh Bot commented Apr 18, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.00% 84.00% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.50% 76.50% +0.00%

Changed lines: 83.33% (5/6) · Uncovered code

Full report · Diff report

@alexey-milovidov

Copy link
Copy Markdown
Member

Closing per the root-cause analysis above: the original bug (issue #89407) was a missing type-aligning CAST in the legacy JoinStep, which has been fixed independently by the new logical JOIN step refactor (d4b469e03a9 made query_plan_use_new_logical_join_step an obsolete alias on 2026-05-04). The issue's exact reproducer no longer raises LOGICAL_ERROR on master without this patch, and I couldn't find any remaining query that reaches the multi_if_args.size() == 1 branch with a type mismatch. Adding a silent cast in coalesce would only mask any future JOIN-side regression.

Thanks again @Onyx2406.

alexey-milovidov added a commit to Onyx2406/ClickHouse that referenced this pull request May 20, 2026
The test was accidentally added to this branch by an earlier renumber
commit. It belonged to PR ClickHouse#101788 which was closed because the underlying
`coalesce` bug got fixed upstream by the new logical JOIN step
(`d4b469e03a9`). The test is no longer applicable and would conflict
with `04089_decimal_datetime64_minmax_if.sql` on master.
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 pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Logical error: 'Unexpected return type from coalesce. Expected UInt32. Got UInt16

2 participants