Skip to content

Fix Unexpected return type in PREWHERE when a Merge table reads another Merge table with different column types - #124037

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-merge-over-merge-prewhere-mergenodes
Oct 9, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-merge-over-merge-prewhere-mergenodes

Conversation

@groeneai

@groeneai groeneai commented Oct 5, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

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

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

Fixed a LOGICAL_ERROR Unexpected return type when reading a Merge table whose underlying table is another Merge table with different column types, with optimize_prewhere_after_pushdown = 1 and move_all_conditions_to_prewhere = 0.

Description

On 26.8.10.6 (also 26.6.8.7), SELECT count() FROM m_outer WHERE a = 1 AND b = 2 SETTINGS optimize_prewhere_after_pushdown = 1, move_all_conditions_to_prewhere = 0, where m_outer (a, b Nullable(UInt64)) is a Merge over the Merge table m_inner (UInt32), fails with Code: 49 ... Unexpected return type from equals. Expected Nullable(UInt8). Got UInt8.

Found by BuzzHouse (amd_debug), STID 1611-4266: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117136&sha=4e6ae73c08748ab5f668b4b0e65b72a4c9f4b2cc&name_0=PR&name_1=BuzzHouse%20%28amd_debug%29. There merge(REGEXP('em$'), '') reads system.all_part_log (a Merge over system.part_log, database LowCardinality(String)) next to system.grants (database Nullable(String)). No related issue found.

Each Merge level wraps its outputs in materialize(<col>), so the pushed-down filter holds two different nodes named materialize(b): the inner UInt32 one and the outer Nullable(UInt64) one. The second PREWHERE pass merges the new condition into the existing PREWHERE with ActionsDAG::mergeNodes, which rebound children by name, so equals was attached to the inner node while keeping the function resolved for the outer type.

mergeNodes now rebinds the children and outputs of the nodes it moves from second by pointer, and de-duplicates only inputs by name. Matching nodes of second against the existing nodes of the destination DAG by name is unchanged.

The new test has 8 arms (two type pairs, enable_multiple_prewhere_read_steps 0/1, the merge() table function). Each arm fails on master; the test fails in 20/20 randomized runs on master and passes in 50/50 with the change.


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

Version info

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

…nother Merge table

`StorageMerge` wraps every child output in `materialize(<col>)` (`addMissingDefaults`), so
when a `Merge` table reads another `Merge` table, the filter pushed down from the outer
`WHERE` holds two different nodes with the same name: the inner `materialize(b)` over the
read column and the outer one over `_CAST(inner, <outer type>)`.

With `optimize_prewhere_after_pushdown = 1` and `move_all_conditions_to_prewhere = 0`, the
second `optimizePrewhere` pass merges the new condition into the existing PREWHERE with
`ActionsDAG::mergeNodes`. It registered every moved node of `second` in a name map and
rebound children by name, so the outer node collapsed into the inner one and `equals` ran
on the inner column with a function resolved for the outer (Nullable) type:
`Unexpected return type from equals. Expected Nullable(UInt8). Got UInt8`. The outputs
were mapped by name with the same defect.

`mergeNodes` now records, for every processed node of `second`, the node it ends up as, and
rebinds children and `out_outputs` through that map by pointer. A node of `second` is
matched by name only against the existing nodes of the destination DAG, and an input also
against the inputs of `second` already moved, so duplicate inputs still collapse while a
computed node never collapses into another node of `second`, including an input it shadows
(`CAST(x, ...) AS x`).

Found by BuzzHouse (amd_debug) on `merge(REGEXP('em$'), '')`, which reads
`system.all_part_log` (a Merge over `system.part_log`) next to `system.grants`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Oct 5, 2026
@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (round 1: codex, 2 findings; round 2 on the fixed tree: claude, 0 findings).

