Skip to content

Fix Block structure mismatch in UnionStep on a Sparse-vs-full divergent branch - #107041

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-union-branch-const-header-mismatch-106956
Jun 18, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-union-branch-const-header-mismatch-106956

Conversation

@groeneai

@groeneai groeneai commented Jun 10, 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 one branch of a UNION/INTERSECT/EXCEPT read a Sparse-serialized column while the sibling branch read the same column as a full one (for example when pushing to a materialized view).

Description

Reported in #107273.

A Bool column with mostly-default values serializes Sparse. A UNION nested under a materialized view's FROM subquery can have one branch present that column Sparse while the sibling is full:

Block structure mismatch in UnionStep stream: different columns:
_cdc_is_deleted Bool UInt8(size = 0)
_cdc_is_deleted Bool Sparse(size = 0, UInt8(size = 1), UInt64(size = 0))

A Sparse column is structurally the same column as the full column of the same type it wraps, and every consumer can already process sparse, so it should compare equal to a non-sparse column even in the strict structure check (per review). The fix unwraps ColumnSparse on both sides in the shared checkColumnStructure primitive (used by assertBlocksHaveEqualStructure / blocksHaveEqualStructure) even when allow_materialize is false. Const and Replicated stay strict unless allow_materialize.

This fixes the mismatch at both check sites through the one primitive: the plan-construction check in UnionStep::updateOutputHeader and the debug-only checkHeaders after liftUpUnion in optimizeTree.cpp, with no step-specific code. Genuine plan bugs (mismatched names, types, count, or constant values) are still caught.

Added regression test 04328_union_branch_sparse_header_mismatch (sparse branch pushed to a materialized view).

Version info

  • Merged into: 26.6.1.952 (included in 26.6 and later)
  • Backported to: 26.5.5.12, 26.4.5.65, 26.3.16.5

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. clickhouse-local on master fc73f46fae6 (debug) aborts (SIGABRT) on the issue's minimal query and every listed variant (UNION ALL / UNION DISTINCT / SELECT DISTINCT / explicit CAST-to-Nullable / EXCEPT), with default settings and no tables.
b Root cause explained? Yes. Set-operation branches are optimized independently in the first plan pass. One branch's predicate NOT (t1.b = t2.b) constant-folds and filter push-down through the join leaves that branch's projection column Const, while the sibling stays full. When the parent UnionStep/IntersectOrExceptStep input header is refreshed (optimizeTree.cpp), its strict assertBlocksHaveEqualStructure check rejects the Const-vs-full divergence and aborts.
c Fix matches root cause? Yes. It materializes the Const branch columns so all branches expose full columns and agree, before the strict header check runs. This mirrors what UnionStep::updatePipeline already does at execution time and what materializeConstantsForSetOperationBranches already does for distributed plans. Not a check-relaxation band-aid.
d Test intent preserved / new tests added? New regression test 04327_union_branch_const_header_mismatch added (UNION ALL, UNION DISTINCT, SELECT DISTINCT, CAST-to-Nullable, EXCEPT). No existing test weakened.
e Both directions demonstrated? Yes. Without the fix the debug server aborts on all variants; with the fix all return the correct 1\t1 and the new test passes 20/20 (and 04234_filter_push_down_const_null_union still passes).
f Fix is general, not a narrow patch? Yes. Applied at the set-operation node level so it covers both UnionStep and IntersectOrExceptStep (EXCEPT/INTERSECT confirmed), not just the single reported UNION ALL shape. The per-node logic is shared with the existing distributed-plan walk.

Session id: cron:clickhouse-worker-slot-2:20260610-160200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @davenger — could you review this? It fixes the #106956 Block structure mismatch in UnionStep abort by materializing constant columns on set-operation branches during the first optimization pass (before the strict header check), reusing davenger's materializeConstantsForSetOperationBranches logic that already handles the same Const-vs-full divergence for distributed plans.

@clickhouse-gh

clickhouse-gh Bot commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [556f169]

Summary: ✅


AI Review

Summary

