Skip to content

Fix Block structure mismatch in UnionStep/IntersectOrExceptStep when a branch constant-folds - #107719

Merged
fm4v merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-union-const-fold-header-106956
Jul 20, 2026
Merged

fm4v merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-union-const-fold-header-106956

Conversation

@groeneai

@groeneai groeneai commented Jun 17, 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 Block structure mismatch in UnionStep stream logical error (server abort on debug/sanitizer builds, Code: 49 on release builds) that occurred when sibling branches of a UNION/INTERSECT/EXCEPT differed only in their WHERE predicate and one branch's predicate constant-folded to a Const column.

Description

Reported in #106956. Split out of #107041 at the reviewer's request (the sparse half stays in #107041, this PR covers the constant-folding half only).

Reproduces deterministically with default settings, no tables needed:

SELECT t2.a, t1.b = t2.b
FROM (SELECT 1 AS a, 2 AS b) AS t1
INNER JOIN (SELECT 1 AS a, 2 AS b) AS t2 ON t1.a = t2.a
WHERE t1.b = t2.b
UNION ALL
SELECT t2.a, t1.b = t2.b
FROM (SELECT 1 AS a, 2 AS b) AS t1
INNER JOIN (SELECT 1 AS a, 2 AS b) AS t2 ON t1.a = t2.a
WHERE NOT (t1.b = t2.b);

Set-operation branches are optimized independently. When one branch's predicate constant-folds (here NOT (t1.b = t2.b) over constant join inputs), filter push-down through the join leaves that branch's projection column Const while the sibling keeps a full column. The plan-time header check in UnionStep::updateOutputHeader / IntersectOrExceptStep::updateOutputHeader used strict assertBlocksHaveEqualStructure and rejected the divergent constness, even though the execution-time path (updatePipeline) already tolerates exactly this via makeConvertingActions.

The fix makes the plan-time check tolerant the same way: it requires matching column names and types but allows a Const to meet a full column, and computes the common header with getLeastSuperColumn (the primitive the planner already uses to build the union header) so a column stays Const only when every branch agrees and is widened to a full column otherwise. When no branch constness diverges the front header is returned unchanged, so plans for ordinary set operations are byte-identical to before (no new plan nodes, no EXPLAIN changes).

Added regression test 04327_union_branch_const_header_mismatch (covering UNION ALL, UNION DISTINCT, SELECT DISTINCT, an explicit CAST(..., 'Nullable(UInt8)') projection, INTERSECT, and EXCEPT).

Related: #107951 (a second path to the same IntersectOrExceptStep divergence).
Related: #107953 (STID 0993-28b7: an AST-fuzzer query reaches the same UnionStep::updateOutputHeader Const-vs-full site).

The plan-time check now stays strict except for top-level Const: each branch is compared to the front with only its top-level Const stripped (the strip is guarded by isColumnConst, so Sparse/Replicated divergences and nested constness such as Array(Const(T)) vs Array(T) stay rejected), and the common header keeps a column Const only when every branch is Const with the same value, materializing otherwise. This replaces the earlier getLeastSuperColumn formulation while keeping the same behavior for ordinary set operations.

At pipeline-build time, both UnionStep and IntersectOrExceptStep guard their converting expression with the strict blocksHaveEqualStructure (the intersect step previously used the lax isCompatibleHeader), so a branch whose column was materialized in the common header gets the conversion applied to every stream of its pipeline - including the totals port when the branch has WITH TOTALS (found by the AST fuzzer; pinned in the test).

The old analyzer computes result_header from the sample block independently of the plan, so a column the plan legitimately materialized (for example randConstant() over remote(...) whose shards fold to different values) stayed Const in result_header and makeConvertingActions rejected the full-vs-Const conversion (01418_query_scope_constants_and_remote). InterpreterSelectQuery::buildQueryPlan now takes the plan's full column into the local convert target where the plan is full but result_header is Const of the same type, leaving result_header itself untouched. The new analyzer already derives result_header from the same logic as the plan and is unaffected.

A review follow-up claimed the old-analyzer parent set-operation interpreters (InterpreterSelectWithUnionQuery / InterpreterSelectIntersectExceptQuery) still convert a materialized child back to a stale Const sample header. Verified against a live 2-shard remote('127.0.0.{1,2}') topology that this does not reproduce: the parents decide their conversion steps at plan-build time, when child plan headers still match the child samples; the Const divergence only appears during plan optimization, after those targets are fixed, and the execution-time conversion tolerates it. All claimed shapes (parent UNION ALL / UNION DISTINCT / INTERSECT / EXCEPT over serverUUID() / randConstant() remote children under enable_analyzer = 0) are pinned as regression cases in 04327_union_branch_const_header_mismatch.

