Skip to content

Fix logical error on GROUP BY GROUPING SETS with force_aggregation_in_order - #109862

Merged
PedroTadim merged 6 commits into
ClickHouse:masterfrom
groeneai:fix-2310-3e66-explain-pipeline
Jul 30, 2026
Merged

PedroTadim merged 6 commits into
ClickHouse:masterfrom
groeneai:fix-2310-3e66-explain-pipeline

Conversation

@groeneai

@groeneai groeneai commented Jul 9, 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 two errors raised when a query with GROUP BY GROUPING SETS (or a scalar or mutation subquery containing one) runs with force_aggregation_in_order = 1: Trying to get name of not a column: ExpressionList under the old analyzer (enable_analyzer = 0), and Memory bound merging of aggregated results is not supported for grouping sets. for a distributed query with enable_memory_bound_merging_of_aggregation_results = 1 under the analyzer.

Closes: #97988

Description

force_aggregation_in_order built in-order aggregation state for GROUPING SETS on both
planning paths, although AggregatingStep::transformPipeline returns from its grouping-sets
branch before any AggregatingInOrderTransform is created. One bug per path follows; both are
fixed here:

  • Old analyzer: getSortDescriptionFromGroupBy calls getColumnName on every GROUP BY child,
    and with GROUPING SETS those children are ExpressionList nodes, so it raises
    LOGICAL_ERROR (an exception in a release build, a server abort in debug and sanitizer
    builds). The sibling optimize_aggregation_in_order branch already guarded this with
    useGroupingSetKey.
  • Analyzer: Planner::addAggregationStep passed the setting through unguarded, so the stale
    in-order state reached AggregatingStep. enableMemoryBoundMerging then treated the local
    step as in-order-capable, called MergingAggregatedStep::applyOrder, and a distributed query
    with enable_memory_bound_merging_of_aggregation_results = 1 failed in
    MergingAggregatedStep::transformPipeline with Memory bound merging of aggregated results is not supported for grouping sets. Reported by review of the first half; it predates this PR.

On each path the eligibility is derived once and used both where the sort descriptions are built
and where AggregatingStep is constructed, so the step cannot report
explicit_sorting_required_for_aggregation_in_order with empty sort descriptions.

The reported query was a mutation subquery, which the test covers alongside a scalar one. It pins
enable_analyzer at both values there: ExecuteScalarSubqueriesVisitor builds an
InterpreterSelectWithUnionQuery directly, so that carrier keeps the old-analyzer path even with
the analyzer enabled.

The guard keys on GROUPING SETS alone rather than on any of ROLLUP/CUBE/GROUPING SETS:
only GROUPING SETS cannot support memory bound merging, and ROLLUP/CUBE use it today.
Because the result rows are identical either way, the test pins the mechanism with
EXPLAIN PIPELINE in both directions, and a mutation using the wider predicate reddens it.

…_order

The old-analyzer force_aggregation_in_order branch of
InterpreterSelectQuery::executeAggregation called getSortDescriptionFromGroupBy,
which invokes getColumnName() on every GROUP BY child. With GROUPING SETS those
children are ExpressionList nodes, not columns, so this aborted the server with
"Trying to get name of not a column: ExpressionList".

The sibling optimize_aggregation_in_order branch already guarded this with
!useGroupingSetKey(); add the same guard to the force branch.

