Skip to content

Fix null AST assertion for ORDER BY ALL over a Merge table with JOIN (old analyzer) - #109139

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-order-by-all-merge-join-old-analyzer
Aug 9, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-order-by-all-merge-join-old-analyzer

Conversation

@groeneai

@groeneai groeneai commented Jul 2, 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):

Fix a null-pointer assertion (px != 0 in TreeRewriter::analyzeSelect, aborting the server in debug and sanitizer builds) when running ORDER BY ALL (or GROUP BY ALL) over a Merge-engine table joined with another table under the old analyzer (allow_experimental_analyzer = 0).

Description

removeJoin() rewrites the per-child query for a Merge table by dropping the ORDER BY and GROUP BY expressions, but it left the order_by_all / group_by_all flags set. That breaks the invariant order_by_all implies orderBy() != nullptr: the modified child query is then re-analyzed by the old analyzer, expandOrderByAll() dereferences a now-null orderBy(), and the null boost::intrusive_ptr<IAST> assertion aborts (in debug/sanitizer; release throws and handles it). The same invariant is also assumed by ASTSelectQuery::formatImpl.

Fix: reset both flags in removeJoin when their expressions are removed. removeJoin is shared by StorageMerge, StorageDistributed and StorageWindowView, so all three are covered.

Minimal reproducer (old analyzer):

CREATE TABLE a (key UInt32) ENGINE = MergeTree ORDER BY key;
CREATE TABLE b (key UInt32, ID UInt32) ENGINE = MergeTree ORDER BY key;
CREATE TABLE m (key UInt32) ENGINE = Merge(currentDatabase(), 'a');
SET allow_experimental_analyzer = 0, enable_order_by_all = 1;
SELECT * FROM m INNER JOIN b USING (key) ORDER BY ALL;

Found by the AST fuzzer.
Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107736&sha=ea4864005b8409e8edb3e4f1e9ce4ce645dfc7a9&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%29 (STID 2982-48f0, AST fuzzer (amd_debug)).

Version info

  • Merged into: 26.8.1.1031 (included in 26.8 and later)

…ld analyzer)

removeJoin() drops the ORDER BY and GROUP BY expressions from the modified
per-child query but left the order_by_all / group_by_all flags set. That
breaks the invariant "order_by_all implies orderBy() != nullptr": when the
Merge child query is re-analyzed by the old analyzer, expandOrderByAll()
dereferenced a now-null orderBy() and aborted with a null intrusive_ptr
assertion (px != 0) in TreeRewriter::analyzeSelect. The same invariant is
also assumed by ASTSelectQuery::formatImpl.

Reset both flags in removeJoin so the invariant holds after the expressions
are removed. removeJoin is shared by StorageMerge, StorageDistributed and
StorageWindowView, so all three paths are covered.

Found by the AST fuzzer.

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

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT * FROM m INNER JOIN b USING (key) ORDER BY ALL with allow_experimental_analyzer=0, enable_order_by_all=1 where m is a Merge table aborts every time (exit 134, px != 0).
b Root cause explained? removeJoin() drops the ORDER BY expression via setExpression(ORDER_BY, {}) but leaves the order_by_all flag set, breaking the invariant order_by_all implies orderBy() != nullptr. The modified Merge child query is then re-analyzed by the old analyzer, expandOrderByAll() dereferences the now-null orderBy() -> null intrusive_ptr<IAST> -> assert.
c Fix matches root cause? Yes. Resets order_by_all (and symmetric group_by_all) in removeJoin when the expressions are removed, restoring the invariant at its source rather than guarding the deref site.
d Test intent preserved / new tests added? New regression test 04417_merge_join_order_by_all_old_analyzer covering ORDER BY ALL and GROUP BY ALL over a Merge+JOIN query under the old analyzer.
e Both directions demonstrated? Pre-fix binary (Build ID 21f972dc) aborts (exit 134); post-fix binary (Build ID 39894585) returns correct results (exit 0). Test passes 30/30 with randomization.
f Fix is general across code paths? Yes. removeJoin is shared by StorageMerge, StorageDistributed and StorageWindowView; fixing it at the source covers all three callers. group_by_all reset added symmetrically to close the same invariant gap.
g Fix generalizes across inputs? Yes. The bug is purely a flag/expression desync in removeJoin, independent of column datatypes or wrappers; it fires whenever order_by_all/group_by_all is set on a JOIN query rewritten by removeJoin. Both ORDER BY ALL and GROUP BY ALL are exercised.
h Backward compatible? Yes. No setting default, on-disk/wire format, or behavior change for valid queries. Previously-aborting queries now execute correctly, matching the new-analyzer behavior.
i Invariants and contracts preserved? Yes. Restores the documented invariant order_by_all implies orderBy() != nullptr (also relied on by ASTSelectQuery::formatImpl and expandOrderByAll). No lock/ownership/block-structure contracts touched.

Session id: cron:clickhouse-worker-slot-4:20260702-092100

@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @azat — could you review this? removeJoin() dropped the ORDER BY / GROUP BY expressions from the Merge per-child query but left the order_by_all / group_by_all flags set, so the old analyzer's expandOrderByAll() dereferenced a null orderBy() (assert px != 0). The fix resets both flags alongside their expressions, covering the shared StorageMerge / StorageDistributed / StorageWindowView paths.

@alexey-milovidov

Copy link
Copy Markdown
Member

Merged current master into the branch to re-trigger CI (the previous run had gone stale since 07-02).

Additional evidence this keeps biting: the same crash (STID 2982-48f0, Assertion `px != 0' failed in TreeRewriter::analyzeSelect via ReadFromMerge::createChildrenPlans) just hit the targeted AST fuzzer on #109843 (report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109843&sha=36009c0a1f12e96ac120e7924f55adae221e8e2c&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29), and previously hit unrelated PRs #100173, #107736, #110633, #110760. I independently re-derived the root cause and arrived at exactly this patch before finding this PR.

Re-verified locally on the merged branch: SELECT * FROM m PASTE JOIN m AS a70 ORDER BY ALL (old analyzer, m = Merge) segfaults a master build and passes with this fix; 04417_merge_join_order_by_all_old_analyzer matches its reference.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @novikd - could you review this? removeJoin() clears the Merge child query's ORDER BY and GROUP BY expressions but leaves ASTSelectQuery::order_by_all / group_by_all set, which breaks the invariant that order_by_all implies orderBy() != nullptr; the old analyzer's expandOrderByAll() then dereferences the null AST. The patch resets both flags where the expressions are dropped.

Still reproducible on master today: SELECT * FROM m PASTE JOIN m AS a70 ORDER BY ALL with allow_experimental_analyzer=0, enable_order_by_all=1 aborts on Assertion 'px != 0' in a debug build whose getHeaderForProcessingStage.cpp, TreeRewriter.cpp and ASTSelectQuery.cpp are byte-identical to the current tip. The family cost 7 AST fuzzer jobs across 6 unrelated PRs in the last 30 days, under two guards: px != 0 in debug builds (STID 2982-48f0) and member access within null pointer of type 'DB::IAST' at TreeRewriter.cpp:850 in UBSan (STID 0250-39f3).

One caveat before you spend time on it: no CI has ever run here. Both PR workflow runs, the original one from 07-02 and the one from the master merge on 07-23, are stuck at action_required with zero jobs, so the fork workflow needs approving first.

@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e02017e]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_tsan, s3 storage, parallel, 3/3) FAIL
04098_tuple_inside_nullable_subcolumn_cache_reads FAIL cidb
Stress test (amd_msan) FAIL
Cannot start clickhouse-server FAIL cidb
Check failed FAIL cidb
Upgrade check (amd_release) FAIL
Changed settings are not reflected in the settings changes history (see changed_settings.txt) FAIL cidb
New settings are not reflected in settings changes history (see new_settings.txt) FAIL cidb
Error message in clickhouse-server.log (see upgrade_error_messages.txt) FAIL cidb

AI Review

Summary

This PR fixes the specific group_by_all / order_by_all null-pointer invariant break in removeJoin for ORDER BY ALL and GROUP BY ALL under the old analyzer. The remaining issue is broader: the AST rewrite helpers here still erase or replace full GROUP BY / ORDER BY clauses without clearing all of the clause-owned modifiers, so the rewritten AST remains internally inconsistent and valid Merge+JOIN and WINDOW VIEW inputs still fail on nearby syntax variants.

Findings

❌ Blockers

  • [src/Storages/WindowView/StorageWindowView.cpp:783] StorageWindowView::getSourceTableSelectQuery still rewrites or removes ORDER BY without normalizing order_by_all. For a WINDOW VIEW ... POPULATE AS SELECT ... ORDER BY ALL query, the rewritten source query can therefore reach the old-analyzer ORDER BY ALL handling with either a synthetic timestamp sort or no ORDER BY list at all, so the same invariant gap survives outside removeJoin. Clear order_by_all when this helper rewrites the clause, and add a regression on the WINDOW VIEW path.
  • [src/Interpreters/getHeaderForProcessingStage.cpp:61] Clearing only group_by_all is not enough after dropping GROUP BY. removeJoin also clears rewriter_result.aggregates, so re-analysis sees a non-aggregating query; any surviving group_by_with_totals / group_by_with_rollup / group_by_with_cube / group_by_with_grouping_sets then trips InterpreterSelectQuery's WITH TOTALS, ROLLUP, CUBE or GROUPING SETS are not supported without aggregation check. A valid old-analyzer query like ... GROUP BY key WITH TOTALS over a Merge table with a JOIN still fails. Clear the other GROUP BY modifiers together with the removed list, and add a regression that exercises at least one of those variants.
  • [src/Interpreters/getHeaderForProcessingStage.cpp:104] Clearing only order_by_all is not enough after dropping ORDER BY. The rewritten AST can still carry limit_with_ties or INTERPOLATE: the former later throws LIMIT WITH TIES without ORDER BY, and the latter still reaches query.orderBy()->children in getInterpolateDescription. A valid old-analyzer query like ... ORDER BY key LIMIT 1 WITH TIES or ORDER BY ... WITH FILL INTERPOLATE over a Merge table with a JOIN still breaks in header analysis. Clear the remaining ORDER BY-dependent modifiers when the clause is removed, and cover one of these cases in the regression test.
Final Verdict

❌ Changes requested. The ALL flags are now synchronized, but removeJoin still leaves other GROUP BY / ORDER BY-owned modifiers attached to clauses it has erased, so the fix is incomplete for valid old-analyzer inputs.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.70% -0.10%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 28, 2026
@vdimir vdimir self-assigned this Jul 28, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — e02017e

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
Config Workflow / Pre Hooks the can be tested label is required before the fork workflow may run; only a maintainer can apply it pending maintainer action — nothing to fix in this PR
Finish Workflow / Post Hooks new_tests_check.py gate: every per-arch Bugfix validation job is DROPPED because the run was gated above, so the new test was never measured against master HEAD pending maintainer action — nothing to fix in this PR

Session id: cron:our-pr-ci-monitor:20260729-043000

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 5, 2026
select.setExpression(ASTSelectQuery::Expression::HAVING, {});
select.setExpression(ASTSelectQuery::Expression::ORDER_BY, {});
/// order_by_all implies a non-null orderBy(); keep that invariant after dropping ORDER BY.
select.order_by_all = false;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

removeJoin now repairs the order_by_all invariant for this header-rewrite path, but StorageWindowView::getSourceTableSelectQuery() still rewrites ORDER BY without clearing the same flag (src/Storages/WindowView/StorageWindowView.cpp:783-800). For CREATE WINDOW VIEW ... POPULATE AS SELECT ... GROUP BY tumble(now(), ...) ORDER BY ALL, ASTCreateQuery::isCreateQueryWithImmediateInsertSelect() sends the source-table read through that helper, the is_time_column_func_now branch drops ORDER BY, and the old analyzer reaches expandOrderByAll() with orderBy() == nullptr again. Even without now(), the stale flag makes the rewritten timestamp sort expand back to ORDER BY ALL instead of the clause this helper just built. Please normalize order_by_all there as well and add a regression on the WINDOW VIEW ... POPULATE ... ORDER BY ALL path.

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.

The order_by_all gap in StorageWindowView is real, but it is a different defect from the one this PR fixes, and this PR neither causes nor fixes it.

Measured on two debug binaries: ch-base = pristine master 2169bf5d402de64 (fix absent, grep -c order_by_all on the built file = 0), ch-fix = the same tree plus only this PR's src/ hunk. CREATE WINDOW VIEW ... POPULATE AS SELECT ... GROUP BY tumble(now(), INTERVAL '1' SECOND) ORDER BY ALL aborts with px != 0 on both arms, while the control SELECT * FROM m INNER JOIN b USING (key) ORDER BY ALL aborts on base and returns 0 5 1 / 2 7 3 on fix. So the probe discriminates and the window-view shape is untouched by this change.

Two corrections to the attribution. The repro has no JOIN at all, and removeJoin returns immediately when !hasJoin(select), so it cannot be on that path; getSourceTableSelectQuery does not appear in the stack either, which is TreeRewriter::analyzeSelect <- InterpreterSelectQuery.cpp:850 <- InterpreterInsertQuery.cpp:640 <- InterpreterCreateQuery::fillTableIfNeeded at :2826. And the crashing branch is the else at StorageWindowView.cpp:800 (is_time_column_func_now == true, the now() case, which drops ORDER BY outright), not the !is_time_column_func_now rewrite at :783-797.

I also measured the three neighbouring shapes: tumble(now(), ...) without ORDER BY ALL, and both tumble(ts, ...) variants, all abort with a different assertion (std::out_of_range: unordered_map::at) that is already tracked separately. So only the now() plus ORDER BY ALL shape is this facet, and the other three would still abort after any order_by_all change here.

Given that, I am not widening this PR: it is a different function in a different subsystem, and one root cause per PR keeps this diff reviewable. The path also needs allow_experimental_window_view = 1 (default off, "Not mature enough") plus the old analyzer, and I have no issue or report for it, so I am not opening anything for it either. StorageWindowView.cpp has 0 occurrences of order_by_all on master, so the gap is recorded here if someone wants to pick it up.

/// Also remove GROUP BY cause ExpressionAnalyzer would check if it has all aggregate columns but joined columns would be missed.
select.setExpression(ASTSelectQuery::Expression::GROUP_BY, {});
/// Reset the flag too: it must not stay set once its expression is gone.
select.group_by_all = false;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

removeJoin is still leaving the rewritten AST in an invalid GROUP BY state here. After setExpression(GROUP_BY, {}) and rewriter_result.aggregates.clear(), re-analysis treats the query as non-aggregating, but any surviving group_by_with_totals / group_by_with_rollup / group_by_with_cube / group_by_with_grouping_sets then hits InterpreterSelectQuery's WITH TOTALS, ROLLUP, CUBE or GROUPING SETS are not supported without aggregation path.

So a valid old-analyzer query like ... GROUP BY key WITH TOTALS over a Merge table with a JOIN still fails after this patch. We need to clear the other GROUP BY-owned modifiers together with the list, not only group_by_all.

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.

I checked this and could not reproduce it: the query returns correct results on unpatched master, so there is nothing here for this PR to fix.

SELECT key, count() FROM m INNER JOIN b USING (key) GROUP BY key WITH TOTALS (old analyzer, m = Merge) returns 0 1 / 2 1 / 0 2 on both a pristine master debug build and the same build plus this PR's hunk. WITH ROLLUP, WITH CUBE and GROUP BY GROUPING SETS ((key)) all behave the same way on both arms. The control for the probe is the bug this PR does fix, which aborts on the pristine build and passes with the patch.

The reason is that removeJoin only ever rewrites the AST for header analysis, and that throw is execution-only. WITH TOTALS, ROLLUP, CUBE or GROUPING SETS are not supported without aggregation is at InterpreterSelectQuery.cpp:2234, inside the block opened by if (options.to_stage > QueryProcessingStage::FetchColumns) at :1898. With a JOIN, StorageMerge::getQueryProcessingStage returns FetchColumns unconditionally (StorageMerge.cpp:432-433), and FetchColumns = 0 is the minimum of the enum, so that block never runs; the interpreter is also constructed .analyze() (getHeaderForProcessingStage.cpp:188).

That is also why the two flags this PR does reset are the right set: src/Interpreters/TreeRewriter.cpp mentions order_by_all 9 times and group_by_all once, and group_by_with_totals, group_by_with_rollup and group_by_with_grouping_sets zero times. The analysis pass dereferences the former and never reads the latter, so stranding them is unobservable on this path.

select.setExpression(ASTSelectQuery::Expression::HAVING, {});
select.setExpression(ASTSelectQuery::Expression::ORDER_BY, {});
/// order_by_all implies a non-null orderBy(); keep that invariant after dropping ORDER BY.
select.order_by_all = false;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This fixes ORDER BY ALL, but removeJoin still strips the whole ORDER BY clause while leaving other ORDER BY-owned state alive. limit_with_ties later throws LIMIT WITH TIES without ORDER BY, and INTERPOLATE paths still dereference query.orderBy()->children in getInterpolateDescription.

A valid old-analyzer query like ... ORDER BY key LIMIT 1 WITH TIES (or ORDER BY ... WITH FILL INTERPOLATE) over a Merge table with a JOIN still breaks in header analysis. The rewrite needs to clear the other ORDER BY modifiers when it drops the ORDER BY expression, not just order_by_all.

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.

Same as the sibling comment: I could not reproduce either shape, and both return correct results on unpatched master.

On a pristine master debug build and on the same build plus this PR's hunk, SELECT * FROM m INNER JOIN b USING (key) ORDER BY key LIMIT 1 WITH TIES returns 0 5 1 on both, and SELECT key, val FROM m INNER JOIN b USING (key) ORDER BY key WITH FILL FROM 0 TO 3 STEP 1 INTERPOLATE (val AS val) returns 0 5 / 1 5 / 2 7 on both. The control is the bug this PR fixes, which aborts on the pristine build.

The mechanism is the same: both sites are execution-only and unreachable from the header analysis that removeJoin feeds. LIMIT WITH TIES without ORDER BY is at InterpreterSelectQuery.cpp:3662 in executeLimit, and getInterpolateDescription is called at :3618 in executeWithFill; both are inside the if (options.to_stage > QueryProcessingStage::FetchColumns) block at :1898, and a Merge read with a JOIN is pinned to FetchColumns (StorageMerge.cpp:432-433). TreeRewriter.cpp never reads limit_with_ties, and its interpolate handling dereferences interpolate() only (:422-454, :506-521), never orderBy().

For what it is worth, the invariant you describe is already enforced where it is reachable: ASTSelectQuery.cpp:843-850 rejects limit_with_ties without a LIMIT length and without an ORDER BY.

On the earlier note about sibling flags: limit_by_all is genuinely not affected here, since removeJoin never calls setExpression on LIMIT BY, and formatImpl's limit_by_all branch is nested under if (limitByLength()).

@clickhouse-gh

clickhouse-gh Bot commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 47.50% 86.20% +38.70%
Functions 57.50% 92.00% +34.50%
Branches 35.90% 78.30% +42.40%

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

Full report · Diff report

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — a59695b

CI is fully finished on this head and there are no failures to own: 175 check-runs,
158 success, 17 skipped, 0 incomplete, Config Workflow and Finish Workflow both
success.

Check / test Reason Owner / fixing PR
— no failing check on this head —

The three failures the previous ledger recorded for e02017e34109
(04098_tuple_inside_nullable_subcolumn_cache_re..., the Stress test (amd_msan) server
start, and the Upgrade check (amd_release) settings-history rows) are absent on this
head
. The settings-history rows in particular were an artifact of that stale base: the
join_runtime_filter_min_probe_rows entry sat in the 26.7 section there while master had
already relocated it to 26.8, and the upgrade runner exempts a changed setting only when
the new version is strictly greater than the base version. That relocation is my own merged
PR #111671, so the current base carries it and the rows no longer appear.

Session id: cron:our-pr-ci-monitor:20260806-020000

@clickgapai

Copy link
Copy Markdown
Contributor

Hi @groeneai @alexey-milovidov @vdimir — while reviewing this PR I found the following:

Happy to discuss — close anything that's wrong or already addressed.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Confirmed real, and already owned by #113759 (open, @ alexey-milovidov). I did not author a fix.

Measured on prebuilt release binaries, ORDER BY ALL arm vs the same statement without the clause as control:

binary ORDER BY ALL control
master f70042f0 SIGSEGV Code: 1001 std::out_of_range
#113759 63d9e628 Code: 1001 Code: 1001

So the segfault is specific to the clause and #113759 removes it. The residual Code: 1001 is a separate pre-existing POPULATE defect, visible in the control on master too.

One correction to the mechanism: #113759 does not patch the else at StorageWindowView.cpp:800 that you identified. It resets order_by_all centrally in ASTSelectQuery::setExpression whenever the ORDER BY clause is removed, so that branch is covered transitively, and expandOrderByAll now throws instead of dereferencing null.

One gap worth flagging: #113759 adds no window-view test (gh pr diff 113759 | grep -ci "window view" is 0), so nothing pins the carrier this finding came from.

middas-0706 pushed a commit to middas-0706/ClickHouse that referenced this pull request Oct 19, 2026
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]>
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.

5 participants