# Sev Finding Verdict Evidence / action
1 ⚠️ mergeNodes still collapsed a computed node of second onto a same-named input of second (CAST(x, ...) AS x) (src/Interpreters/ActionsDAG.cpp, mergeNodes) AGREE, fixed in round 2 a node of second now binds by name only to an existing node of the destination DAG; inputs of second are de-duplicated in a separate map
2 ⚠️ The test does not prove the second PREWHERE pass ran (asks for an EXPLAIN oracle) DISAGREE every arm aborts on master in the second-pass merge, and the test fails in 20/20 randomized runs on master; the pass is pinned by SET and a validated Random settings limits clamp
3 💡 No SQL arm for the shadowed-input rule of row 1 noted 24 probes (materialized view with a row policy over a drifted type, Buffer, Merge) on three binaries, with a debugger check at the merge site: the second-pass PREWHERE DAG never holds a computed node named like its own input, so the rule is not reachable through this path
4 💡 A node of second is still matched by name against the destination DAG, which can hold two same-named nodes noted unchanged by design (other callers rely on it); not reachable through optimizePrewhere: a second-pass condition that reuses a first-pass column reads a non-table input and is not moved to PREWHERE

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-9:20261005-131100

@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The test's setup plus any of its 8 SELECTs with optimize_prewhere_after_pushdown = 1, move_all_conditions_to_prewhere = 0 aborts a master debug clickhouse local at ExpressionActions.cpp:696, every run.
b Root cause explained? Each Merge level adds materialize(<col>), so the pushed filter holds two different nodes with one name. The second PREWHERE pass combines via ActionsDAG::mergeNodes, which rebound children by name, so equals ran on the inner column with a function resolved for the outer type.
c Fix matches root cause? Yes. mergeNodes rebinds children and outputs of moved nodes by pointer; a name binds a node of second only to an existing node of the destination DAG, or an input to an input of second. No guard at the abort site.
d Test intent preserved / new tests added? New 05325_merge_over_merge_prewhere_after_pushdown.sql (8 arms). optimize_move_to_prewhere clamped to 1 (validated: 0 of 92 runs got 0; 5 of 100 with the line corrupted).
e Both directions demonstrated? Master: all 8 arms abort; 20/20 randomized runner runs kill the server with the same message. Fix: all arms correct; 50/50 randomized runs pass. The CI query over system aborts on master and returns a count with the fix.
f Fix is general across code paths? Fixed in the shared primitive used by all five mergeNodes callers (PREWHERE combine, alias columns, join conditions, set index, text index); their behaviour changes only when second has two same-named nodes that are not both inputs (two computed nodes, or a computed node shadowing an input, CAST(x, ...) AS x). ~1300 caller-area tests: no new failure.
g Fix generalizes across inputs (params/datatypes/wrappers)? LowCardinality(String) under Nullable(String), UInt32 under Nullable(UInt64), three Merge levels, multi-step PREWHERE 0/1, the merge() table function. Int, Array and LowCardinality(Nullable) pairs were already correct and stay correct.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or stored-state change.
i Invariants and contracts preserved? out_outputs[i] corresponds to second.getOutputs()[i] by pointer; no node of the destination DAG is removed; duplicate inputs still collapse; children are finalized before parents, so the pointer lookup cannot miss.

Session id: cron:clickhouse-impl-slot-4:20261005-085500

@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Oct 5, 2026
@groeneai
groeneai requested review from vdimir and yariks5s October 5, 2026 14:24
@clickhouse-gh

clickhouse-gh Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [22c3ece]

Summary: ✅


AI Review

Summary

This PR fixes ActionsDAG::mergeNodes so nodes imported from the second DAG keep their internal pointer-based structure instead of rebinding children by result_name, which matches the PREWHERE Merge-over-Merge failure described in the PR. The change is narrow, preserves the existing cross-DAG name reuse that the other callers rely on, and the new stateless regression covers both the engine path and the merge() table-function reproducer. I did not find a remaining correctness, metadata, or test-coverage issue in the current diff.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 22c3ece.

Metric Baseline Current Δ
Lines 88.20% 88.30% +0.10%
Functions 92.10% 92.10% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 29/32 (90.62%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Oct 5, 2026
@alexey-milovidov alexey-milovidov self-assigned this Oct 9, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 9, 2026
Merged via the queue into ClickHouse:master with commit c16fb52 Oct 9, 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 9, 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-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default 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.

3 participants