Skip to content

Fix NOT_IMPLEMENTED for Merge over Distributed with a JOIN and a GROUP BY modifier - #118658

Merged
PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-storage-merge-group-by-modifier-flags
Oct 19, 2026
Merged

PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-storage-merge-group-by-modifier-flags

Conversation

@groeneai

@groeneai groeneai commented Sep 7, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #99508

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 NOT_IMPLEMENTED error ("WITH TOTALS, ROLLUP, CUBE or GROUPING SETS are not supported without aggregation") when a query with a JOIN or ARRAY JOIN and a GROUP BY ... WITH TOTALS/ROLLUP/CUBE/GROUPING SETS read a Merge table that matches a Distributed table. The rewritten child query kept the GROUP BY modifier after its GROUP BY clause was removed.

Description

Requested by @ nihalzp in #99508 (comment) as a pre-existing master bug, out of scope of that PR.

A valid query is rejected. With md a Merge table matching a Distributed table:

SELECT md.a, count() FROM md JOIN t2 ON md.a = t2.a GROUP BY md.a WITH TOTALS ORDER BY 1
Code: 48. DB::Exception: WITH TOTALS, ROLLUP, CUBE or GROUPING SETS are not supported
without aggregation: Child table: default.d. (NOT_IMPLEMENTED)

Root cause: replaceTableExpressionAndRemoveJoin builds a per-child query and clears the GROUP BY and ORDER BY node lists (they may reference the removed JOIN), but never resets the modifier flags, and it also replaces the projection, dropping the aggregate functions. The child query for d is therefore aggregation-free while still carrying WITH TOTALS, and a Distributed child re-analyses that tree, where validateAggregates rejects it.

The old-analyzer twin, removeJoin in getHeaderForProcessingStage.cpp, already resets these flags, so enable_analyzer = 0 is unaffected. This mirrors it, alongside the is_limit_with_ties reset the same function already performs.

Verified witnesses: WITH TOTALS, WITH ROLLUP, WITH CUBE, and GROUPING SETS with more than one grouping set, reached through JOIN, ARRAY JOIN, GLOBAL JOIN and the merge() table function. A single-set GROUPING SETS list is collapsed during resolution, which clears its flag too. is_group_by_all, is_order_by_all and is_limit_by_all are also cleared during resolution, so they are not independently observable today; I reset them so the two rewrites agree, matching the AST-side fixes in #109139 and #113759.

Present in 26.3, 26.6 and 26.8.

New test 05136_merge_over_distributed_join_group_by_modifiers: five witnesses plus three controls (a Merge over the plain table as oracle, enable_analyzer = 0, and no JOIN). It fails on master and passes with this change.


Workflow [PR]
Sync PR [sync-upstream/pr/118658]

Version info

  • Merged into: 26.11.1.219-master (included in 26.11 and later)

Reading a Merge table that matches a Distributed table with a JOIN and a
GROUP BY ... WITH TOTALS/ROLLUP/CUBE/GROUPING SETS failed outright:

  Code: 48. DB::Exception: WITH TOTALS, ROLLUP, CUBE or GROUPING SETS are not
  supported without aggregation: Child table: default.d. (NOT_IMPLEMENTED)

replaceTableExpressionAndRemoveJoin builds a separate query for each matched
child table. It clears the GROUP BY, ORDER BY and LIMIT BY node lists, because
they may reference the JOIN it removes, and it replaces the projection with
plain column identifiers, which drops the aggregate functions. It did not reset
the modifier flags belonging to those clauses, so the child query was left with
no GROUP BY keys and no aggregates while still carrying WITH TOTALS. When the
child is a Distributed table that tree is re-analyzed and validateAggregates
rejects it. The child query the rewrite produced is visible in the server log as:

  SELECT `__table1`.`a` AS `a` FROM `t_99508` AS `__table1` WITH TOTALS

The old-analyzer twin of this rewrite, removeJoin in
getHeaderForProcessingStage.cpp, already resets all seven of these flags, which
is why enable_analyzer = 0 was unaffected. This mirrors it, in the same spirit
as the is_limit_with_ties reset the function already performs for the same
reason: a clause modifier flag must not outlive the clause it modifies.

WITH TOTALS, WITH ROLLUP, WITH CUBE, and GROUPING SETS with more than one
grouping set are the independently observable cases, reachable through JOIN,
ARRAY JOIN, GLOBAL JOIN and the merge() table function. A single-set
GROUPING SETS list is collapsed during resolution by
GroupingFunctionsResolvePass, which clears the flag with it, so only a multi-set
list survives to reach this rewrite. is_group_by_all, is_order_by_all and
is_limit_by_all are cleared during resolution, so they cannot be witnessed on
their own today; they are reset as well so that the two rewrites agree, and
because a surviving order_by_all with no ORDER BY list later dereferences a null
orderBy() in ASTSelectQuery. The AST side of that pair was fixed in ClickHouse#109139
and ClickHouse#113759.

