Skip to content

Fix Block structure mismatch after liftUpUnion with divergent aggregate state types - #110745

Open
groeneai wants to merge 9 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-liftupunion-agg-state-type-mismatch
Open

groeneai wants to merge 9 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-liftupunion-agg-state-type-mismatch

Conversation

@groeneai

@groeneai groeneai commented Jul 16, 2026 •

Copy link
Copy Markdown
Collaborator

No related open issue found.

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):

Fix a LOGICAL_ERROR "Block structure mismatch in after optimization liftUpUnion" (server abort in debug and sanitizer builds) that could occur for a query with an expression or preliminary DISTINCT above a UNION ALL whose branches produce aggregate-function state columns that share the same state representation but different type names (for example quantileExactTupleState and quantilesExactTupleState).

Description

tryLiftUpUnion pushes the parent Expression/Distinct step into each union branch, assuming the union forwards every branch unchanged. That assumption breaks when a branch column matches the union output only loosely: two AggregateFunction columns can share the same state representation yet print different type names (e.g. quantileExactTuple vs quantilesExactTuple(0.9)), so blocksHaveEqualStructure treats them as equal and the union output takes the first branch's type. The union coerces the diverging branch at runtime via a converting step; pushing the parent down bypasses that coercion and produces branch headers that no longer match, tripping the post-optimization checkHeaders assertion.

The fix lifts the parent only when every branch input header is identical (same name and same type name) to the union output. The optimization still fires for genuine same-type unions.

Found by the AST fuzzer (Stress test, amd_tsan; CIDB STID 0993-23fd).

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse-local -q "EXPLAIN header=1 SELECT tuple(s) AS ts FROM (SELECT quantileExactTupleState((toUInt32(number), toFloat64(number))) AS s FROM numbers(100, 1) UNION ALL SELECT quantilesExactTupleState(0.9)((toUInt32(number), toFloat64(number))) AS s FROM numbers(101, 257))" aborts 100% on unpatched debug builds.
b Root cause explained? Yes. The two UNION ALL branches produce AggregateFunction(quantileExactTuple,...) and AggregateFunction(quantilesExactTuple(0.9),...). These share the same state representation, so blocksHaveEqualStructure (via haveSameStateRepresentation) treats them as equal and the union output takes branch 0's type. tryLiftUpUnion then pushes the parent Expression (tuple(s)) into each branch, bypassing the union's runtime coercion; the rebuilt branch header for branch 1 keeps quantilesExactTuple(0.9) while the new union expects quantileExactTuple, so the post-optimization checkHeaders assertion fails.
c Fix matches root cause? Yes. tryLiftUpUnion now bails out unless every branch input header is identical (same name and type name) to the union output — exactly the loose-match case that made the rewrite unsafe.
d Test intent preserved / new tests added? New stateless test 04545_lift_up_union_agg_state_type_mismatch covers both the Expression and preliminary-DISTINCT lift-up variants of the divergent-agg-state union, plus a same-type union to confirm the optimization still applies.
e Both directions demonstrated? Yes. Test SIGABRTs (exit 134) on the pristine binary; passes and matches the reference with the fix, both on a rebuilt Build-ID-verified binary.
f Fix is general across code paths? Yes. The guard is added once at the top of tryLiftUpUnion, covering both rewrites (Expression and Distinct). No sibling optimization performs the same unchecked lift over a union.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. The check compares type names for all columns, so any loose-match divergence (any aggregate function whose parameters do not affect state, and any type-name mismatch tolerated by blocksHaveEqualStructure) is caught, not just quantileExactTuple.
h Backward compatible? (maintainer-approved exception only) Yes. Pure query-plan optimization guard; no setting default, on-disk/wire format, or validation change. The optimization still fires for all previously-valid same-type unions.
i Invariants and contracts preserved? Yes. Upholds tryLiftUpUnion's documented invariant ("union does not change header") by only proceeding when it actually holds; the block-structure invariant checked by checkHeaders now holds on all paths.