Version info

  • Merged into: 26.7.1.1214 (included in 26.7 and later)
  • Backported to: 26.6.2.84

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. The SELECT ... UNION ALL SELECT ... query in the description aborts the server (debug/sanitizer) / returns Code: 49 (release) on demand with default settings, no tables.
b Root cause explained? Set-operation branches are optimized independently. Filter push-down through a join in one branch constant-folds its projection column to Const while the sibling stays full, so the plan-time UnionStep/IntersectOrExceptStep::updateOutputHeader strict assertBlocksHaveEqualStructure rejects the divergent constness, even though updatePipeline already reconciles it at execution time via makeConvertingActions.
c Fix matches root cause? Yes. The plan-time check is made tolerant the same way the execution path already is: match names and types, allow Const to meet full, and compute the common header with getLeastSuperColumn so a column stays Const only when every branch agrees. No symptom guard.
d Test intent preserved / new tests added? New regression test 04327_union_branch_const_header_mismatch (UNION ALL, UNION DISTINCT, SELECT DISTINCT, explicit CAST(..., 'Nullable(UInt8)'), INTERSECT, EXCEPT). No existing test weakened.
e Both directions demonstrated? Yes. The query aborts on master HEAD and passes with this commit; the regression test fails without the fix and passes with it. Validated on the original combined PR #107041 before the split into this PR.
f Fix is general, not a narrow patch? Both divergent set-operation steps are covered (UnionStep and IntersectOrExceptStep), and the front header is returned unchanged when no branch constness diverges, so ordinary set operations are unaffected. The sibling Sparse-vs-full case is handled separately in #107041 at the shared primitive.

Session id: cron:clickhouse-worker-slot-3:20260617-103600

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @davenger - const-fold half split out of #107041 per review. Makes the plan-time UnionStep/IntersectOrExceptStep header check tolerate a Const branch meeting a full one via getLeastSuperColumn, matching what updatePipeline already does at execution time.

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Jun 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ced56bb]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_asan_ubsan, db disk, old analyzer, 3/6) FAIL
test_replicated_database/test.py::test_replicated_table_structure_alter FAIL cidb, issue
Integration tests (amd_tsan, 3/6) FAIL
test_replicated_database/test.py::test_replicated_table_structure_alter FAIL cidb, issue

AI Review

Summary

This PR fixes UnionStep / IntersectOrExceptStep header mismatches when one set-operation branch constant-folds and another stays full, and it also hardens the related optimizer and old-analyzer paths. The main logic now looks correct for the previously discussed const-vs-full cases, but there is still one correctness hole in the old-analyzer reconciliation for duplicate output names.

PR Metadata
  • Changelog category: correct (Bug Fix).
  • Changelog entry: required for this category, present, and specific enough about the affected UNION / INTERSECT / EXCEPT failure mode and user-visible behavior.
Findings
⚠️ Majors
  • src/Interpreters/InterpreterSelectQuery.cpp:1222 The old-analyzer convert_target reconciliation now matches columns with findByName, but Block headers may legitimately contain duplicate output names and findByName only returns the first occurrence. If only a later duplicate is materialized by the plan (for example SELECT toUInt32(42) AS c, randConstant() AS c FROM remote('127.0.0.{1,2}', system.one)), the later duplicate stays Const in convert_target and the subsequent makeConvertingActions(..., ignore_constant_values = true) rewrites the real full column to the stale sample constant. Match duplicates positionally, or use the same per-name queue logic as makeConvertingActions.
Final Verdict
  • Status: ⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 17, 2026
@KochetovNicolai

Copy link
Copy Markdown
Member

The fix looks too complex.
Initially, UNION streams should have an identical structure. Mixed const and non-const columns should be allowed, common header should drop the const in this case. Different types are not allowed.

Filter-push-down can fold the constant, but this should not break the logic.

@groeneai
groeneai force-pushed the groeneai/fix-union-const-fold-header-106956 branch from 2441ef7 to 4493fad Compare June 17, 2026 16:51
@groeneai