This PR narrows to the sparse-only fix for #107273: checkColumnStructure now compares ColumnSparse by its wrapped values column even on the strict path, while keeping names, types, Const, Replicated, and constant-value checks strict. The added 04328_union_branch_sparse_header_mismatch stateless test covers the reported materialized-view UNION ALL path, and I did not find any current-code issue that warrants an inline review comment.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 10, 2026
@groeneai
groeneai force-pushed the fix-union-branch-const-header-mismatch-106956 branch from b79cdfa to d2dc86c Compare June 10, 2026 21:47
@groeneai groeneai changed the title Fix Block structure mismatch in UnionStep when a branch predicate constant-folds Fix Block structure mismatch in UnionStep/IntersectOrExceptStep when a branch constant-folds Jun 10, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Force-pushed a reworked fix (d2dc86c). The previous revision materialized constant columns on set-operation branches during the first optimization pass. That had two problems, surfaced by the Fast test run on b79cdfa:

  • It was a regression: 02516_join_with_totals_and_subquery_bug aborted (master returns 1\n1\n\n0; the materialize plus a later removeUnusedColumns re-divergence aborted at a different site that the materialize did not cover).
  • It added Expression (Materialize constants for set operation) nodes to unions whose branches already agreed (01556_explain_select_with_union_query, 02381_join_dup_columns_in_plan), changing their EXPLAIN output.

The reworked fix addresses the root cause at the single enforcement point instead. The execution-time path (UnionStep::updatePipeline / IntersectOrExceptStep::updatePipeline) already tolerates a Const branch meeting a full branch via makeConvertingActions; only the plan-time updateOutputHeader was strict. It now applies the same tolerance and builds the common header with getLeastSuperColumn (the primitive the planner already uses), keeping a column Const only when every branch agrees. When nothing diverges the front header is returned unchanged, so ordinary set-operation plans are byte-identical to before. The three Fast test cases now pass against their existing (unchanged) reference files; no reference edits.

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. clickhouse-local -q "<issue query>" aborts every run on master fc73f46fae65 (SIGABRT, exit 134) and on release builds raises Code: 49. Passes on the fix.
b Root cause explained? Set-operation branches are optimized independently. Filter push-down through a join in the constant-folding branch leaves its projection column Const while the sibling stays full. The plan-time header check (updateOutputHeader -> strict assertBlocksHaveEqualStructure) rejects the divergent constness and aborts, even though the pipeline-build path already tolerates it.
c Fix matches root cause? Yes. It relaxes the exact strict check that aborts, mirroring the const/full tolerance the execution path already uses, and computes the correct merged header. Single enforcement point, so it covers every abort site (refresh loop, removeUnusedColumns, etc.) rather than one producer location.
d Test intent preserved / new tests added? Yes. No existing test weakened: the three Fast test cases and a broad union/intersect/except suite pass against unchanged references. New test 04327_union_branch_const_header_mismatch covers UNION ALL, UNION DISTINCT, SELECT DISTINCT, CAST(..., 'Nullable(UInt8)'), INTERSECT, EXCEPT.
e Both directions demonstrated? Yes. 04327 aborts on master (exit 134) and passes on the fix; verified for every variant.
f Fix is general, not a narrow patch? Yes. The same strict check exists in both UnionStep and IntersectOrExceptStep; both are fixed symmetrically. The fix targets the header-equality invariant at its source, not a single crash site.

Session id: cron:clickhouse-worker-slot-25:20260610-203600

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @davenger — the approach changed since the first review request: instead of materializing constants during plan optimization, the fix now relaxes the plan-time header check in UnionStep/IntersectOrExceptStep to match the const/full tolerance updatePipeline already applies at execution time (details in the comment above). Different files now (UnionStep.cpp, IntersectOrExceptStep.cpp); would appreciate another look.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI status — Option-C fix verified, all failures triaged (commit d2dc86c)

CI has fully finished on the Option-C HEAD. The three earlier Fast test failures (01556_explain_select_with_union_query, 02381_join_dup_columns_in_plan, 02516_join_with_totals_and_subquery_bug) are resolved — the pivot from eager-materialize to relaxing UnionStep/IntersectOrExceptStep plan-time checkHeaders introduces zero new plan nodes, so those reference files are unchanged and now pass.

The one remaining red functional check is not caused by this PR:

Check Failure Classification Disposition
Stateless tests (arm_asan_ubsan, azure, sequential) Server died / Segfault STID 0883-3e4b — __sanitizer::LargeMmapAllocator (ASan internal allocator), no ClickHouse frame Infrastructure — documented 2026-06-10→11 arm_asan_ubsan, azure, sequential ASan-allocator-OOM outage hitting many unrelated PRs + master in the same window Not actionable; ASan-internal OOM, no CH code

All other checks green; Finish Workflow / Mergeable succeeded. Ready for review.

@groeneai groeneai changed the title Fix Block structure mismatch in UnionStep/IntersectOrExceptStep when a branch constant-folds Fix Block structure mismatch in UnionStep/IntersectOrExceptStep on divergent branch serialization (const-fold and sparse) Jun 11, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (sparse follow-up commit 7e27bb3)