Session id: cron:clickhouse-worker-slot-0:20260716-201600

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @davenger — could you review this? tryLiftUpUnion pushes the parent Expression/Distinct step into each UNION branch assuming the union forwards branches unchanged; when two branches produce aggregate-state columns with the same state representation but different type names (quantileExactTuple vs quantilesExactTuple(0.9)), the union coerces one branch at runtime and lifting the parent bypasses that coercion, tripping the post-optimization block-structure assertion. The guard now lifts only when every branch header is identical to the union output.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 16, 2026
@groeneai groeneai closed this Jul 17, 2026
@groeneai groeneai reopened this Jul 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bb35bed]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, WasmEdge, parallel, 2/3) FAIL
Server died FAIL cidb
03129_format_row_json_http UNKNOWN cidb
02428_decimal_in_floating_point_literal UNKNOWN cidb
Logical error: Arguments of 'A' have incorrect data types: 'B' of type 'C', 'D' of type 'E (STID: 2735-47bf) FAIL cidb
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 hardens UNION/set-op branch homogenization for divergent aggregate-state types across the optimizer, planner, legacy analyzer, and Variant carriers. Most of the previously reported gaps are fixed on the current head, but createVariantToVariantWrapper still resolves an unmatched source member to the first equals()-equal destination member, which can silently rewrite a suspicious Variant to the wrong aggregate state when allow_suspicious_variant_types = 1, so I would still request changes.

Findings
❌ Blockers
  • [src/Functions/FunctionsConversion.cpp:1921] The new Variant fallback no longer preserves the documented “extension only” contract when the destination Variant contains more than one equals()-equal aggregate-state alternative under allow_suspicious_variant_types = 1. old_type->equals(*new_variants[j]) can match multiple candidates (for example AggregateFunction(quantilesExactTuple(0.5), ...) and AggregateFunction(quantilesExactTuple(0.9), ...)), but the loop stops at the first unmapped one. That means a source member such as AggregateFunction(quantileExactTuple, ...) can be rewritten to an arbitrary target alternative, changing later Variant subcolumn selection and finalize semantics instead of either preserving the exact member or rejecting the cast as ambiguous.
    Suggested fix: accept the fallback only when there is exactly one equals()-equal candidate. If there are zero candidates, keep throwing CANNOT_CONVERT_TYPE; if there are multiple candidates, throw as ambiguous instead of picking one. Add a focused regression with allow_suspicious_variant_types = 1 that exercises multiple equals()-equal aggregate-state members in the destination Variant.
Final Verdict
  • Status: ⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 17, 2026
…gent aggregate state types

Rewrites that push a step (Expression/Distinct lift-up in liftUpUnion, filter
push-down in filterPushDown) through a UnionStep clone that step into every
branch, assuming the union forwards each branch unchanged. That assumption
breaks when a branch column matches the union output only loosely: two
AggregateFunction columns can share the same state representation yet print
different type names (e.g. quantileExactTuple vs quantilesExactTuple(0.9)), so
blocksHaveEqualStructure treats them as equal and the union output takes the
first branch's type. The union coerces the diverging branch at runtime via a
converting step; pushing the step down bypasses that coercion and produces
branch headers that no longer match, tripping the post-optimization 'Block
structure mismatch' LOGICAL_ERROR (server abort in debug/sanitizer builds).

Factor the precondition into canPushStepThroughUnion (every branch input header
identical, same name and type name, to the union output) and apply it to both
the liftUpUnion rewrites and the tryPushDownFilter Filter -> Union rewrite.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the groeneai/fix-liftupunion-agg-state-type-mismatch branch from fc5a9a8 to 9063d53 Compare July 17, 2026 02:16
@groeneai

Copy link
Copy Markdown
Collaborator Author

Addressed in 9063d53. Factored the precondition into a shared helper `canPushStepThroughUnion(const UnionStep &)` (returns true only when every branch input header is identical, same name and type name, to the union output) and applied it to both `tryLiftUpUnion` (Expression and Distinct lift-up) and `tryPushDownFilter` (Filter -> Union at filterPushDown.cpp).

Audited the other UnionStep sites: only these two clone a step into each branch off the union output header. `limitPushDown` inserts a per-branch LimitStep built from each branch's own output header (no rebuilt union, no coercion bypass), so it is not affected; the remaining sites (applyOrder, enableMemoryBoundMerging, considerEnablingParallelReplicas, makeDistributed, optimizeReadInOrder) do not push a step through the union.

Extended the regression test with the Filter -> Union shape you described. It reproduces the crash at `after optimization pushDownFilter` on the pristine binary and passes with the fix:

  • bare divergent aggregate state in the UNION ALL branches (union builds via the state-representation-tolerant header check)
  • `tuple(s)` wraps the state above the union
  • `WHERE c > 0` on a sibling column stays above the union so the filter is cloned into each branch