Closes ClickHouse#97988

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

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. enable_analyzer=0; force_aggregation_in_order=1; SELECT a, sum(b) FROM t GROUP BY GROUPING SETS ((), (a)) aborts every time (SIGABRT) on master HEAD (9ba77fe).
b Root cause explained? Old analyzer's executeAggregation force_aggregation_in_order branch calls getSortDescriptionFromGroupBy, which runs getColumnName() on each GROUP BY child. With GROUPING SETS those children are ExpressionList nodes (one per set), not columns, so getColumnName() throws LOGICAL_ERROR and aborts the server.
c Fix matches root cause? Yes. The sibling optimize_aggregation_in_order branch already skips this path via !query_analyzer->useGroupingSetKey(); the fix adds the identical guard to the force_aggregation_in_order branch.
d Test intent preserved / new tests added? New stateless test 03892_grouping_sets_force_aggregation_in_order (GROUPING SETS + ROLLUP + CUBE + plain GROUP BY under force_aggregation_in_order=1). No existing test weakened.
e Demonstrated in both directions? Yes. Fails (SIGABRT) on the pre-fix build, passes on the post-fix build (test runner + minimal repro).
f Fix general, not a narrow patch? Yes. All three getSortDescriptionFromGroupBy call sites are now guarded by !useGroupingSetKey() (lines 2867/2888, 3025, 3033). Grep-verified.
g Generalizes across inputs? Verified GROUPING SETS single/multi/empty-set, ROLLUP, CUBE, and plain GROUP BY (the last confirming aggregation-in-order still applies when there is no grouping-set key — no regression).
h Backward compatible? Yes. No setting/format/default change; only prevents an abort on a query that should never have crashed. New-analyzer path already handled this correctly and is untouched.
i Invariants and contracts preserved? Yes. getSortDescriptionFromGroupBy's precondition (each GROUP BY child is a column expression) is now respected on the force path exactly as on the optimize path.

Session id: cron:clickhouse-worker-slot-2:20260709-041400