Copy link
Copy Markdown
Collaborator Author

@KochetovNicolai Simplified, thanks. Pushed 4493fad.

The check now keeps assertCompatibleHeader (identical structure: same names and types, different types still rejected, plus the const-value equality check), and the only relaxation is that a Const may meet a full column — in which case the common header just drops the const for that column. Dropped the getLeastSuperColumn/supertype machinery; types are already guaranteed equal by the check above, so there was nothing to widen.

Filter-push-down folding a constant in one branch is handled by that single rule: the column becomes full in the common header. No-divergence plans return the front header unchanged.

Verified on a debug build: 04327 aborts before the change (SIGABRT, Code 49) and passes after, with output matching the reference; const-vs-const same-value still keeps the const.

Comment thread src/Processors/QueryPlan/UnionStep.cpp Resolved
@groeneai
groeneai force-pushed the groeneai/fix-union-const-fold-header-106956 branch from 4493fad to ffd0383 Compare June 17, 2026 18:05
@groeneai

Copy link
Copy Markdown
Collaborator Author

Good catch, confirmed. assertCompatibleHeader runs with allow_materialize=true, which getActualColumn uses to strip Const, Sparse, and Replicated, while the loop only dropped top-level Const, so a Sparse/full or Replicated/full divergence passed unnormalized.

Fixed by keeping the check strict except for top-level Const (direction a). Each branch is now compared to the front with only its top-level Const stripped via convertToFullColumnIfConst (which leaves Sparse/Replicated wrappers untouched), then validated with strict assertBlocksHaveEqualStructure. So only a Const meeting a full column is tolerated; different types and divergent Sparse/Replicated representations are rejected at plan time as before, and cannot leak into later pipeline construction.

convertToFullColumnIfConst is overridden only by ColumnConst (Block.cpp:49-62 / ColumnConst.h); ColumnSparse and ColumnReplicated inherit the IColumn no-op, so the strict compare still sees their distinct representation.

Verified: 04327 passes (20/20 with randomization); const/full UNION/INTERSECT/EXCEPT drop the const to full; all-const-agree keeps the front header unchanged; a top-level type difference is still rejected.

Pushed in ffd0383.

Comment thread src/Processors/QueryPlan/UnionStep.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixed in cfe8828. Took route (b): the common-header build now keeps a column Const only when every branch is Const with the same getField() value, otherwise it materializes (convertToFullColumnIfConst). This is the getLeastSuperColumn save_constness rule without reintroducing the supertype machinery, since the strict name/type/representation check already runs first. Applied identically in UnionStep and IntersectOrExceptStep.

While validating the all-Const-different-value case through actual execution I found the materialized output then aborted one pass later, after optimization liftUpUnion (optimizeTree.cpp header validation). tryLiftUpUnion assumes the union forwards each branch unchanged and rebuilds the UnionStep forcing every branch input header to the lifted step's full output, so a branch still exposing a Const no longer matches. It now skips the rewrite when the union output differs from any branch input header (i.e. the union normalized something).

Repro that exercises the execution path (both branches keep rows, same column folds to 1 and 0):

SELECT a, c FROM (
    SELECT t2.a AS a, (t1.b = t2.b) AS c
    FROM (SELECT 1 AS a, 2 AS b) AS t1 INNER JOIN (SELECT 1 AS a, 2 AS b) AS t2 ON t1.a = t2.a WHERE t1.b = t2.b
    UNION ALL
    SELECT t2.a AS a, NOT (t1.b = t2.b) AS c
    FROM (SELECT 1 AS a, 2 AS b) AS t1 INNER JOIN (SELECT 1 AS a, 2 AS b) AS t2 ON t1.a = t2.a WHERE t1.b = t2.b
) ORDER BY a, c;

On master this aborts at the original UnionStep::checkHeaders; before this commit it aborted at liftUpUnion. Test 04327 now covers UNION ALL / UNION DISTINCT / INTERSECT / EXCEPT for the all-Const-different-value case and passes 10/10 under randomization. Verified Sparse/full and Replicated/full are still rejected (convertToFullColumnIfConst leaves those wrappers untouched, so the strict compare rejects them).

session: cron:clickhouse-worker-slot-3:20260617-191100

@groeneai

Copy link
Copy Markdown
Collaborator Author

@KochetovNicolai CI surfaced a regression from the current commit (cfe88282) that I think needs your call before I push, since both fix locations touch contract-bearing code.

