Repository navigation
Fix null AST assertion for ORDER BY ALL over a Merge table with JOIN (old analyzer) - #109139
Conversation
…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]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-4:20260702-092100 |
|
cc @KochetovNicolai @azat — could you review this? |
…rge-join-old-analyzer
|
Merged current Additional evidence this keeps biting: the same crash (STID 2982-48f0, Re-verified locally on the merged branch: |
|
cc @vdimir @novikd - could you review this? Still reproducible on master today: 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 |
|
Workflow [PR], commit [e02017e] Summary: ❌
AI ReviewSummaryThis PR fixes the specific Findings❌ Blockers
Final Verdict❌ Changes requested. The LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 8/8 (100.00%) · Uncovered code |
CI finish ledger — e02017eEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260729-043000 |
| 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; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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()).
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 8/8 (100.00%) · Uncovered code |
CI finish ledger — a59695bCI is fully finished on this head and there are no failures to own: 175 check-runs,
The three failures the previous ledger recorded for Session id: cron:our-pr-ci-monitor:20260806-020000 |
|
Hi @groeneai @alexey-milovidov @vdimir — while reviewing this PR I found the following:
Happy to discuss — close anything that's wrong or already addressed. |
|
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:
So the segfault is specific to the clause and #113759 removes it. The residual One correction to the mechanism: #113759 does not patch the One gap worth flagging: #113759 adds no window-view test ( |
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]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix a null-pointer assertion (
px != 0inTreeRewriter::analyzeSelect, aborting the server in debug and sanitizer builds) when runningORDER BY ALL(orGROUP BY ALL) over aMerge-engine table joined with another table under the old analyzer (allow_experimental_analyzer = 0).Description
removeJoin()rewrites the per-child query for aMergetable by dropping theORDER BYandGROUP BYexpressions, but it left theorder_by_all/group_by_allflags set. That breaks the invariantorder_by_allimpliesorderBy() != nullptr: the modified child query is then re-analyzed by the old analyzer,expandOrderByAll()dereferences a now-nullorderBy(), and the nullboost::intrusive_ptr<IAST>assertion aborts (in debug/sanitizer; release throws and handles it). The same invariant is also assumed byASTSelectQuery::formatImpl.Fix: reset both flags in
removeJoinwhen their expressions are removed.removeJoinis shared byStorageMerge,StorageDistributedandStorageWindowView, so all three are covered.Minimal reproducer (old analyzer):
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
26.8.1.1031(included in26.8and later)