@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @nickitat — could you review this? It adds the missing !useGroupingSetKey() guard to the old-analyzer force_aggregation_in_order branch of executeAggregation, which otherwise calls getColumnName() on the ExpressionList children of a GROUP BY GROUPING SETS and aborts the server (closes #97988).

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [abd94f4]

Summary: ✅


AI Review

Summary

This PR fixes two GROUP BY GROUPING SETS failures behind force_aggregation_in_order = 1: the old-analyzer ExpressionList exception and the analyzer/distributed enable_memory_bound_merging_of_aggregation_results path that still advertised in-order aggregation and later failed in MergingAggregatedStep. The current head propagates the guard consistently through both aggregation planners, and the expanded stateless test now covers the top-level, distributed, mutation-subquery, and scalar-subquery carriers discussed in review. I did not find a remaining correctness or coverage gap in the touched code.

Final Verdict

✅ No new findings.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 42e5493

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
Stress test (amd_debug) / Logical error: Block structure mismatch in A stream: different number of columns (STID 0993-386d) Block structure mismatch in JoinStep: [__table3.number, __table3.number] and [__table3.number] - the decorrelated-correlated-subquery duplicate build-side key column #109114 (ours, merged 2026-07-17)
Sync - CH Inc sync (private, not actionable)

#109114's merge commit 5e9c1f38be32 is NOT an ancestor of this head
(git merge-base --is-ancestor 5e9c1f38be32 42e5493f8810 is false), and this head's CI ran 2026-07-09,
eight days before that merge - so the failure predates the fix rather than surviving it. Merging master
into this branch picks it up and gets a fresh run.

Session id: cron:our-pr-ci-monitor:20260727-170000

groeneai and others added 2 commits July 29, 2026 11:35
Picks up ClickHouse#109114 (merge 5e9c1f3, 2026-07-17), which owns the
Stress test (amd_debug) 'Block structure mismatch in JoinStep' failure
recorded on the previous head's CI ledger, and gets a current-base run.
The GROUPING SETS guard was applied only where the sort descriptions are
built, while `AggregatingStep` was still constructed with the ungated
`force_aggregation_in_order` expression. For GROUPING SETS that left the step
claiming `explicit_sorting_required_for_aggregation_in_order` with both sort
descriptions empty, which makes `isSerializable` return false, so
`calculateHashTableCacheKeys` omits the step parameters and layouts with
identical flattened keys can share preallocation statistics. Derive the
eligibility once and use it in both places.

The result rows of the existing queries are the same whether or not in-order
aggregation runs, so an over-broad guard that also disabled ROLLUP, CUBE and
plain GROUP BY passed the test unchanged. Add `EXPLAIN PIPELINE` assertions
that require `AggregatingInOrderTransform` for the sibling forms and reject it
for GROUPING SETS.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master to pick up #109114, whose fix owns the Stress test (amd_debug) failure
(Block structure mismatch in JoinStep) recorded on the previous head's CI ledger. That
failure's CI ran on 2026-07-09, eight days before #109114 merged, so the build predated the
fix rather than failing with it.

While re-reviewing I found and fixed two defects in my own change:

  • The GROUPING SETS guard was applied only where the sort descriptions are built, while
    AggregatingStep was still constructed with the ungated force_aggregation_in_order
    expression. For GROUPING SETS that left the step reporting
    explicit_sorting_required_for_aggregation_in_order with both sort descriptions empty, so
    isSerializable returns false and calculateHashTableCacheKeys omits the step parameters,
    letting layouts with identical flattened keys share preallocation statistics. The
    eligibility is now derived once and used in both places.
  • The result rows of the ROLLUP, CUBE and plain GROUP BY queries in the test are
    identical whether or not in-order aggregation runs, so the test could not tell a correct
    guard from an over-broad one. I confirmed that by running the same queries with
    force_aggregation_in_order = 0: the reference is reproduced byte for byte. The test now
    also pins the mechanism with EXPLAIN PIPELINE, requiring AggregatingInOrderTransform
    for the sibling forms and rejecting it for GROUPING SETS.

Validation on the merged base, debug build c519e302:

  • The exception still reproduces on current master, so this is not yet fixed upstream. The
    reproducer from Logical error: Trying to get name of not a column: A (STID: 2310-3e66) #97988 aborts a master-snapshot binary and now returns
    Code: 125 INCORRECT_RESULT_OF_SCALAR_SUBQUERY instead.
  • Mutation testing: forcing the eligibility to false flips the three sibling assertions
    from 1 to 0, and dropping only the !useGroupingSetKey() clause restores the abort. So
    both directions are pinned. Restoring rebuilt bit-identically.
  • 100/100 runs pass: 50 deterministic plus 50 with a fresh randomized draw per run, using the
    179 settings and 61 merge-tree settings drawn from tests/clickhouse-test itself.
  • Regression A/B against a master snapshot over the 42 grouping_set and
    aggregation_in_order tests: 30 pass and 12 pre-existing sandbox failures in both arms,
    per-test results identical, so no new failures.

@PedroTadim
PedroTadim disabled auto-merge July 29, 2026 13:32
groeneai and others added 2 commits July 29, 2026 17:37
…UPING SETS

Planner::addAggregationStep passed force_aggregation_in_order to AggregatingStep
unguarded, so a GROUPING SETS query kept in-order sort metadata even though
AggregatingStep::transformPipeline returns from the grouping-sets branch before
any AggregatingInOrderTransform is built. In a distributed query with
enable_memory_bound_merging_of_aggregation_results, enableMemoryBoundMerging then
treated the local step as in-order-capable and called
MergingAggregatedStep::applyOrder, and the initiator raised "Memory bound merging
of aggregated results is not supported for grouping sets." from
MergingAggregatedStep::transformPipeline.

The guard keys on the grouping-sets parameter list alone. Only GROUPING SETS
cannot support memory bound merging; ROLLUP and CUBE use it today, so reusing the
wider aggregation_with_rollup_or_cube_or_grouping_sets predicate from the sibling
distributed_aggregation_memory_efficient argument would remove a working
optimization. The extended test pins both directions with EXPLAIN PIPELINE.

Reproduced on master before this change and verified after it against a
materialized oracle, with the previously measured old-analyzer, ROLLUP, CUBE,
WITH TOTALS, plain GROUP BY and distributed_aggregation_memory_efficient routes
kept as controls.
…s of 03892

The CI `distributed plan` job installs tests/config/users.d/distributed_plan.xml,
which sets serialize_query_plan = 1 for every query. The four distributed control
rows of this test use plain GROUP BY / ROLLUP / CUBE / WITH TOTALS, so with
force_aggregation_in_order = 1 they legitimately keep an in-order sort description,
and AggregatingStep::serialize refuses to serialize such a step:

  Code: 48. Serialization of AggregatingStep optimized for in-order is not
  supported. (NOT_IMPLEMENTED)

That refusal is pre-existing engine behaviour on master, unrelated to grouping sets;
this test is simply the first one driving force_aggregation_in_order = 1 across
remote() while the plan is serialized. Measured on a pristine master debug build:
the same four statements fail identically there, and serialize_query_plan = 0 makes
exactly those four pass.

The pin is per statement rather than a file-level SET, because the two GROUPING SETS
rows must keep running under the ambient CI settings: they are what proves the fix.
Verified they still abort on pristine master with the pin in place elsewhere, so the
pin hides no coverage. The EXPLAIN PIPELINE mechanism rows never serialize a plan and
need no pin.

serialize_query_plan only affects plan serialization across the network and cannot
reach the grouping-sets branch this PR fixes, so it is orthogonal to the fix.

Co-Authored-By: Claude Fable 5 <[email protected]>
The changelog entry says the old-analyzer half of the fix also covers a scalar or
mutation subquery containing GROUPING SETS, but the test only exercised top-level
SELECTs, so that half of the contract was asserted and not pinned. Review of the
test raised this.

The reported query in the linked issue was
`ALTER ... UPDATE c0 = (SELECT ... GROUP BY GROUPING SETS ...)` with
`mutations_execute_subqueries_on_initiator = 1`. That carrier reaches the failing
code through `replaceNonDeterministicToScalars` ->
`ExecuteScalarSubqueriesVisitor` -> `InterpreterSelectWithUnionQuery`, which is
built directly and therefore keeps the old-analyzer path even when
`enable_analyzer = 1`. Both values of that setting are pinned for the mutation
rows, since only measuring them shows the carrier is not analyzer-gated.

On pristine master all three new rows abort the server with
`Trying to get name of not a column: ExpressionList`, and they still do with only
the `useGroupingSetKey` clause removed from this branch, so each is load-bearing
on its own rather than riding on the top-level rows already in the file.

The subquery reads `numbers` rather than the mutated table, so its value does not
depend on how many times the mutation ran, and `ORDER BY 1 DESC LIMIT 1` keeps it
a single row while still using more than one grouping set. A single grouping set
would be silently vacuous: it takes the ordinary aggregation-key path and never
reaches the failing code. The two mutations read different ranges so that the
second one lands a distinct value: with the same assignment its assertion held
even when that mutation was removed entirely.
@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.40% 86.40% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.50% 78.50% +0.00%

Changed lines: Changed C/C++ lines covered: 25/25 (100.00%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - abd94f4

CI fully finished on this head: 174 check-runs, all completed (156 success, 18 skipped),
0 failure / 0 timed_out / 0 action_required. Finish Workflow and Config Workflow are both
SUCCESS. Cross-checked in the CI database keyed to this commit: 317954 rows across 158
checks, 0 FAIL/ERROR test rows.

Check / test Reason Owner / fixing PR
(no failures on this head) - -

The failures carried on earlier heads are resolved by re-measurement rather than by a
disposition:

  • Stress test (amd_debug) / Block structure mismatch in JoinStep (STID 0993-386d), owned
    on the 42e5493f8810 ledger by Fix Block structure mismatch in JoinStep for decorrelated correlated subquery with duplicate column name #109114. That fix is now an ancestor of this head and the
    failure did not recur here.
  • 03892_grouping_sets_force_aggregation_in_order on Stateless tests (amd_debug, distributed plan, s3 storage, parallel)
    and Stateless tests (amd_asan_ubsan, distributed plan, parallel), both on head
    6f61ae467e3f. That was my own new test, and it is fixed in this PR: the non-grouping-sets
    assertions now pin serialize_query_plan = 0, revalidated with 200/200 runs under both plan
    variants.

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

@PedroTadim
PedroTadim added this pull request to the merge queue Jul 30, 2026
Merged via the queue into ClickHouse:master with commit 18cc04e Jul 30, 2026
179 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 30, 2026
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: Trying to get name of not a column: A (STID: 2310-3e66)

3 participants