Confirmed the guard does not over-block: filter push-down and both lift-up rewrites still fire for genuine same-type unions.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Two shapes on a pristine debug binary abort with SIGABRT (exit 134): the liftUpUnion Expression/Distinct variant (after optimization liftUpUnion) and the new Filter -> Union variant (after optimization pushDownFilter, confirmed via gdb context_description). Both pass with the fix.
b Root cause explained? Two AggregateFunction columns can share the same state representation but print different type names (quantileExactTuple vs quantilesExactTuple(0.9)). blocksHaveEqualStructure uses the state-tolerant haveSameStateRepresentation for bare agg columns, so the union output takes branch 0's type and coerces branch 1 at runtime. A rewrite that clones a step (Expression/Distinct/Filter) into each branch bypasses that coercion; the rebuilt branch header keeps branch 1's type while the new union expects branch 0's, and the strict post-optimization checkHeaders (which compares getName() once the column is wrapped in a tuple) throws.
c Fix matches root cause? Yes. canPushStepThroughUnion bails the rewrite out unless every branch input header is identical (same name AND type name) to the union output, i.e. exactly the loose-match case that the runtime coercion would otherwise handle.
d Test intent preserved / new tests added? New stateless test 04545 covers all three rewrites (Expression lift-up, Distinct lift-up, Filter -> Union) plus a same-type union that must still be optimized. No existing test weakened.
e Both directions demonstrated? Yes. Pristine binary: SIGABRT on both signatures. Fixed binary (Build ID 006ad927...): all 04545 cases pass, output matches reference.
f Fix is general across code paths? Yes. Factored into one shared helper and applied to every rewrite that clones a step into union branches (tryLiftUpUnion Expression + Distinct, tryPushDownFilter). Audited the other UnionStep sites; limitPushDown uses per-branch headers (safe), the rest do not push steps through the union.
g Fix generalizes across inputs? The guard is type-name-agnostic: it triggers for any divergent-branch case (agg-state name divergence is the concrete instance; any name/type mismatch is caught). Same-type unions (including plain columns) are unaffected, verified by EXPLAIN.
h Backward compatible? Yes. Query-plan optimization internals only; no setting, format, or on-disk change. The guard only skips an unsafe rewrite (falls back to the correct un-pushed plan).
i Invariants and contracts preserved? Yes. Upholds the block-structure invariant checkHeaders enforces (branch input header == cloned-step output header). The helper reads headers only; both rewrites keep their existing behavior when the precondition holds.

Session id: cron:clickhouse-worker-slot-3:20260717-015300

@groeneai

Copy link
Copy Markdown
Collaborator Author

Done in the current head (9063d53), pushed after this review was posted against fc5a9a8.

The predicate is now a shared helper canPushStepThroughUnion(const UnionStep &) (declared in Optimizations.h, defined in liftUpUnion.cpp) that returns true only when every branch input header is identical (same name and type name) to the union output. It is applied to both rewrites that clone a step into each branch:

  • tryLiftUpUnion (Expression/Distinct lift-up), liftUpUnion.cpp
  • tryPushDownFilter Filter -> Union rewrite, filterPushDown.cpp:1186 (bails out before the UnionStep rebuild you flagged at 1181-1215)

Regression 04545_lift_up_union_agg_state_type_mismatch covers the Filter -> Union shape you described: bare divergent aggregate state in the UNION ALL branches, tuple() above the union, and a WHERE on a sibling column so the filter clones into each branch.

Verified on a debug binary both directions: with the filterPushDown guard the query returns a row (reference matches); with the guard removed it aborts on the post-optimization block-structure LOGICAL_ERROR ("after optimization pushDownFilter", checkHeaders).

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 9063d53

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted) + (targeted, old_compatibility) / Block structure mismatch (STID 0993-2a62) PR-caused — fuzzer mutated this PR test 04545 and hit a residual "Block structure mismatch in QueryPipeline stream" on the exact quantileExactTupleState vs quantilesExactTupleStateOrNull UNION ALL family this PR targets; the fix does not yet cover this reachable path PR-caused → fixing in this PR
Stateless tests (arm_binary, parallel) / 01730_distributed_group_by_no_merge_order_by_long flaky (14 master hits + 15+ unrelated PRs in 30d; MEMORY_LIMIT in distributed GROUP BY, unrelated to liftUpUnion) #109847 (external, open)

Session id: cron:our-pr-ci-monitor:20260717-070000

The AST fuzzer found a Block structure mismatch reachable with query plan
optimizations disabled, so the residual mismatch is in the base planner, not
in the liftUpUnion / tryPushDownFilter guards.

A UNION ALL whose branches produce aggregate-state columns sharing state
representation but differing by type name (quantileExactTuple vs
quantilesExactTuple(0.9)) picks one branch type as the common union header in
buildCommonHeaderForUnion. addConvertingToCommonHeaderActionsIfNeeded then
skipped the conversion for the other branch: blocksHaveEqualStructure and
makeConvertingActions both treat the two aggregate-state types as equal. The
branch kept physically emitting its own type while the union output advertised
the common type, so a step above the union that wraps the column (tuple(s))
built a column whose name embeds the branch aggregate function name, and the
strict per-stream checkBlockStructure aborted at pipeline build.

Force the conversion, and an explicit CAST, whenever a branch column type name
diverges from the common header so every branch physically emits the common
type.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

The AST fuzzer failure on the previous head (STID 0993-2a62, Block structure mismatch in ... stream) is a deeper variant of the same class, and it reproduces with query_plan_enable_optimizations = 0 — so the residual mismatch is in the base planner, not in the liftUpUnion / tryPushDownFilter optimization guards.

Root cause: a UNION ALL whose branches produce aggregate-state columns sharing state representation but differing by type name (quantileExactTuple vs quantilesExactTuple(0.9)) picks one branch's type as the common header in buildCommonHeaderForUnion. addConvertingToCommonHeaderActionsIfNeeded then skipped the conversion for the other branch, because both blocksHaveEqualStructure and makeConvertingActions' CAST decision (type->equals()) treat the two aggregate-state types as equal. The branch kept physically emitting its own type while the union output advertised the common type; a step above the union that wraps the column (tuple(s)) then built a column whose name embeds the branch aggregate function name, and the strict per-stream checkBlockStructure aborted at pipeline build.

Fix (3d81a4f): in addConvertingToCommonHeaderActionsIfNeeded, force the conversion — and an explicit CAST — whenever a branch column's type name diverges from the common header, so every branch physically emits the common type. Verified fails-without / passes-with on a Build-ID-pinned debug binary, both with optimizations on and off; INTERSECT/EXCEPT and plain type coercion unaffected. The exact fuzzer-reduced query is added to 04545.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (commit 3d81a4f, click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT tuple(s) FROM (SELECT quantileExactTupleState((toUInt32(number),toFloat64(number))) AS s FROM numbers(100,5) GROUP BY number%2 UNION ALL SELECT quantilesExactTupleState(0.9)(...) AS s FROM numbers(7) GROUP BY ALL) aborts every time (SIGABRT), including with query_plan_enable_optimizations=0, plus the exact AST-fuzzer-reduced query.
b Root cause explained? buildCommonHeaderForUnion picks one branch's aggregate-state type (quantileExactTuple) as the union common header. addConvertingToCommonHeaderActionsIfNeeded skipped converting the other branch because blocksHaveEqualStructure and makeConvertingActions' CAST decision (type->equals()) both treat the two agg-state types (same state repr, different name) as equal. The branch kept physically emitting quantilesExactTuple while the union advertised quantileExactTuple; a step above the union wrapping the column (tuple(s)) built a column whose name embeds the branch function name, and the strict per-stream checkBlockStructure aborted at pipeline build.
c Fix matches root cause? Yes. In addConvertingToCommonHeaderActionsIfNeeded, force the conversion — and an explicit addCast — whenever a branch column's type NAME diverges from the common header, so every branch physically emits the common type. Fix is in the base planner (where the bug reproduces with optimizations off), not a symptom guard.
d Test intent preserved / new tests added? Yes. 04545 extended: base-planner variant with optimizations OFF + the exact fuzzer query; the same-type-union case still asserts the optimization applies. Reference regenerated.
e Both directions demonstrated? Yes. Baseline (fix reverted, Build ID ea424823): fuzzer query SIGABRT (RC=134). With fix (Build ID 0521e40e): RC=0, all 04545 cases pass, opt on and off.
f Fix is general across code paths? Yes. The single planner conversion covers UNION ALL, UNION DISTINCT, and INTERSECT/EXCEPT (all route through addConvertingToCommonHeaderActionsIfNeeded); verified INTERSECT/EXCEPT no longer abort. The liftUpUnion/tryPushDownFilter guards remain as defense for the optimization rewrites.
g Fix generalizes across inputs? Yes. Verified with Nullable agg states (*OrNull), 3-branch divergent unions, reversed branch order (common type from either branch), and boundary aggregate arities. Plain scalar type coercion (Int8/Int64) unaffected.
h Backward compatible? Yes. No setting default, on-disk/wire format, or validation change. Only makes the planner insert a conversion that was previously (incorrectly) skipped; query results are correct (finalized states match).
i Invariants and contracts preserved? Yes. Restores the union invariant that every branch pipeline physically emits the union output header type — the invariant the downstream strict checkBlockStructure relies on. The forced CAST between same-representation agg-state types is a valid no-op-on-bytes relabel (confirmed a real CAST produces the target type and finalizes correctly).

Session id: cron:clickhouse-worker-slot-6:20260717-071000

Comment thread src/Planner/Utils.cpp Resolved
… type