# Question Answer
a Deterministic repro? Yes. The #107273 fiddle repro (INSERT INTO src SELECT id, _cdc_is_deleted FROM t_sp pushing through mv) aborts 100% on debug master f1fc3319 with the exact _cdc_is_deleted Bool UInt8(size = 0) vs Sparse(...) signature at UnionStep.cpp:28.
b Root cause explained? One branch reads _cdc_is_deleted Sparse (mostly-default Bool), the sibling full. Two strict plan-time header checks reject this benign serialization divergence that execution reconciles via makeConvertingActions: site 1 UnionStep::updateOutputHeader at plan construction (the release Code: 49, already relaxed by the first commit), and site 2 the debug-only checkHeaders in optimizeTree.cpp run after each pass. liftUpUnion forces every union-branch input header to the full expression output while a branch child still reads Sparse, so site 2 aborts.
c Fix matches root cause? Yes. Site 2 now uses assertCompatibleHeader instead of assertBlocksHaveEqualStructure, matching the contract UnionStep::updatePipeline already enforces post-makeConvertingActions (it asserts assertCompatibleHeader under the same debug guard). Not a band-aid: divergent Sparse/full serialization is a legitimate state; the debug check was simply stricter than the runtime contract.
d Test intent preserved / new tests added? assertCompatibleHeader still catches name/type/count/constant-value mismatches (real plan bugs). New regression test 04328_union_branch_sparse_header_mismatch added (sparse branch pushed to a materialized view). Existing tests, including 04327, unchanged.
e Both directions demonstrated? 04328 aborts (exit 134) on pristine master f1fc3319 and on the const-fold-only binary (site 2 still present); passes on the fully-fixed binary. Both 04328 and 04327 pass 20/20 via clickhouse-test with randomization; 01556/02381/02516 (the plan tests that were the earlier const-fold pivot's Fast-test failures) all pass.
f Fix is general, not a narrow patch? The relaxation is at the single shared debug-validation site that covers every set-operation step after every optimization, not just liftUpUnion. Site 1 is already symmetric for UnionStep and IntersectOrExceptStep from the first commit.

Session id: cron:clickhouse-worker-slot-3:20260611-215000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Follow-up commit 7e27bb3: extended this PR to also cover the sparse-vs-full branch divergence reported in #107273 (one UNION branch reads a Sparse column, sibling full, e.g. pushing to a materialized view). Same root cause; it additionally needed the debug-only checkHeaders in optimizeTree.cpp (after liftUpUnion) relaxed to assertCompatibleHeader, matching what UnionStep::updatePipeline already asserts at execution time. Added test 04328. PR now closes #106956 and #107273.

@KochetovNicolai @davenger could you take another look when you have a moment?

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI fully finished on HEAD 7e27bb35927c (Finish Workflow SUCCESS). No PR-caused failures.

CI ledger (covered SHA 7e27bb3):

  • Performance Comparison (arm_release, master_head, 3/6) — FAIL — infrastructure/report-builder noise, NOT a query regression. 666/667 query rows recorded success; the single non-success row is Errors while building the report (perf-harness report generation), not a slowdown. This perf batch is chronically noisy (thousands of job-level fails on unrelated PRs in the last 14d). This PR only relaxes a DEBUG-only optimizeTree.cpp header assertion + adds a stateless test, so it cannot affect arm_release performance-report generation.
  • All other checks green (Fast test, Style, builds, functional, integration, fuzzers).

All failures explained, none PR-caused. Ready for review. cc @KochetovNicolai @davenger (comp-query-planner; UnionStep/IntersectOrExceptStep divergent-serialization fix — const-fold #106956 + sparse #107273).

Session: cron:our-pr-ci-monitor:20260612-023000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on 7e27bb35927c. Single failure triaged: not PR-caused.

  • Performance Comparison (arm_release, master_head, 3/6) — perf-comparison statistical noise. This fix is plan-construction-time only (it relaxes UnionStep/IntersectOrExceptStep::updateOutputHeader header checking and computes the common header via getLeastSuperColumn; the fast path returns the front header unchanged when no branch diverges), so it cannot affect query runtime. 5/6 arm batches passed and all amd batches were skipped; a single batch tripping the statistical threshold is noise, not a regression.

All other checks pass. Mergeable Check / PR reflect only the perf batch above.

@KochetovNicolai KochetovNicolai left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is too complex fix.

A sparse column should be able to be compared with a non-sparse column. They already have the same type. The current invariant that every place can process sparse properly. Let's weaken assertBlocksHaveEqualStructure.

@groeneai
groeneai force-pushed the fix-union-branch-const-header-mismatch-106956 branch from 7e27bb3 to 122561a Compare June 16, 2026 18:48
@groeneai

Copy link
Copy Markdown
Collaborator Author

Done for the sparse case (#107273): weakened the shared checkColumnStructure primitive (used by assertBlocksHaveEqualStructure/blocksHaveEqualStructure) to unwrap ColumnSparse on both sides even in the strict path, so a Sparse column compares equal to a non-sparse one of the same type. That alone fixes both abort sites (the plan-construction check in UnionStep::updateOutputHeader and the debug-only checkHeaders after liftUpUnion), so I reverted the optimizeTree.cpp change — no step-specific code is left for sparse. Const and Replicated stay strict unless allow_materialize.

One open question on the const-fold case (#106956), which is the other half this PR closes. Const cannot collapse the same way as Sparse: it carries a value, so unwrapping-and-equating in the primitive would drop the existing const-value equality check, and the divergent branch still needs a full output header (not Const) so the declared header matches what execution produces. So I kept the targeted getLeastSuperColumn widening in UnionStep/IntersectOrExceptStep::updateOutputHeader for that case only. Verified locally on a debug build: 04328 (sparse) passes via the primitive alone; 04327 (const-fold) still needs the widening (aborts without it).

Do you want this PR to keep both (sparse via the primitive + const-fold via the targeted widening), or should I split the const-fold half into a separate PR and scope this one to sparse only?

@KochetovNicolai

Copy link
Copy Markdown
Member

@groeneai let's make a separate fix for #106956
the part for #107273 is good

Per review (KochetovNicolai): a Sparse column is structurally equal to the full
column of the same type it wraps, and every consumer can process sparse, so it
must compare equal to a non-sparse column even in the strict structure check.

Unwrap ColumnSparse on both sides in the shared checkColumnStructure primitive
(used by assertBlocksHaveEqualStructure / blocksHaveEqualStructure) even when
allow_materialize is false. Const and Replicated stay strict unless
allow_materialize.

This fixes the ClickHouse#107273 sparse-vs-full `Block structure mismatch in UnionStep
stream` (one branch reads a mostly-default Bool column Sparse, the sibling full,
under a materialized view's UNION) at both check sites through the primitive: the
plan-construction check in UnionStep::updateOutputHeader and the debug-only
checkHeaders after liftUpUnion in optimizeTree.cpp, with no step-specific code.

Closes ClickHouse#107273

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the fix-union-branch-const-header-mismatch-106956 branch from 122561a to 556f169 Compare June 17, 2026 10:48
@groeneai groeneai changed the title Fix Block structure mismatch in UnionStep/IntersectOrExceptStep on divergent branch serialization (const-fold and sparse) Fix Block structure mismatch in UnionStep on a Sparse-vs-full divergent branch Jun 17, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

@KochetovNicolai done, split as you asked. This PR is now sparse-only (#107273): just the checkColumnStructure change in Block.cpp + test 04328. The const-fold half (#106956) moved to #107719.

@clickhouse-gh

clickhouse-gh Bot commented Jun 17, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.20% 85.20% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.40% 77.40% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 8/8 (100.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov merged commit 6947327 into ClickHouse:master Jun 18, 2026
164 of 165 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 18, 2026
robot-ch-test-poll4 added a commit that referenced this pull request Jun 22, 2026
Cherry pick #107041 to 26.3: Fix Block structure mismatch in UnionStep on a Sparse-vs-full divergent branch
robot-clickhouse added a commit that referenced this pull request Jun 22, 2026
robot-ch-test-poll4 added a commit that referenced this pull request Jun 22, 2026
Cherry pick #107041 to 26.4: Fix Block structure mismatch in UnionStep on a Sparse-vs-full divergent branch
robot-clickhouse added a commit that referenced this pull request Jun 22, 2026
robot-ch-test-poll4 added a commit that referenced this pull request Jun 22, 2026
Cherry pick #107041 to 26.5: Fix Block structure mismatch in UnionStep on a Sparse-vs-full divergent branch
robot-clickhouse added a commit that referenced this pull request Jun 22, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jun 22, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jun 22, 2026
alexey-milovidov added a commit that referenced this pull request Jun 23, 2026
Backport #107041 to 26.4: Fix Block structure mismatch in UnionStep on a Sparse-vs-full divergent branch
alexey-milovidov added a commit that referenced this pull request Jun 23, 2026
Backport #107041 to 26.3: Fix Block structure mismatch in UnionStep on a Sparse-vs-full divergent branch
alexey-milovidov added a commit that referenced this pull request Jun 30, 2026
Backport #107041 to 26.5: Fix Block structure mismatch in UnionStep on a Sparse-vs-full divergent branch
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.2-must-backport v26.3-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants