Repository navigation
Fix segfault in expandOrderByAll for a Merge child query - #113759
Conversation
`removeJoin` strips the `ORDER BY` and `GROUP BY` clauses from the rewritten single-table query but left the `order_by_all`/`group_by_all` flags set. Re-analysis of that query for a child plan of `StorageMerge` then called `expandOrderByAll`, which dereferenced the null `orderBy()`. Reset both flags in `removeJoin` and turn the null dereference in `TreeRewriter` into an exception. Found by the targeted AST fuzzer: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104510&sha=c265df97ecae25ad7a94813525aaedaa2b4deee2&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29 (PR: #104510) Closes: #113758 Co-Authored-By: Claude Fable 5 <[email protected]>
|
Workflow [PR], commit [63d9e62] Summary: ✅
AI ReviewSummaryThis PR hardens the old-analyzer AST rewrites behind Findings
Final VerdictStatus: Minimum required actions:
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 39/62 (62.90%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units11 translation units recompiled, 38 s compile time in total, 11 of them have a recent master baseline. |
…r_by_all` reset Two review findings on the clause-removal invariant: - `removeJoin` left `INTERPOLATE` behind after removing `ORDER BY`. `RequiredSourceColumnsVisitor` traverses `select.interpolate()` independently of `orderBy()`, so a rewritten `Merge` child query could still reference columns of the removed joined table and fail with `UNKNOWN_IDENTIFIER`. Now the clause is removed together with `ORDER BY` (regression case added to the test). - Other writers also removed `ORDER BY` without clearing `order_by_all` (`StorageWindowView::getSourceTableSelectQuery`, `DuplicateOrderByVisitor`), leaving the same malformed state. The reset is now centralized in `ASTSelectQuery::setExpression`: removing the `ORDER_BY` expression clears `order_by_all`. This cannot be done for `group_by_all` because `GROUP BY ALL` is legitimately represented as the flag with no `GROUP BY` list until `expandGroupByAll` runs (the parser itself calls `setExpression(GROUP_BY, nullptr)` after setting the flag), so `removeJoin` and `StorageWindowView` reset it explicitly. `CREATE WINDOW VIEW ... ORDER BY ALL` with a `tumble(now(), ...)` window segfaulted before this change (verified on 26.7.1); it no longer does. A clean stateless test for it is blocked by the unrelated pre-existing #113493. Co-Authored-By: Claude Fable 5 <[email protected]>
|
🕵 Addressed both AI review findings in d14e1d1 ( The three CI reds on fd158ed are unrelated to this change:
|
…rewrites `ORDER BY` `StorageWindowView::getSourceTableSelectQuery` replaces (or removes) the `ORDER BY` clause while rewriting the POPULATE source query, but left a stale `INTERPOLATE` list attached. `RequiredSourceColumnsVisitor` walks `INTERPOLATE` independently of `ORDER BY`, so its expressions could pull aliases of the removed select list into the source query (`UNKNOWN_IDENTIFIER`), and the result was a parser-impossible AST shape (`INTERPOLATE` without `WITH FILL`).
|
🕵 The only CI failure on d14e1d1, |
Address review: `removeJoin` and the mirrored non-join branch of `StorageWindowView::getSourceTableSelectQuery` cleared `group_by_all` but left `group_by_with_totals`, `group_by_with_rollup`, `group_by_with_cube`, and `group_by_with_grouping_sets` set after deleting the GROUP BY clause. A stale modifier flag on the rewritten aggregation-free query is a malformed internal AST: `ASTSelectQuery::formatImpl` still emits `WITH TOTALS`/`ROLLUP`/`CUBE` without a GROUP BY, and `InterpreterSelectQuery` rejects that shape with "WITH TOTALS, ROLLUP, CUBE or GROUPING SETS are not supported without aggregation" when the child query is analyzed past the aggregation stage. Regression cases with `WITH TOTALS`/`WITH ROLLUP`/`WITH CUBE`/`GROUPING SETS` on the old-analyzer `merge()` path are appended to the test (all four segfault on 26.7.1 via the original `expandOrderByAll` bug). Co-Authored-By: Claude Fable 5 <[email protected]>
|
🕵 The four CI reds on 63097ab are unrelated to this change:
The remaining AI review Major (stale |
|
🕵 Filed #113989 to track the |
|
Confirmed and reproduced deterministically on plain master (no fuzzer needed), four rows: CREATE TABLE t (n UInt32) ENGINE = MergeTree ORDER BY n;
INSERT INTO t VALUES (1),(2),(3),(4);
SELECT theilsUState(n, n) OVER (ORDER BY n) FROM t
SETTINGS make_distributed_plan = 1, enable_parallel_replicas = 0, distributed_plan_execute_locally = 1;One correction to the issue: it is not the version.
That happens for exactly one family. Arms, same settings, same binary, each verified against the server log:
Two notes on the breadth in the issue. STID 0993-290c pools two unrelated defects, because the CIDB test name does not carry the step: bucketing 90 days on the step in No fix PR exists yet. I am authoring one and will link it here. Two shapes are plausible, the serializer persisting the variant against |
|
Fix PR as promised: #114020 It relaxes the plan-deserialization header check to accept a header pair whose serialized bytes are |
`removeJoin` rewrites the select list of a `Merge`/`Distributed` child query down to left-table columns, but left the `WINDOW` and `LIMIT BY` clauses attached. The old analyzer resolves both unconditionally (`ExpressionAnalyzer::makeWindowDescriptions` and `appendLimitBy`), so a query such as `... NATURAL JOIN r WINDOW w AS (PARTITION BY r.t)` or `... LIMIT 1 BY r.t` still failed with `UNKNOWN_IDENTIFIER` after the join was stripped. Both are now cleared together with the other post-join decorations, along with `QUALIFY`, the `limit_by_all` flag, and the `limit_with_ties` flag (meaningless without the removed `ORDER BY`). The non-join rewrite in `StorageWindowView::getSourceTableSelectQuery` gets the same cleanup. Both `WINDOW` and `LIMIT BY` failures reproduce on a stock 26.7.1 binary and pass with the fix; regression cases added to the test.
|
🕵 The only CI failure on 9ce9dbe, Stress test (amd_debug) — d7c60d5 addresses the remaining AI review Major ( |
|
🕵 The single red on
Everything else is green, all review threads are resolved, and the AI review reports no new findings on the current head. |
…rge-join # Conflicts: # src/Interpreters/getHeaderForProcessingStage.cpp
|
🕵 Merged The conflict is because the core part of this fix — resetting
Verified locally: warning-free incremental build; both The only CI red on the previous head was AST fuzzer (amd_debug, targeted, old_compatibility) |
Cherry pick #113759 to 25.8: Fix segfault in `expandOrderByAll` for a `Merge` child query
Cherry pick #113759 to 26.3: Fix segfault in `expandOrderByAll` for a `Merge` child query
Cherry pick #113759 to 26.5: Fix segfault in `expandOrderByAll` for a `Merge` child query
Cherry pick #113759 to 26.6: Fix segfault in `expandOrderByAll` for a `Merge` child query
Cherry pick #113759 to 26.7: Fix segfault in `expandOrderByAll` for a `Merge` child query
Backport #113759 to 26.7: Fix segfault in `expandOrderByAll` for a `Merge` child query
Backport #113759 to 26.3: Fix segfault in `expandOrderByAll` for a `Merge` child query
Backport #113759 to 26.6: Fix segfault in `expandOrderByAll` for a `Merge` child query
CTE/AN/QP: old analyzer: ORDER BY ALL in WINDOW VIEW; INTERPOLATE/WINDOW/LIMIT BY over Merge/Distributed with a join -> crash/exc. Effect in the production build a394e92: wrong/failing (the upstream test fails on it and passes on official 26.8.8.8; evidence/fix_ci_20260925/upstream_repro/residual/113759.PROD263.txt). Upstream patch unchanged, with its test(s): 04817_order_by_all_merge_natural_join. Co-Authored-By: Claude Opus 5.5 <[email protected]>
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]>
Closes: #113758
Related: #104510
Related: #109139
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix a crash for
ORDER BY ALLin aWINDOW VIEW, andUNKNOWN_IDENTIFIERerrors forINTERPOLATE,WINDOWandLIMIT BYin a query over aMergeorDistributedtable with a join, with the old analyzer.removeJoinandStorageWindowView::getSourceTableSelectQueryrewrite a query into a single-table one and drop some of its clauses, but used to leave behind state that refers to what was just removed:order_by_all/group_by_allflags outlived theORDER BY/GROUP BYclauses they refer to, so a re-analysis by the old analyzer madeexpandOrderByAlldereference the nullorderBy()— a segfault in release builds and theintrusive_ptrassertionpx != 0in debug builds. For theremoveJoinpath this was fixed in Fix null AST assertion for ORDER BY ALL over a Merge table with JOIN (old analyzer) #109139; hereASTSelectQuery::setExpressionresetsorder_by_allwhenever theORDER BYexpression is removed, which additionally coversStorageWindowView(CREATE WINDOW VIEW ... POPULATE ... ORDER BY ALLsegfaulted),DuplicateOrderByVisitorand any future writer. The same cannot be centralized forgroup_by_all, becauseGROUP BY ALLlegitimately has noGROUP BYlist untilexpandGroupByAllmaterializes it, so that flag is reset explicitly in the two rewriting places.INTERPOLATE,WINDOW,QUALIFYandLIMIT BYsurvived the removal ofORDER BY/GROUP BY.RequiredSourceColumnsVisitortraverses them independently of the clause they belong to, so the rewritten child query still asked for columns of the removed joined table and failed withUNKNOWN_IDENTIFIER.GROUP BYmodifiers (WITH TOTALS/ROLLUP/CUBE/GROUPING SETS) andLIMIT ... WITH TIESwere left set without the clause they modify.TreeRewriternow throws an exception instead of dereferencing a nullorderBy(), so any remaining path that breaks the invariant reports it instead of crashing.Found by the targeted AST fuzzer in an unrelated PR: AST fuzzer (amd_debug, targeted, old_compatibility) report (PR #104510).
Version info
26.8.1.1146(included in26.8and later)26.7.6.39,26.6.4.65,26.3.26.4