Skip to content

Fix crash when Merge table wraps Distributed with distributed_group_by_no_merge=1 - #100859

Merged
alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:fix/merge-distributed-dgbnm-crash
Apr 8, 2026
Merged

alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:fix/merge-distributed-dgbnm-crash

Conversation

@groeneai

@groeneai groeneai commented Mar 26, 2026 •

Copy link
Copy Markdown
Collaborator

When a Merge table (or the merge() table function) references multiple underlying tables, and one of them is a Distributed table, queries crash with a LOGICAL_ERROR if distributed_group_by_no_merge=1 is set:

Logical error: 'Queries with distributed_group_by_no_merge=1 should be processed to Complete stage'

Root cause: StorageMerge::getQueryProcessingStage() caps the processing stage to WithMergeableState when there are multiple underlying tables (line 415). When createPlanForTable() then calls StorageDistributed::getQueryProcessingStage() with this capped to_stage=WithMergeableState, the assertion at line 516 fires because it requires to_stage == Complete.

Fix: The assertion was too strict. With distributed_group_by_no_merge=1, each shard processes the full query independently and the initiator concatenates results. StorageDistributed can always return Complete regardless of the requested to_stage — the caller (StorageMerge) correctly handles storage_stage > processed_stage via the condition at line 1273.

Reproducer (from issue):

CREATE TABLE t30 (c0 Int) ENGINE = MergeTree() ORDER BY c0;
CREATE TABLE t31 (c0 Int) ENGINE = Distributed('test_shard_localhost', currentDatabase(), 't30');
CREATE TABLE t32 (c0 Int) ENGINE = Memory;
SELECT 1 FROM merge(currentDatabase(), '^t3[12]$') SETTINGS distributed_group_by_no_merge = 1;
-- Crashes with LOGICAL_ERROR

Closes #75604

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 crash (LOGICAL_ERROR) when querying a Merge table (or merge() table function) that wraps multiple tables including a Distributed table, with distributed_group_by_no_merge=1 enabled.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.4.1.671

…y_no_merge=1

When a Merge table contains multiple underlying tables and one is a
Distributed table, StorageMerge::getQueryProcessingStage() caps the
processing stage to WithMergeableState. It then passes this capped
stage to StorageDistributed::getQueryProcessingStage() which had an
assertion requiring to_stage == Complete when
distributed_group_by_no_merge=1.

The assertion was too strict. With distributed_group_by_no_merge=1,
each shard processes the full query independently and the initiator
concatenates results, so StorageDistributed can always return Complete
regardless of the requested to_stage. The caller (StorageMerge)
correctly handles storage_stage > processed_stage.

Closes ClickHouse#75604

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR Validation Gate (Session a42ef9e6)

a) Deterministic repro? ✅ Yes — SELECT count() FROM merge(currentDatabase(), '^(dist_table|memory_table)$') SETTINGS distributed_group_by_no_merge = 1 crashes 100% on unfixed binary when the Merge wraps 2+ tables including a Distributed table.

b) Root cause explained? ✅ StorageMerge::getQueryProcessingStage() caps stage to WithMergeableState for multi-table scenarios (line 415: std::min(stage_in_source_tables, WithMergeableState)). Then createPlanForTable() calls StorageDistributed::getQueryProcessingStage() with to_stage=WithMergeableState. StorageDistributed asserts to_stage == Complete when distributed_group_by_no_merge=1 → LOGICAL_ERROR.

c) Fix matches root cause? ✅ Removes the overly-strict assertion. StorageDistributed now unconditionally returns Complete when distributed_group_by_no_merge=1, which is semantically correct — each shard processes independently. The caller handles storage_stage > processed_stage correctly (StorageMerge.cpp line 1273).

d) Test intent preserved? ✅ This is a source code fix. The regression test (04064_merge_distributed_group_by_no_merge) verifies correct results for count/sum/GROUP BY/SELECT with both distributed_group_by_no_merge=1 and =2.

e) Both directions demonstrated? ✅

  • Without fix: Server crashes with Logical error: 'Queries with distributed_group_by_no_merge=1 should be processed to Complete stage'
  • With fix: 50/50 passes under full randomization, correct results verified.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @azat @alexey-milovidov — could you review this? It fixes a crash when a Merge table wraps a Distributed table with distributed_group_by_no_merge=1.

@pufit pufit added the can be tested Allows running workflows for external contributors label Mar 27, 2026
@clickhouse-gh

clickhouse-gh Bot commented Mar 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7839867]

Summary: ✅


AI Review

Summary

This PR fixes an exception in StorageDistributed::getQueryProcessingStage when distributed_group_by_no_merge=1 is used through Merge over multiple underlying tables. The change removes an overly strict stage check and keeps returning Complete, which matches the existing ReadFromMerge::createPlanForTable handling of storage_stage > processed_stage. Regression coverage in 04064_merge_distributed_group_by_no_merge.sql reproduces the failure pattern and validates key query shapes. High-level verdict: change is correct and safe.

Missing context
  • ⚠️ No CI logs/results were provided in this review context.
ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Mar 27, 2026
@azat azat self-assigned this Mar 27, 2026
@azat

azat commented Mar 27, 2026

Copy link
Copy Markdown
Member

@groeneai why have you merged master to this branch? It had one failed test, it is OK to have them, you do not need to restart CI to hide this problems (cc @pufit )

@groeneai

Copy link
Copy Markdown
Collaborator Author

@azat Thanks for the feedback — noted for the future. In this case the merge was to pick up PR #100867 (fix for 02967_parallel_replicas_joins_and_analyzer), which was blocking multiple PRs including this one. But I understand the point — a single pre-existing flaky failure doesn't need to be "fixed" by merging master. Will avoid unnecessary merges going forward.

Could you take a look at the actual fix when you have a chance? The core change is small: removing the overly-strict assertion in StorageDistributed::getQueryProcessingStage() that crashes when StorageMerge calls it with to_stage=WithMergeableState while distributed_group_by_no_merge=1.

@clickhouse-gh

clickhouse-gh Bot commented Apr 7, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.00% 84.00% +0.00%
Functions 90.90% 90.90% +0.00%
Branches 76.60% 76.50% -0.10%

Changed lines: 100.00% (2/2) | lost baseline coverage: 3 line(s) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov merged commit bc855b9 into ClickHouse:master Apr 8, 2026
159 checks passed
@robot-ch-test-poll1 robot-ch-test-poll1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Apr 8, 2026
/// The caller may request a lower stage (e.g. StorageMerge passes
/// WithMergeableState when it wraps multiple tables), but that's fine —
/// the caller handles storage_stage > processed_stage correctly.
return QueryProcessingStage::Complete;

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 not enough, Merge also should be aware - #105330

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.

Agreed, my fix only covered same-type aggregates (count, sum) where the WithMergeableState and Complete column types coincide. Your follow-up correctly handles the remaining nested-Merge case where state-bearing aggregates (uniqExact, avg, groupArray, ...) hit CANNOT_CONVERT_TYPE.

Both halves look right:

  1. StorageMerge single-table branch capping at WithMergeableState mirrors the multi-table cap on the same line.
  2. std::max(to_stage, Complete) in StorageDistributed avoids silently downgrading WithMergeableStateAfterAggregation(/AndLimit) callers, which my original Complete return swallowed.

Test 04256 is a strict superset of 04064. Happy to help review #105330.

FYI: 01227_distributed_merge_global_in_primary_key just failed on your distributed-plan CI jobs. It looks like a pre-existing flake on that build family: 5 hits on #102192, 2 hits on #100226 over 30 days, 0 on master. Probably not yours.

azat added a commit to azat/ClickHouse that referenced this pull request Jun 16, 2026
…stributed_group_by_no_merge=1

ClickHouse#100859 made multi-table `Merge` over `Distributed` with
`distributed_group_by_no_merge=1` work for all aggregates: the
`processed_stage <= storage_stage` rescue in
`ReadFromMerge::createPlanForTable` takes the if-branch and calls
`storage->read` with `processed_stage = WithMergeableState`, so the
shards return states and they line up with the Merge's `common_header`.

But that rescue is bypassed when the Merge child is itself a
`StorageMerge` (the `must_return_interpreter_select_query_plan` flag
forces the else-branch unconditionally). With the shape:

  outer Merge (multi-table - caps its own stage at WithMergeableState)
    -> inner Merge (single Distributed child - no cap on single-table branch)
      -> Distributed with distributed_group_by_no_merge=1
         (now returns Complete instead of throwing)

the inner `Merge` propagated `Complete` upward, the nested interpreter
emitted finalized columns, and `convertAndFilterSourceStream` then
tried to CAST e.g. `UInt64` to `AggregateFunction(uniqExact, Int)`,
which the generic CAST does not support - failing with
`CANNOT_CONVERT_TYPE` for state-bearing aggregates (`uniqExact`, `avg`,
`groupArray`, `quantile`, ...).

Two fixes:

- `StorageMerge::getQueryProcessingStage`: cap the single-table branch
  at `WithMergeableState` when the caller asked for `WithMergeableState`
  or less. Mirrors the multi-table cap already present on the same line.

- `StorageDistributed::getQueryProcessingStage`: return
  `std::max(to_stage, Complete)` instead of plain `Complete`, so a
  caller asking for `WithMergeableStateAfterAggregation(/AndLimit)` is
  not silently downgraded.

Test 04256 covers the nested-Merge case and the state-bearing
aggregates that 04064 missed.
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-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Logical error: 'Queries with distributed_group_by_no_merge=1 should be processed to Complete stage'.

5 participants