The AST fuzzer found a residual "Block structure mismatch in UnionStep
stream" abort (STID 0993-27f0) for a UNION ALL whose branches carry an
aggregate state nested inside a composite column, e.g. the -StateTuple
combinator returning Tuple(AggregateFunction(quantileExactTuple, ...)) vs
Tuple(AggregateFunction(quantilesExactTuple(0.9), ...)).

buildCommonHeaderForUnion picks one branch's Tuple(agg) type as the common
header and addConvertingToCommonHeaderActionsIfNeeded inserts a CAST to it.
But FunctionCast::prepareImpl took an identity wrapper: the two Tuple(agg)
types compare equal() (IDataType::equals is tolerant of aggregate states
sharing the same representation but differing by function name), and the
top-level type is DataTypeTuple, so the bare-DataTypeAggregateFunction
strictEquals guard did not apply. The identity wrapper passed the source
column through unchanged, so the branch kept emitting its original aggregate
function while the union type advertised another. ColumnTuple::getName embeds
the nested ColumnAggregateFunction function name, so the strict per-stream
block-structure check aborted at plan build (reproduces with
query_plan_enable_optimizations = 0).

Extend the strict-identity guard to composite types: skip the identity
wrapper when the two equal() types contain an aggregate-function subtype that
is not strictEquals, so the real recursive Tuple/Array/Map wrapper rebuilds
each aggregate column with the target function.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Extended the fix to the AST-fuzzer-found variant STID 0993-27f0 ("Block structure mismatch in UnionStep stream: different columns: s Tuple(AggregateFunction(quantileExactTuple, Tuple(UInt32, Float64)))"), found on the prior head 3d81a4f.

Why the previous commit did not cover it. Commit 3d81a4f homogenizes divergent aggregate-state branch types before the union by inserting a CAST to the common header. That works when the divergent aggregate state is the top-level branch column. STID 0993-27f0 nests it inside a composite column: the -StateTuple combinator returns Tuple(AggregateFunction(quantileExactTuple, ...)) vs Tuple(AggregateFunction(quantilesExactTuple(0.9), ...)). The CAST is inserted, but FunctionCast::prepareImpl took an identity wrapper for it: the two Tuple(agg) types compare equals() (IDataType::equals is tolerant of aggregate states sharing the same representation but differing by function name), and since the top-level type is DataTypeTuple the existing bare-DataTypeAggregateFunction strictEquals guard did not apply. The identity wrapper passes the source column through unchanged, so the branch keeps emitting its original aggregate function while the union type advertises the other. ColumnTuple::getName embeds the nested ColumnAggregateFunction function name, so the strict per-stream block-structure check aborts at plan build. It reproduces with query_plan_enable_optimizations = 0 (base planner), independent of the liftUpUnion/tryPushDownFilter guards.

Fix. Extend the strict-identity guard in prepareImpl to composite types: skip the identity wrapper when the two equals()-equal types contain an aggregate-function subtype that is not strictEquals, so the real recursive Tuple/Array/Map CAST wrapper rebuilds each aggregate column with the target function.

CI report (0993-27f0): https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110745&sha=3d81a4f7a785af96b471ff5634baf9bb12f10e55&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29

Verified both directions on a Build-ID-pinned debug binary (worktree, fix Build ID 0642bf25 / baseline 0521e40e): baseline (fix reverted) aborts RC=134 on the 0993-27f0 query; with the fix RC=0. Covers Array/Map/3-branch/Nullable nesting and preserves plain-identity and scalar CAST. Regression 04545 extended with the nested Tuple(agg) opt-off variant; reference regenerated.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT count() IGNORE NULLS FROM (SELECT tuple(s) AS ts FROM (SELECT quantileExactTupleStateTuple(tuple((toUInt32(number),toFloat64(number)))) AS s FROM numbers(100,1) UNION ALL SELECT quantilesExactTupleStateTuple(0.9)(tuple((toUInt32(number),toFloat64(number)))) AS s FROM numbers(101,2147483647)) LIMIT -258) LIMIT 796 SETTINGS query_plan_enable_optimizations = 0 aborts every time on the pre-fix binary.
b Root cause explained? Yes. buildCommonHeaderForUnion picks one branch's Tuple(AggregateFunction(...)) as the common type; the branch-conversion CAST to it takes an identity wrapper in FunctionCast::prepareImpl because the two Tuple(agg) types equals() (tolerant of aggregate-state func-name differences) and the top-level type is DataTypeTuple, so the bare-agg strictEquals guard is bypassed. The identity wrapper passes the source column through with its original aggregate function; ColumnTuple::getName embeds the nested func name, so the strict per-stream block-structure check aborts at plan build (UnionStep::updateOutputHeader -> checkHeaders).
c Fix matches root cause? Yes. Skip the identity wrapper when two equals()-equal types contain a nested aggregate-function subtype that is not strictEquals, so the real recursive Tuple/Array/Map CAST wrapper rebuilds each aggregate column with the target function.
d Test intent preserved / new tests added? Yes. 04545 extended with the nested Tuple(agg) opt-off variant (0993-27f0) alongside the existing liftUpUnion/tryPushDownFilter/base-planner variants; reference regenerated. No existing assertion weakened.
e Both directions demonstrated? Yes. Baseline (fix reverted, Build ID 0521e40e) aborts RC=134; with fix (Build ID 0642bf25) RC=0.
f Fix is general across code paths? Yes. The fix is at the single identity-wrapper gate in prepareImpl, which governs every CAST; it is not a per-call-site patch. It addresses the source (identity wrapper wrongly reused for tolerant-but-not-strict nested aggregate states), not the abort symptom.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Verified for Tuple(agg), Array(agg), Map(String, agg), 3-branch unions, and -StateOrNull variants; plain-identity CAST (same func) stays a no-op and scalar CASTs (String/UInt64/Array/Tuple) are unaffected. forEachChild recurses through all composite wrappers.
h Backward compatible? Yes. No setting/format/on-disk change; only makes a previously-aborting query succeed with correct results. No SettingsChangesHistory change needed.
i Invariants and contracts preserved? Yes. The block-structure invariant (union branch headers strictly equal) is now upheld by physically homogenizing the nested aggregate column, instead of relying on a tolerant type relabel. The identity wrapper is still used for genuinely strict-equal types, preserving its optimization for the common case.

Session id: cron:clickhouse-worker-slot-2:20260717-083700

groeneai and others added 2 commits July 17, 2026 09:40
Style check requires -WithMemoryTracking containers in src/Functions;
replace std::vector<DataTypePtr> with the DataTypes typedef
(VectorWithMemoryTracking<DataTypePtr>).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ERSECT/EXCEPT builders

The query-tree planner (Planner::buildQueryPlanForUnionNode) already forces a
CAST for any UNION branch whose column type name diverges from the common header
even when blocksHaveEqualStructure is tolerant (aggregate-state columns that
share the same state representation but differ by type name, e.g.
quantileExactTuple vs quantilesExactTuple). The legacy enable_analyzer = 0
builders InterpreterSelectWithUnionQuery::buildQueryPlan and
InterpreterSelectIntersectExceptQuery::buildQueryPlan still gated the branch
conversion on !blocksHaveEqualStructure + plain makeConvertingActions, so a
branch kept emitting its own aggregate-state type while the union advertised the
common one. A step above the union that wraps the column (tuple(s)) then built a
column whose name embeds the branch aggregate function name, and the strict
per-stream Block structure mismatch check aborted at pipeline build.

Route both legacy builders through the shared
addConvertingToCommonHeaderActionsIfNeeded helper so the analyzer and legacy
paths cannot drift.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Addressed in b21f021.

The forced-cast homogenization now covers the legacy enable_analyzer = 0 builders. Both InterpreterSelectWithUnionQuery::buildQueryPlan and InterpreterSelectIntersectExceptQuery::buildQueryPlan are routed through the shared addConvertingToCommonHeaderActionsIfNeeded helper (the same one the query-tree planner uses), instead of the old !blocksHaveEqualStructure + plain makeConvertingActions gate. That gate skipped conversion for branches whose aggregate-state type name diverged from the common header (same state representation, different function name, e.g. quantileExactTuple vs quantilesExactTuple), so the mismatch stayed reachable with the old analyzer. Analyzer and legacy paths now share one code path and cannot drift.

