Repository navigation
Fix Block structure mismatch in UnionStep/IntersectOrExceptStep when a branch constant-folds - #107719
Conversation
Pre-PR validation gate
Session id: cron:clickhouse-worker-slot-3:20260617-103600 |
|
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. |
|
Workflow [PR], commit [ced56bb] Summary: ❌
AI ReviewSummaryThis PR fixes PR Metadata
Findings
|
|
The fix looks too complex. Filter-push-down can fold the constant, but this should not break the logic. |
2441ef7 to
4493fad
Compare
|
@KochetovNicolai Simplified, thanks. Pushed The check now keeps 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: |
4493fad to
ffd0383
Compare
|
Good catch, confirmed. Fixed by keeping the check strict except for top-level
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. |
ffd0383 to
cfe8828
Compare
|
Fixed in cfe8828. Took route (b): the common-header build now keeps a column While validating the all- Repro that exercises the execution path (both branches keep rows, same column folds to 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 session: cron:clickhouse-worker-slot-3:20260617-191100 |
|
@KochetovNicolai CI surfaced a regression from the current commit ( Repro (old analyzer only; pre-existing test 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: The same-value rule should stay (dropping it brings back a silent wrong result for Two fix points, both with caveats:
Do you have a preference, or a third option I'm missing? |
|
@groeneai The failure to |
|
@Algunenano Yes, that one is the known PR-caused regression from this commit ( Mechanism: The same-value materialize rule should stay (dropping it reintroduces a silent wrong result for 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? |
|
Confirmed, option 2 it is: keep the same-value materialize rule and reconcile the old-analyzer 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. |
…const-fold-header-106956
…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]>
…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); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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)throwsMULTIPLE_EXPRESSIONS_FOR_ALIAS(Code 179) under both analyzers and single-node: two different expressions cannot share an explicit alias, so it never reachesbuildQueryPlan. - Duplicate names via a column reference collapse upstream.
SELECT c, c2 AS c FROM (SELECT toUInt32(100) AS c, toUInt32(200) AS c2)returns200 200on master under both analyzers (a pre-existing name-collision, separate from this PR);EXPLAIN header=1showsOutput: materialize(200), materialize(200), i.e. both outputs are the same full node. Both are full, so theisColumnConstguard 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.
|
Thanks, verified
On 07-19 "does not reproduce": agreed, and re-confirmed here. The nested parent-setop shapes (union-of-union, |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 90/90 (100.00%) · Uncovered code |
851d5f4
Backport #107719 to 26.6: Fix Block structure mismatch in UnionStep/IntersectOrExceptStep when a branch constant-folds
…nionStep/IntersectOrExceptStep when a branch constant-folds
…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
…-const-fold-header-106956 Fix Block structure mismatch in UnionStep/IntersectOrExceptStep when a branch constant-folds
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a
Block structure mismatch in UnionStep streamlogical error (server abort on debug/sanitizer builds,Code: 49on release builds) that occurred when sibling branches of aUNION/INTERSECT/EXCEPTdiffered only in theirWHEREpredicate and one branch's predicate constant-folded to aConstcolumn.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:
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 columnConstwhile the sibling keeps a full column. The plan-time header check inUnionStep::updateOutputHeader/IntersectOrExceptStep::updateOutputHeaderused strictassertBlocksHaveEqualStructureand rejected the divergent constness, even though the execution-time path (updatePipeline) already tolerates exactly this viamakeConvertingActions.The fix makes the plan-time check tolerant the same way: it requires matching column names and types but allows a
Constto meet a full column, and computes the common header withgetLeastSuperColumn(the primitive the planner already uses to build the union header) so a column staysConstonly 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(coveringUNION ALL,UNION DISTINCT,SELECT DISTINCT, an explicitCAST(..., 'Nullable(UInt8)')projection,INTERSECT, andEXCEPT).Related: #107951 (a second path to the same
IntersectOrExceptStepdivergence).Related: #107953 (STID 0993-28b7: an AST-fuzzer query reaches the same
UnionStep::updateOutputHeaderConst-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-levelConststripped (the strip is guarded byisColumnConst, soSparse/Replicateddivergences and nested constness such asArray(Const(T))vsArray(T)stay rejected), and the common header keeps a columnConstonly when every branch isConstwith the same value, materializing otherwise. This replaces the earliergetLeastSuperColumnformulation while keeping the same behavior for ordinary set operations.At pipeline-build time, both
UnionStepandIntersectOrExceptStepguard their converting expression with the strictblocksHaveEqualStructure(the intersect step previously used the laxisCompatibleHeader), 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 hasWITH TOTALS(found by the AST fuzzer; pinned in the test).The old analyzer computes
result_headerfrom the sample block independently of the plan, so a column the plan legitimately materialized (for examplerandConstant()overremote(...)whose shards fold to different values) stayedConstinresult_headerandmakeConvertingActionsrejected the full-vs-Const conversion (01418_query_scope_constants_and_remote).InterpreterSelectQuery::buildQueryPlannow takes the plan's full column into the local convert target where the plan is full butresult_headerisConstof the same type, leavingresult_headeritself untouched. The new analyzer already derivesresult_headerfrom 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 staleConstsample header. Verified against a live 2-shardremote('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; theConstdivergence only appears during plan optimization, after those targets are fixed, and the execution-time conversion tolerates it. All claimed shapes (parentUNION ALL/UNION DISTINCT/INTERSECT/EXCEPToverserverUUID()/randConstant()remote children underenable_analyzer = 0) are pinned as regression cases in04327_union_branch_const_header_mismatch.Version info
26.7.1.1214(included in26.7and later)26.6.2.84