Reported by Nihal Z. Miaji on ClickHouse#99508 as a pre-existing master bug.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 7, 2026
@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (3 rounds): 7 agreed and fixed, 3 declined, 1 noted

An independent model reviewed this change against the resulting code, then a second pass re-reviewed it
with the validation evidence. Three rounds, verdicts below.

❌ Blockers: none.

⚠️ Agreed, fixed before publishing:

  • The mirror was one flag short. removeJoin resets seven flags; the first draft reset six, leaving
    is_limit_by_all set while the same function clears the whole LIMIT BY clause eleven lines below.
    Added, so the claim that the two rewrites agree is now literally true.
  • GROUPING SETS is a real witness, not an inert flag. An early single-set probe read as inert
    because GroupingFunctionsResolvePass collapses a one-set list and clears the flag with it. A
    multi-set list survives resolution and is rejected on master, so it is named in the changelog and has
    its own test arm.
  • The WITH ROLLUP/CUBE/GROUPING SETS arms would have reddened the Stress job. It enables
    group_by_use_nulls in half its workers, which renders the subtotal key as NULL instead of 0 and
    moves the row. Pinned to the shipped default on the three arms with a defaultable key; the reference
    is unchanged.
  • The GROUPING SETS arm could not detect its own regression half the time. QueryNode::toASTImpl
    stamps the modifier flags onto the child AST unconditionally but sets GROUP BY only when the node
    list is non-empty, and ASTSelectQuery prints GROUPING SETS only when that list exists, while
    WITH ROLLUP/CUBE/TOTALS print unconditionally. A shard served in memory therefore keeps the
    modifier and rejects the query, while a shard served as formatted SQL loses it in transit. Since
    prefer_localhost_replica is randomized per run, that one arm was a reliable witness only half the
    time. Measured on the unfixed binary with the setting forced both ways, then pinned on that arm alone;
    the other arms stay unpinned so they keep exercising the serialized path.
  • is_distinct is the one clause flag neither rewrite resets. Measured against two independent
    oracles rather than argued about: no observable difference. It is legitimately outside this mirror,
    because its clause is replaced rather than cleared.

💡 Declined, with reasons:

  • "Add a per-flag comment at each reset." The one block explains all three ALL resets together,
    whose expansion passes all read the projection this function replaces. Splitting it would leave two
    resets unexplained and add comments without adding information.
  • "Add an arm per flag." Capped at one arm per user-visible keyword instead. All four modifier flags
    feed one validation condition, so beyond that the arms test the same scenario twice.
  • "@ nihalzp should be @nihalzp." The spaced form cites provenance without adding a second
    notification; the requesting comment is linked directly and I reply in that thread.

💡 Noted, not fixed: the test's header comment says the rejection happens on the initiator while
planning the child. That is true at the default prefer_localhost_replica = 1; with it off, arms 1-4
are rejected shard-side instead. "The child query is rejected wherever it is planned" would be exact.
One local shard is enough either way, so no arm's coverage depends on it.

Nothing was deferred.

@clickhouse-gh clickhouse-gh Bot closed this Sep 7, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6b3c797]

Summary: ✅


AI Review

Summary

The PR clears stale clause modifiers when StorageMerge removes a join and replaces the child query's projection, fixing NOT_IMPLEMENTED errors for grouping modifiers over Distributed children. No actionable findings.

Missing context / blind spots
  • ⚠️ Functional tests and bugfix validation are still pending for head 6b3c797184809672aea0e1700aded7631fc7efc8. The added regression test passed on earlier head abf782a01e4fd72eda547bd3eed47ae69fc39edc in bugfix validation and ARM stateless tests. Current-head results will confirm coverage after the merge from master; no local executable was available to rerun it.
Final Verdict

Status: ✅ Approve. No code changes requested; current-head CI remains pending.

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

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @azat, could you review this? replaceTableExpressionAndRemoveJoin clears the child query's GROUP BY list and replaces the projection, dropping the aggregates, but left the modifier flags set, so a Distributed child re-validated an aggregation-free tree still carrying WITH TOTALS and rejected it with NOT_IMPLEMENTED. This resets the same seven flags the old-analyzer twin removeJoin already resets; @vdimir, it is the query-tree half of the asymmetry behind #109139, which you approved.

@clickhouse-gh clickhouse-gh Bot added the comp-storage-merge Merge table engine (logical union over tables) and related mechanics. label Sep 7, 2026
@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3cf3e46

Every failure below has an owner: a fixing PR (mine 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
Build (arm_tidy) / Build ClickHouse master-side readability-duplicate-include: src/Storages/MergeTree/MergeTreeIndexConditionText.cpp includes DataTypes/DataTypeLowCardinality.h twice (line 11 and line 36). Build (arm_tidy) is red on master itself (5 CIDB rows from 20:34Z) and on ~25 unrelated PRs in the same window #118661 (external, open) and #118664 (external, open), identical one-line diffs removing the second include
Finish Workflow / Post Hooks cascade of the row above: new_tests_check.py reports both Bugfix validation (functional tests, amd64/aarch64) legs as DROPPED (Dropped due to previous failure [Build (arm_tidy)]), so no per-arch leg could report OK #118661 / #118664 (external, open), same fix
Sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20260907-233055

@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6b3c79718 with master 6a78f52eb (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 3389afa5e; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

7 translation units recompiled, 23 s compile time in total, 7 of them have a recent master baseline.

Job report

@PedroTadim

Copy link
Copy Markdown
Member

cc @nihalzp

@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - abf782a

Every failure below has an owner: a fixing PR (mine 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_tsan) / Hung check failed, possible deadlock found hang, not PR-caused: exactly one hung query in the job log, a cancelled odbc() read stuck 395.6 s with is_cancelled = 1 and read_rows = 0, its only running thread parked in poll under Poco::Net::HTTPClientSession::receiveResponse / ReadWriteBufferFromHTTP::nextImpl / StorageURLSource::generate, so the XDBC bridge HTTP read never observes the cancellation #112930 (external, open)
Mergeable Check cascade, its own description reads Failed: Stress test (amd_tsan) #112930 (external, open)
PR cascade, workflow rollup of the same single red job #112930 (external, open)

Everything else at this head is green: 153 pass, 18 skipped, 0 other red. CH Inc sync is success here,
so no exempt row is owed.

Not PR-caused, measured rather than assumed: this diff is src/Storages/StorageMerge.cpp plus the new
05136_merge_over_distributed_join_group_by_modifiers.{sql,reference}, and the hung query is
SELECT count() > 1 FROM (SELECT * FROM odbc(..., 'system', 'tables')) from 01086_odbc_roundtrip.sh,
which reaches none of that code. #112930 ("Improve canceling queries with the url function") patches the
exact frames the thread is parked in: ReadWriteBufferFromHTTP.{cpp,h}, StorageURL.{cpp,h} and
ExecutionThreadContext.cpp. Rule 3c does not apply because it is not merged yet, so nothing is pushed to
this branch and no master merge is owed.

Read from the per-attempt GitHub Actions job log rather than the CIDB test_context_raw, which keeps only
the last 32 KiB and drops the processlist that names the hung query.

Session id: cron:our-pr-ci-monitor:20260908-090153

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai is this PR still needed with all the switches it toggles?

@PedroTadim PedroTadim self-assigned this Oct 13, 2026
@vdimir

vdimir commented Oct 13, 2026

Copy link
Copy Markdown
Member

@groeneai was it ever supported in any version? If not it's ok too keep it not implemented

@groeneai

Copy link
Copy Markdown
Collaborator Author

@PedroTadim @vdimir It did work before the analyzer, and it is still broken on master. Same query (Merge over a Distributed table, JOIN, GROUP BY ... WITH TOTALS), official binaries:

Version Default enable_analyzer = 0
23.8.16.40 (old analyzer by default) correct rows correct rows
24.8, 24.12, 25.3, 25.6, 25.8, 26.1, 26.3, 26.6, 26.7, 26.8 NOT_IMPLEMENTED correct rows
26.9.7.6 NOT_IMPLEMENTED rejected, the analyzer is mandatory
master cb52cc13 (today) NOT_IMPLEMENTED NOT_IMPLEMENTED, the setting is replaced with 1

So it is a regression of the analyzer switch, and since 26.9 there is no workaround. WITH ROLLUP behaves the same on every version.

On the switches: the bug needs only the four GROUP BY modifier resets (WITH TOTALS, ROLLUP, CUBE, GROUPING SETS). The three *_all resets are not observable, because expandGroupByAll/expandOrderByAll/expandLimitByAll already clear those flags during resolution; I added them only to mirror removeJoin. I can drop them, together with the enable_analyzer = 0 arm of the test, which no longer tests anything on master. Should I?

@PedroTadim

Copy link
Copy Markdown
Member

@vdimir this seems to be a long time regression

@PedroTadim
PedroTadim added this pull request to the merge queue Oct 19, 2026
Merged via the queue into ClickHouse:master with commit 1120699 Oct 19, 2026
178 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 19, 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 comp-storage-merge Merge table engine (logical union over tables) and related mechanics. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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.

5 participants