Repro (old analyzer only; pre-existing test 01418_query_scope_constants_and_remote):

SET enable_analyzer = 0;
SELECT c >= 0 FROM (SELECT randConstant() AS c FROM remote('127.0.0.{1,2}', numbers_mt(1)));
-- Code: 44. Cannot convert column `c` because it is non constant in source stream but must be constant in result.

Root cause: remote(2 shards) builds an internal UnionStep (ClusterProxy) whose branches are both Const c but with different per-shard values (randConstant bakes a value into each branch header). The same-value rule materializes c to full in the union output (correct for set-op semantics). But the old analyzer computes the surrounding result_header from the ExpressionAnalyzer sample block (Const c), independently of the plan, and InterpreterSelectQuery::buildQueryPlan then converts plan(full c) -> result_header(const c) and throws. The new analyzer is fine: the Planner derives the common header from the same getLeastSuperColumn over plan headers, so plan and result_header always agree.

The same-value rule should stay (dropping it brings back a silent wrong result for c=1 UNION ALL c=0, and the original #106956 crash). The mismatch is purely the old analyzer's separately-computed Const result_header not matching a column the plan legitimately materialized to full.

Two fix points, both with caveats:

  1. makeConvertingActions: when ignore_constant_values = true and the result is Const but the source is full, keep the source full instead of throwing. Smallest, but makeConvertingActions is shared by many callers.
  2. InterpreterSelectQuery::buildQueryPlan (old analyzer only): reconcile result_header constness with the actual plan header before converting. Localized, but result_header also feeds getSampleBlock(), so it changes what an enclosing subquery sees.

Do you have a preference, or a third option I'm missing?

@Algunenano

Copy link
Copy Markdown
Member

@groeneai The failure to 01418_query_scope_constants_and_remote is related.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@Algunenano Yes, that one is the known PR-caused regression from this commit (cfe88282), already root-caused, not infra.

Mechanism: remote('127.0.0.{1,2}', ...) builds an internal UnionStep whose two shard branches are both Const c but with different baked randConstant() values, so the new same-value rule materializes c to full in the union output (correct for set-op semantics). Under the old analyzer the surrounding result_header is computed separately from the ExpressionAnalyzer sample block as Const c, so InterpreterSelectQuery::buildQueryPlan then converts plan(full c) -> result_header(Const c) and throws Code 44. The new analyzer is fine: the Planner derives the common header from the same plan headers, so plan and result_header always agree.

The same-value materialize rule should stay (dropping it reintroduces a silent wrong result for c=1 UNION ALL c=0, plus the original #106956 crash). The clean reconciliation touches contract-bearing code, so I posed two options to KochetovNicolai and am holding the push until a maintainer picks: (1) makeConvertingActions, when ignore_constant_values=true and the result is Const but the source is full, keep the source full instead of throwing (smallest, but shared by many callers); (2) old-analyzer buildQueryPlan, reconcile result_header constness with the actual plan header before converting (localized, but result_header also feeds getSampleBlock()). Full analysis and repro: #107719 (comment #107719 (comment)).

Do you have a preference between the two? I lean to (2) as the more localized change, but it is your and KochetovNicolai's call.

@Algunenano

Copy link
Copy Markdown
Member

Do you have a preference between the two? I lean to (2) as the more localized change, but it is your and KochetovNicolai's call.

@KochetovNicolai Can you please have a look? I think breaking the old analyzer isn't ok, and adding more code there seems like an ok thing to avoid adding complexity to the code that should remain in the future. So I'd prefer option 2. WDTY?

@groeneai

Copy link
Copy Markdown
Collaborator Author

Confirmed, option 2 it is: keep the same-value materialize rule and reconcile the old-analyzer result_header constness inside InterpreterSelectQuery::buildQueryPlan before the convert, leaving the new analyzer and the shared makeConvertingActions path untouched.

Ready to push as soon as you or KochetovNicolai give the go; if KochetovNicolai is tied up I am happy to proceed on your call as assignee. Before pushing I will re-validate 01418 on both analyzers, the 04327 all-const-different-value cases, and the original #106956 repro so the regression does not come back.

alexey-milovidov and others added 3 commits July 19, 2026 15:46
…hildren

Review claimed the old-analyzer parent `UNION`/`INTERSECT`/`EXCEPT`
interpreters still convert a materialized child back to a stale `Const`
sample header (`Cannot convert column ... must be constant in result`).
This does not reproduce: branch headers only diverge during plan
optimization, which runs after the parent interpreters have decided
their "Conversion before UNION" steps, and the execution-time
`updatePipeline` conversion tolerates `Const` meeting a full column.
Pin the claimed shapes (`serverUUID`/`randConstant` over
`remote('127.0.0.{1,2}')` under parent `UNION ALL`/`UNION DISTINCT`/
`INTERSECT ALL`/`EXCEPT ALL`, `enable_analyzer = 0`) as regression
cases in `04327_union_branch_const_header_mismatch`.

Co-Authored-By: Claude Fable 5 <[email protected]>
The analyzer has been enabled by default since ClickHouse 24.3 and is no
longer "new"; the style check `ci/jobs/scripts/check_style/various_checks.sh`
rejects the phrase "new analyzer". This failure gated the whole pipeline
(builds, `Fast test`, `Code Review`, and the `Bugfix validation` functional
tests job were all dropped), which in turn made `new_tests_check.py` fail
because no per-arch Bugfix Validation job could run.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Processors/QueryPlan/UnionStep.cpp Resolved
…y top-level Const in checkHeaders

Two fixes from the latest CI round:

1. AST fuzzer (amd_debug, targeted, old_compatibility) found a query where the
   fixed plan-time check admitted a branch whose pipeline carries a totals port
   (`WITH TOTALS`): `IntersectOrExceptStep::updatePipeline` guarded the converting
   expression with `isCompatibleHeader`, which tolerates a `Const` meeting a full
   column, so no conversion was applied and the branch's totals port kept its
   `Const` header while the step's output header materialized the column. The
   per-stream structure check in a downstream `DistinctStep` then threw
   `Block structure mismatch in QueryPipeline stream`. Use the strict
   `blocksHaveEqualStructure` guard, same as `UnionStep::updatePipeline`:
   `addSimpleTransform` applies the converting expression to the totals and
   extremes ports too. Added both `INTERSECT DISTINCT` and `EXCEPT DISTINCT`
   shapes to `04327_union_branch_const_header_mismatch`.

   Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107719&sha=24107526ff1449f7c7fae761354826cdcf7f0239&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29

2. Address AI review: guard the top-level-`Const` strip in `checkHeaders` with
   `isColumnConst`. `convertToFullColumnIfConst` is broader for some columns
   (`ColumnArray` materializes const nested data too), so the unguarded call also
   admitted `Array(Const(T))` meeting `Array(T)`, which the execution-time
   conversion path does not reconcile. With the guard, nested-const divergence is
   rejected at plan time exactly as before this PR.

Related: ClickHouse#107719
{
if (!res_col.column || !isColumnConst(*res_col.column))
continue;
const auto * plan_col = plan_header.findByName(res_col.name);

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.

Block headers can legitimately contain duplicate output names, and makeConvertingActions handles them by matching same-name columns in order. This reconciliation uses findByName, which only returns the first occurrence. If only a later duplicate is materialized by the plan (for example SELECT toUInt32(42) AS c, randConstant() AS c FROM remote('127.0.0.{1,2}', system.one) under the old analyzer), the second loop iteration still sees the first c, leaves the later convert_target entry as Const, and the follow-up makeConvertingActions(..., ignore_constant_values = true) rewrites the materialized column to the stale sample constant instead of preserving the full stream. Please match duplicates positionally or with the same per-name queue logic as makeConvertingActions.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Verified on the current head (debug build):

The mechanism is real. makeConvertingActions matches same-name columns with a per-name FIFO queue (ActionsDAG.cpp:2145-2183, std::list<size_t> + pop_front), while this loop uses findByName (first occurrence only). But I could not construct a query that reaches this loop with a Const result-header column whose same-named plan sibling is full at a later position:

  • The literal example is rejected before planning. SELECT toUInt32(42) AS c, randConstant() AS c FROM remote('127.0.0.{1,2}', system.one) throws MULTIPLE_EXPRESSIONS_FOR_ALIAS (Code 179) under both analyzers and single-node: two different expressions cannot share an explicit alias, so it never reaches buildQueryPlan.
  • Duplicate names via a column reference collapse upstream. SELECT c, c2 AS c FROM (SELECT toUInt32(100) AS c, toUInt32(200) AS c2) returns 200 200 on master under both analyzers (a pre-existing name-collision, separate from this PR); EXPLAIN header=1 shows Output: materialize(200), materialize(200), i.e. both outputs are the same full node. Both are full, so the isColumnConst guard skips both and the loop is a no-op.

So today the stale-const rewrite is unreachable at this point. I did not change the loop because I cannot back the change with a failing test. The asymmetry is a latent risk only if the duplicate-name collapse is later fixed so that per-position const/full divergence survives to here. If you have a concrete query that reaches the loop with a materialized later duplicate, I will switch it to the same per-name queue as makeConvertingActions and add it to 04327.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks, verified ced56bb6150 on a fresh debug build against a 2-shard remote('127.0.0.{1,2}') topology:

  • 04327 matches the reference exactly, including the two new totals-port cases.
  • The isColumnConst guard is correct: with the strip reverted to unguarded convertToFullColumnIfConst it normalizes ColumnArray nested const, which the execution-time path can't reconcile; the guard keeps master's Array(Const(T)) vs Array(T) rejection.
  • The totals-port fix is load-bearing: reverting just that line to isCompatibleHeader and rebuilding reproduces Block structure mismatch in QueryPipeline stream (Const-vs-full totals port) on the STID 0993-2a62 INTERSECT DISTINCT case; strict compare passes it.

On 07-19 "does not reproduce": agreed, and re-confirmed here. The nested parent-setop shapes (union-of-union, INTERSECT ALL/EXCEPT ALL, 3-branch mixed const, WHERE push-down) all pass under enable_analyzer = 0 because the parent interpreter fixes its convert targets during buildQueryPlan, before optimization materializes the divergent Const. Pinning them as regressions rather than adding unreachable parent-interpreter code is the right call.

@clickhouse-gh

clickhouse-gh Bot commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 78.20% 78.20% +0.00%

Changed lines: Changed C/C++ lines covered: 90/90 (100.00%) · Uncovered code

Full report · Diff report

@fm4v
fm4v added this pull request to the merge queue Jul 20, 2026
Merged via the queue into ClickHouse:master with commit 851d5f4 Jul 20, 2026
175 of 178 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added 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 labels Jul 20, 2026
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 20, 2026
clickhouse-gh Bot added a commit that referenced this pull request Jul 20, 2026
Backport #107719 to 26.6: Fix Block structure mismatch in UnionStep/IntersectOrExceptStep when a branch constant-folds
UnamedRus pushed a commit to UnamedRus/ClickHouse that referenced this pull request Aug 12, 2026
…nionStep/IntersectOrExceptStep when a branch constant-folds
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…y top-level Const in checkHeaders

Two fixes from the latest CI round:

1. AST fuzzer (amd_debug, targeted, old_compatibility) found a query where the
   fixed plan-time check admitted a branch whose pipeline carries a totals port
   (`WITH TOTALS`): `IntersectOrExceptStep::updatePipeline` guarded the converting
   expression with `isCompatibleHeader`, which tolerates a `Const` meeting a full
   column, so no conversion was applied and the branch's totals port kept its
   `Const` header while the step's output header materialized the column. The
   per-stream structure check in a downstream `DistinctStep` then threw
   `Block structure mismatch in QueryPipeline stream`. Use the strict
   `blocksHaveEqualStructure` guard, same as `UnionStep::updatePipeline`:
   `addSimpleTransform` applies the converting expression to the totals and
   extremes ports too. Added both `INTERSECT DISTINCT` and `EXCEPT DISTINCT`
   shapes to `04327_union_branch_const_header_mismatch`.

   Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107719&sha=24107526ff1449f7c7fae761354826cdcf7f0239&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29

2. Address AI review: guard the top-level-`Const` strip in `checkHeaders` with
   `isColumnConst`. `convertToFullColumnIfConst` is broader for some columns
   (`ColumnArray` materializes const nested data too), so the unguarded call also
   admitted `Array(Const(T))` meeting `Array(T)`, which the execution-time
   conversion path does not reconcile. With the guard, nested-const divergence is
   rejected at plan time exactly as before this PR.

Related: ClickHouse#107719
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…-const-fold-header-106956

Fix Block structure mismatch in UnionStep/IntersectOrExceptStep when a branch constant-folds
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-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.6-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Logical error: Block structure mismatch in UnionStep stream (Const vs full column) from ActionsDAG self-deduplication across UNION branches

8 participants