Confirmed the legacy path aborted before the fix: with enable_analyzer = 0 the divergent-aggregate-state UNION ALL wrapped in tuple() hit Logical error: 'Block structure mismatch in QueryPipeline stream: different columns'; it passes after the fix. Regression 04545_lift_up_union_agg_state_type_mismatch extended with an enable_analyzer = 0 section (UNION ALL + INTERSECT + same-type sanity).

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse local --enable_analyzer=0 --query "SELECT tuple(s) FROM (SELECT quantileExactTupleState((toUInt32(number),toFloat64(number))) AS s FROM numbers(100,5) GROUP BY number%2 UNION ALL SELECT quantilesExactTupleStateOrNull(toDecimal64(0.9,12))((toUInt32(number),toFloat64(number))) AS s FROM numbers(7) GROUP BY ALL) FORMAT Null" aborts every time on baseline.
b Root cause explained? The legacy builders gated branch conversion on !blocksHaveEqualStructure and used plain makeConvertingActions. blocksHaveEqualStructure and IDataType::equals are both tolerant of aggregate-state columns with the same representation but different function name, so a divergent branch was neither flagged nor cast. It kept physically emitting its own type while the union header advertised the common one; a step above the union wrapping the column (tuple(s)) built a column whose name embeds the branch function name, so the strict per-stream block-structure check aborted at pipeline build.
c Fix matches root cause? Yes. Both legacy builders now call addConvertingToCommonHeaderActionsIfNeeded, which forces an explicit CAST whenever a branch column type name diverges from the common header, so the branch physically emits the common type.
d Test intent preserved / new tests? Yes. 04545 extended with an enable_analyzer = 0 section (UNION ALL, INTERSECT, and a genuine same-type union to prove the conversion is still skipped when unneeded). Existing assertions unchanged.
e Demonstrated both directions? Yes. Baseline (Build ID a129857e): the legacy UNION ALL query aborts RC=134 Block structure mismatch in QueryPipeline stream. Fixed (Build ID 5244141b): RC=0, and quantileExactTupleStateMerge over the divergent branches returns a correct value.
f Fix general, not a narrow patch? Yes. Rather than patch one builder, both legacy builders share the same helper as the analyzer path, so all three paths (planner, legacy SELECT-UNION, legacy INTERSECT/EXCEPT) are covered by one implementation and cannot drift.
g Generalizes across inputs? Verified: UNION ALL, INTERSECT, EXCEPT; -StateOrNull; nested tuple() wrapping; both analyzers. Plain scalar type coercion (UInt8 vs Int64) still works and same-type unions still skip conversion.
h Backward compatible? Yes. No setting, format, or default change. Only broadens when a branch is physically cast to the already-computed common union type.
i Invariants preserved? Yes. The common union header is unchanged (buildCommonHeaderForUnion / getCommonHeader); the fix only ensures each branch's emitted block matches that header, which is exactly the per-stream block-structure invariant the pipeline builder asserts.

Session id: cron:clickhouse-worker-slot-3:20260717-141300

Comment thread src/Functions/FunctionsConversion.cpp Resolved
…NION common type

createVariantToVariantWrapper matched variant members by getName() only, so a
UNION/set-op branch whose Variant nests an aggregate-state type differing from
the common header only by function name (same state representation, e.g.
quantileExactTuple vs quantilesExactTuple(0.9)) was rejected with
CANNOT_CONVERT_TYPE even though the two Variant types are equals()-equal.
buildCommonHeaderForUnion picks one branch's Variant as the common header and
addConvertingToCommonHeaderActionsIfNeeded forces a CAST, but the variant
wrapper could not rewrite it, so the branch kept emitting its own variant type
and the strict per-stream block-structure check aborted at pipeline build.

Match an unmatched-by-name old variant member to an equals()-equal new member
and force a real converting wrapper so the subcolumn is physically rebuilt with
the target function. Genuine Variant extensions still cast for free.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
std::optional<ColumnVariant::Discriminator> matched;
for (size_t j = 0; j != new_variants.size(); ++j)
{
if (!new_discriminator_mapped[j] && old_type->equals(*new_variants[j]))

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.

This fallback is broader than the union-common-header case it is trying to fix. old_type->equals(*new_variants[j]) can succeed for more than one unmapped target member when allow_suspicious_variant_types = 1, for example Variant(AggregateFunction(quantilesExactTuple(0.5), ...), AggregateFunction(quantilesExactTuple(0.9), ...), UInt8). A source member like AggregateFunction(quantileExactTuple, ...) or AggregateFunction(quantilesExactTuple(0.7), ...) will then be rewritten to whichever candidate sorts first, which changes the later merge/finalize semantics arbitrarily instead of preserving the documented "extension only" contract.

Please make this accept only a unique equals()-equal fallback match: if there are zero matches, keep throwing CANNOT_CONVERT_TYPE as before; if there is exactly one, use it for the union/common-header fix; if there are two or more, throw as ambiguous instead of picking the first one.

cppcoreguidelines-init-variables (-warnings-as-errors) does not do
branch-assignment analysis and flagged the unconditionally-assigned
new_discriminator in createVariantToVariantWrapper. Initialize at
declaration; no behavior change.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 3c5a8b1

Every failure below has an owner. CI fully finished on this head (Finish Workflow SUCCESS).

Check / test Reason Owner / fixing PR
Stress test (amd_asan_ubsan) / UndefinedBehaviorSanitizer division by zero (STID 4141-5b13) flaky (chrono duration.h:460, CREATE QUOTA FOR INTERVAL 0 SECOND; 20+ unrelated PRs + master, 30d) #110346 (ours, open)
Stateless (amd_llvm_coverage, old analyzer, s3, DBReplicated, WasmEdge, parallel, 2/3) / "Server died" + "Unknown error" (lost connection) crash (Int256*Float64 SIGABRT on type mismatch in the heavy WasmEdge coverage job; 56 master + many PR hits, 14d) #109747 + #110048 (external, open)

Neither failure is PR-caused (both unrelated to the liftUpUnion / set-op divergent-aggregate-state fix this PR makes; both are pre-existing trunk/flaky signatures with open fixing PRs).

Session id: cron:our-pr-ci-monitor:20260718-033000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 3c5a8b1

Every failure below has an owner: a fixing PR (ours or external). No failure is caused by this PR's diff (which only changes the union converting-actions path in liftUpUnion/pushDownFilter/InterpreterSelectWithUnionQuery).

Check / test Reason Owner / fixing PR
Stateless (amd_llvm_coverage, old analyzer, s3, DBReplicated, WasmEdge, parallel, 2/3) — "Server died" / "Unknown error" crash (MultiplyImpl aggregate-multiply abort in ActionsDAG::updateHeader -> evaluatePartialResult -> executeImplDryRun; unrelated to this PR) #109747 (ours, open)
Stress test (amd_asan_ubsan) — UBSan __chrono/duration.h:460:29 division by zero (STID 4141-5b13) crash (zero-length-interval quota chrono division; trunk-wide, on master + many unrelated PRs) #110846 (external, open)

Config Workflow / Finish Workflow / Mergeable Check / PR aggregators are red only because they roll up the two lines above; both are owned. No PR-caused failure.

groeneai added 2 commits July 21, 2026 11:39
Resolves conflicts in liftUpUnion.cpp and filterPushDown.cpp with master's
ClickHouse#106956 const-fold guard. Both guards protect the same push-through-union
rewrites but catch different divergence: master's blocksHaveEqualStructure
check rejects physical divergence (a branch that constant-folds a column to
Const) while remaining tolerant of aggregate-state type-name differences via
IDataType::equals; this PR's check rejects the aggregate-state type-name
divergence (quantileExactTuple vs quantilesExactTuple) that equals() misses.
Folded both into the shared canPushStepThroughUnion helper so tryLiftUpUnion
and filterPushDown's Filter->Union rewrite carry both protections.
@clickhouse-gh

clickhouse-gh Bot commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.10% -0.10%
Functions 92.10% 92.00% -0.10%
Branches 78.30% 78.20% -0.10%

Changed lines: Changed C/C++ lines covered: 113/116 (97.41%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - bb35bed...

CI fully finished (Finish Workflow pass; 0 checks queued/in-progress; CH Inc sync pass). New head (pushed today) since the 2026-07-18 ledger. Failures below have owners; none is caused by this PR's diff (share identical-header precondition with the Filter->Union rewrite).

Check / test Reason Owner / fixing PR
Stateless (amd_llvm_coverage, old analyzer, s3, DBReplicated, WasmEdge, 2/3) / Server died + Logical error multiply Int256*Float64 (STID 2735-47bf) crash (SIGABRT LOGICAL_ERROR: concurrent EXCHANGE TABLES swaps table out from under a resolved multiply; chronic coverage-WasmEdge family, 0 master) fixing PR #109747 (ours, open) + #110048 (alexey-milovidov, open)
Integration tests (amd_tsan, 3/6) / test_replicated_database::test_replicated_table_structure_alter flaky (replicated-DDL structure-alter race) fixing PR #109245 (ours, open; #110036)
Mergeable Check / PR rollup of the above owned via the rows above

Session id: cron:our-pr-ci-monitor:20260721-190000

@groeneai groeneai added the groeneai-origin-unknown PR origin: unclassified (legacy task) label Aug 19, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 4, 2026
@groeneai

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author

This PR is superseded by #111191 (merged 2026-07-30, backported to 26.5, 26.6 and 26.7). It fixed the same Block structure mismatch family by applying the aggregate-state relaxation of checkColumnStructure inside Tuple/Array/Map/Variant columns, and it closed #111185, the same liftUpUnion error this PR targets.

On a current master debug build (44b568f4e45), this PR's own test 04545_lift_up_union_agg_state_type_mismatch produces output identical to its .reference with none of this PR's code, and CIDB has no AST fuzzer report of this shape since August. So I am not resolving the merge conflict. Can this PR be closed?

This branch has not been deployed

No deployments
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-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... groeneai-origin-unknown PR origin: unclassified (legacy task) pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants