Skip to content

Fix server abort on GROUPING SETS in a set operation with parallel replicas - #109003

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-grouping-sets-merging-aggregated-grouping-set
Jul 1, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-grouping-sets-merging-aggregated-grouping-set

Conversation

@groeneai

@groeneai groeneai commented Jun 30, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #107826

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 ("Cannot find __grouping_set column in header of MergingAggregatedTransform with grouping sets", or "Chunk info was not set for chunk in MergingAggregatedTransform") that could occur, without the analyzer, for a UNION ALL/INTERSECT/EXCEPT where one branch uses GROUP BY GROUPING SETS with parallel replicas and another branch uses FINAL.

Description

Found by the AST fuzzer on #107826 (AST fuzzer (amd_tsan), report, STID 5710-675a). The fuzzed query is a server-side GROUPING SETS planning bug unrelated to that PR's Web-UI/docs change.

Reproducer

CREATE TABLE t (key Int32, sign Int8) ENGINE = CollapsingMergeTree(sign) ORDER BY key;
INSERT INTO t SELECT number, if(number % 2, 1, -1) FROM numbers(20);

SET enable_analyzer = 0, parallel_replicas_only_with_analyzer = 0,
    enable_parallel_replicas = 1, max_parallel_replicas = 3,
    parallel_replicas_for_non_replicated_merge_tree = 1,
    cluster_for_parallel_replicas = 'test_cluster_one_shard_three_replicas_localhost';

SELECT NULL FROM t GROUP BY GROUPING SETS ((sign), ('x'))
UNION ALL
SELECT NULL FROM t FINAL GROUP BY sign;
-- Logical error: Cannot find __grouping_set column in header of MergingAggregatedTransform with grouping sets

Root cause

InterpreterSelectWithUnionQuery and InterpreterSelectIntersectExceptQuery build all of their branch interpreters with the same mutable context. Both branch interpreters are constructed first, then planned.

  1. The grouping-sets branch is constructed while parallel replicas are enabled, so getQueryProcessingStage returns WithMergeableState and the branch caches that as its from_stage. Its plan therefore adds a MergingAggregatedStep with grouping sets, whose input is expected to carry the synthetic __grouping_set column produced by the partial-aggregation read on the replicas.
  2. The FINAL branch is constructed next and, because FINAL is not supported with parallel replicas, sets allow_experimental_parallel_reading_from_replicas = 0 on the shared context.
  3. When the grouping-sets branch is finally planned, its cached from_stage still says WithMergeableState, but the read now falls back to a local read (parallel replicas were disabled in the shared context) whose header has only the grouping key, without __grouping_set. The MergingAggregatedStep then sees grouping sets but no __grouping_set and the transform raises a LOGICAL_ERROR (the same divergence also produces "Chunk info was not set ..." when there are no grouping sets).

The analyzer is not affected: it decides parallel replicas and the processing stage per branch at planning time.

Fix

Build each set-operation branch with its own context copy (Context::createCopy), so a branch disabling parallel replicas for itself can no longer retroactively change a sibling branch's already chosen processing stage. This matches how the analyzer keeps the branches independent.

Verified both directions on a debug build (server aborts before the fix, passes after) and added a regression test 04492_grouping_sets_parallel_replicas_set_operation_final.

Version info

  • Merged into: 26.7.1.372 (included in 26.7 and later)

…plicas

A UNION ALL or INTERSECT/EXCEPT where one branch uses GROUP BY GROUPING SETS
over a parallel-replicas read and another branch uses FINAL aborted the server
in the non-analyzer interpreter with a LOGICAL_ERROR "Cannot find __grouping_set
column in header of MergingAggregatedTransform with grouping sets" (or "Chunk
info was not set for chunk in MergingAggregatedTransform").

Set-operation branches were built with a shared mutable context. The FINAL
branch disables parallel replicas for itself (allow_experimental_parallel_reading_from_replicas
= 0), which retroactively changed the grouping-sets branch's already chosen
processing stage: it had picked WithMergeableState and a MergingAggregatedStep
with grouping sets, but its read then fell back to a local read whose header
lacks the synthetic __grouping_set column.

Build each set-operation branch with its own context copy so a branch's settings
changes cannot leak into a sibling branch.

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. With enable_analyzer=0, parallel_replicas_only_with_analyzer=0, enable_parallel_replicas=1, max_parallel_replicas=3, parallel_replicas_for_non_replicated_merge_tree=1, cluster_for_parallel_replicas='test_cluster_one_shard_three_replicas_localhost': SELECT NULL FROM t GROUP BY GROUPING SETS ((sign),('x')) UNION ALL SELECT NULL FROM t FINAL GROUP BY sign aborts the server every run on a debug build (also the exact fuzzer query, and the INTERSECT variant).
b Root cause explained? Set-op branches share one mutable context. The grouping-sets branch is constructed with parallel replicas on, caches from_stage=WithMergeableState and plans a MergingAggregatedStep with grouping sets (expecting __grouping_set from the replica partial-aggregation read). The FINAL branch then sets allow_experimental_parallel_reading_from_replicas=0 on the shared context. When the grouping-sets branch is planned, from_stage is still WithMergeableState but the read falls back to a local read whose header lacks __grouping_set -> the transform throws.
c Fix matches root cause? Yes. Each branch is built with its own Context::createCopy, so a branch's settings change cannot retroactively alter a sibling branch's already chosen processing stage. This is the same independence the analyzer already has.
d Test intent preserved / new tests added? New regression test 04492_grouping_sets_parallel_replicas_set_operation_final covering all three crash forms (GROUPING SETS UNION ALL, GROUPING SETS INTERSECT, and the no-grouping-sets "Chunk info was not set" variant). No existing test weakened.
e Both directions demonstrated? Yes (Build-ID verified). Pre-fix binary: all three queries abort the server. Post-fix binary: all pass, server alive, results match the analyzer; regression test 30/30 OK.
f Fix is general across code paths? Both set-op interpreters fixed: InterpreterSelectWithUnionQuery (UNION ALL/DISTINCT) and InterpreterSelectIntersectExceptQuery (INTERSECT/EXCEPT). The fix is at the source of the divergence (shared mutable context), not a guard at the crash site, so it also covers the sibling "Chunk info was not set" manifestation.
g Fix generalizes across inputs? Verified across branch order (grouping-sets first/second), table engines (plain MergeTree, CollapsingMergeTree, ReplacingMergeTree), LowCardinality(Nullable(Int8)) and plain Int8 keys, with/without DISTINCT, and UNION ALL vs INTERSECT.
h Backward compatible? Yes. No setting default, on-disk/wire format, or validation change. Pure planning-isolation fix; query results are unchanged (verified equal to the analyzer path).
i Invariants and contracts preserved? Yes. Branches already received a context via the same set-op builders; this only ensures each branch's settings scope is independent (the analyzer's existing contract). The parent set-op interpreter does not rely on a child mutating the shared context after construction. Normal UNION ALL/INTERSECT/EXCEPT, nested set-ops, and scalar-subquery sharing verified to produce identical results.

Session id: cron:clickhouse-worker-slot-4:20260630-224900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @nickitat — could you review this? It fixes a non-analyzer server abort where set-operation branches share a mutable context: a FINAL branch disables parallel replicas for itself, retroactively breaking a sibling GROUPING SETS branch that had already chosen WithMergeableState and a MergingAggregatedStep, leaving its input header without __grouping_set. The fix gives each set-op branch its own context copy.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a1aa2ce]

Summary: ✅


AI Review

Summary
  • This PR isolates old-analyzer set-operation branches by copying the Context for both real child interpreter construction and the column-pruned header probe. That matches the stated bug: one branch disabling parallel replicas for itself must not mutate a sibling branch's planning scope after the sibling has chosen WithMergeableState. The previous AI review thread about the pruned-subquery probe is resolved in the current code.
Missing context / blind spots
  • ⚠️ Current CI for commit a1aa2ce69eef992a1e3927c3ccbbd3fc6ef032f0 was still pending when reviewed. The fetched Praktika summary showed no failed checks, but most jobs had not completed yet; the pending Fast test and bugfix validation jobs would close this gap.
Final Verdict
  • ✅ No new inline findings. I did not post a review batch.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 1, 2026
…rations

When a set operation is planned as a column-pruned subquery (non-empty
required_result_column_names), the constructor first probes each child header
via getCurrentChildResultHeader. The probe instantiated the temporary child
interpreters with the union's mutable parent context, so a FINAL child that
disables allow_experimental_parallel_reading_from_replicas leaked that change
into the parent context. The real (copied-context) children built afterwards
then inherited parallel replicas already disabled, so a sibling grouping-sets
branch silently lost parallel replicas.

Give the probe the same per-child Context::createCopy as the real construction
path so column-pruned subqueries keep the same branch-local settings scope as
top-level set operations. Extend the regression test with a pruned-subquery
case asserting the grouping-sets branch still reads with parallel replicas.

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

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

Follow-up fix for the AI-review finding on the column-pruned-subquery path (commit f17f302).

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Pruned subquery SELECT a FROM (GROUPING SETS branch UNION ALL FINAL branch) on a 3-replica cluster: ParallelReplicasUsedCount=0 on the unfixed build, deterministically.
b Root cause explained? On the pruned-subquery path (required_result_column_names non-empty) the constructor runs the header-probe loop first. getCurrentChildResultHeader instantiated the temp children on the shared mutable parent context; the FINAL child calls context->setSetting("allow_experimental_parallel_reading_from_replicas", 0), mutating the parent context. The real children (built later with Context::createCopy) then copy the already-corrupted context, so the grouping-sets branch loses parallel replicas. Instrumentation showed the shared context going 1 -> 0 across the probe loop.
c Fix matches root cause? Yes. The probe now gets its own Context::createCopy(context), identical to the buildCurrentChildInterpreter fix, so a probed branch cannot mutate the parent context.
d Test intent preserved / new tests added? Yes. Extended 04492_... with the pruned-subquery case asserting ParallelReplicasUsedCount > 0 on the grouping-sets branch (a correct-results check cannot catch a silently-dropped optimization). Existing assertions unchanged.
e Both directions demonstrated? Yes. Test prints pruned subquery: pr NOT used on the unfixed binary (Build ID e9b1dd68, FAILS vs reference) and pruned subquery: pr used with the fix (Build ID 16f77481, 30/30 with randomization).
f Fix is general across code paths? Yes. All three probe branches (ASTSelectWithUnionQuery / ASTSelectQuery / ASTSelectIntersectExceptQuery) now use the copied context, matching the sibling buildCurrentChildInterpreter. The two paths that instantiate child interpreters on context are now both isolated.
g Fix generalizes across inputs? Yes. The leak is a settings-scope issue independent of column types; the isolation applies to every probed child regardless of query shape. Verified with grouping-sets first and FINAL first, and INTERSECT/EXCEPT (which take the full-header path and skip the probe).
h Backward compatible? Yes. No setting default, wire/disk format, or validation change; purely restores per-branch settings isolation for the header probe.
i Invariants and contracts preserved? Yes. getCurrentChildResultHeader only reads a sample header; using a per-child context copy does not change the returned header (verified results unchanged, analyzer path unaffected). It restores the same contract the real construction path already relies on: each branch plans in its own settings scope.

Session id: cron:clickhouse-worker-slot-4:20260701-031100

…terministic

The pruned-subquery case added for the header-probe fix asserts that the
grouping-sets branch reads with parallel replicas (ParallelReplicasUsedCount > 0).
The CI flaky check randomizes automatic_parallel_replicas_mode to 2 in ~25% of
runs. With the old analyzer (enable_analyzer = 0), a non-zero
automatic_parallel_replicas_mode is unsupported, so InterpreterSelectQuery resets
allow_experimental_parallel_reading_from_replicas to 0 and no parallel replicas
are used, flipping the assertion to "pr NOT used". Pin the setting to 0 in the
test's settings block so the injected value is overridden and the assertion holds
under randomization, without touching the grouping-sets coverage.

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

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

Fixed the PR-caused flaky-check failure on the newly-added pruned-subquery case (Stateless tests (amd_debug/amd_asan_ubsan/amd_tsan/amd_msan, flaky check)), commit a1aa2ce.

Root cause. The pruned-subquery case asserts the grouping-sets branch reads with parallel replicas (ParallelReplicasUsedCount > 0). The flaky check randomizes automatic_parallel_replicas_mode to 2 in ~25% of runs (tests/clickhouse-test line 1518). With the old analyzer (enable_analyzer = 0, which this test uses), a non-zero automatic_parallel_replicas_mode is unsupported, so InterpreterSelectQuery (src/Interpreters/InterpreterSelectQuery.cpp:586-596) resets allow_experimental_parallel_reading_from_replicas to 0 and no parallel replicas are used, flipping the assertion to pruned subquery: pr NOT used. Every failing flaky-check run had --automatic_parallel_replicas_mode 2 (100% correlation in CIDB); prefer_localhost_replica varied 0/1 and was not the driver.

Fix. Pin SET automatic_parallel_replicas_mode = 0; in the test's settings block so the injected value is overridden. Grouping-sets coverage is unchanged.

Reports:

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On a 3-replica local cluster (non-analyzer), the pruned-subquery query with automatic_parallel_replicas_mode = 2 deterministically yields pr NOT used; with = 0 it yields pr used. Reproduced the exact CI diff via the runner with --client-option automatic_parallel_replicas_mode=2 (FAIL) and confirmed 100% CIDB correlation with mode=2.
b Root cause explained? Yes. flaky check injects automatic_parallel_replicas_mode=2 -> old-analyzer path (InterpreterSelectQuery.cpp:586-596) resets allow_experimental_parallel_reading_from_replicas=0 -> ParallelReplicasUsedCount=0 -> assertion flips to pr NOT used.
c Fix matches root cause? Yes. Pins the one injected setting (automatic_parallel_replicas_mode = 0) that defeats PR on this path. Not a bounds-widening or blanket no-random-* band-aid.
d Test intent preserved / new tests added? Yes. The assertion still verifies the grouping-sets branch uses parallel replicas; only the interfering randomized setting is pinned. No coverage removed.
e Both directions demonstrated? Yes. Without the pin + injected mode=2: FAIL (pr NOT used, byte-identical to CI). With the pin: 100/100 full-randomization, 50/50 --flaky-check, 10/10 with mode=2 forced.
f Fix is general across code paths? N/A (flaky test setting fix, not a code bug). The C++ code path fix is the separate commit f17f302 already validated in this PR.
g Fix generalizes across inputs? N/A (flaky test setting fix, not a code bug).
h Backward compatible? N/A (flaky test setting fix, not a code bug).
i Invariants and contracts preserved? N/A (flaky test setting fix, not a code bug).

Session id: cron:clickhouse-worker-slot-3:20260701-044600

@clickhouse-gh

clickhouse-gh Bot commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 85.40% +0.00%
Functions 92.60% 92.60% +0.00%
Branches 77.70% 77.60% -0.10%

Changed lines: Changed C/C++ lines covered: 20/21 (95.24%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — a1aa2ce

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
CH Inc sync private fork-sync mirror CH Inc sync (private, not actionable by us)

All real CI is green on this head. Finish Workflow and Mergeable Check both pass; the 4 flaky-check lanes (amd_debug / amd_asan_ubsan / amd_tsan / amd_msan) now pass 56/56 after the pruned-subquery automatic_parallel_replicas_mode pin. No PR-caused failures.

Session id: cron:our-pr-ci-monitor:20260701-090000

@alexey-milovidov alexey-milovidov 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.

Thanks, that's clear.

@alexey-milovidov alexey-milovidov self-assigned this Jul 1, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 1, 2026
Merged via the queue into ClickHouse:master with commit 8694ed0 Jul 1, 2026
174 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 1, 2026
alexey-milovidov added a commit that referenced this pull request Jul 2, 2026
…o-read-setting

The branch was ~11.7k commits behind (last merge 2026-06-20) and red. The
diff vs. `master` is still the single randomizer line — no functional change:

    "parallel_replicas_min_number_of_rows_per_replica": lambda: random.randint(0, 1),

Reason to re-merge now: the parallel-replicas owners have landed several
directly relevant fixes since 2026-06-20, so refreshing CI on today's
`master` will narrow the remaining set of genuine product bugs this PR is
meant to surface:
- #108451 (`Fix NOT_FOUND_COLUMN_IN_BLOCK for virtual columns under parallel
  replicas`, closes #106561) — should clear the tracked
  `04098_asterisk_include_virtual_columns_mergetree` failure.
- #101434 (`Reimplement reading in order for parallel replicas`) — bears
  directly on the `max_rows_to_read`-not-honored class
  (`02155_read_in_order_max_rows_to_read`, `00945_bloom_filter_index`).
- #109003 (`Fix server abort on GROUPING SETS in a set operation with
  parallel replicas`) — a "Server died" class fix.
- Flaky-test fix for `04051_pk_analysis_stats`.

Conflicts were all in files the branch does not intentionally change (its
only intended change is the one `tests/clickhouse-test` line); they were
resolved by taking `master`'s version. No pinning/blacklisting of the
affected parallel-replicas tests — that would mask the very signal this PR
exists to produce.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…merging-aggregated-grouping-set

Fix server abort on GROUPING SETS in a set operation with parallel replicas
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.

3 participants