Repository navigation
Apply SORT + LIMIT before ARRAY JOIN - #116550
Conversation
Introduce `query_plan_top_k_through_array_join` to restrict ARRAY JOIN input rows when the sort key does not reference joined columns. Extract shared `peelPassThroughExpressions` from `topKThroughJoin` and add functional, explain, and performance tests.
Move bounded sorting below `ARRAY JOIN`, safely pre-limit expansion-only queries, and preserve unaffected ordering prefixes. Add guards and coverage for inner, left, chained, offset, serialization, and metrics cases. Related: ClickHouse#115157
Handle consecutive ARRAY JOIN steps by inserting an inner limit and emptiness guard for each join, walk through filters when detecting duplicate limits, and resolve guard columns from analyzer aliases as well as original input names.
Resolve joined and source column names inside the helper so limit and top-K rewrites pass only the step and insertion point.
…ons. Peel pass-through Expression steps in an inner loop before each ArrayJoin step, matching the structure used in both limit pushdown and Top-K rewrite.
|
@yariks5s I've made an initial attempt at this. Could you review it when you get a chance? Thanks! |
|
Will try to take a look shortly, thank you for the contribution! |
|
Be aware that I'm planning to intoduce several optimizations/changes for ArrayJoin (that will probably be merged before this one): #112241 |
|
Workflow [PR], commit [f9738a5] Summary: ✅
AI ReviewSummaryAdds an opt-in optimization that moves bounded sorting below an eligible Performance & SafetyThe long-array workload demonstrates the documented memory tradeoff: local median peak memory increased from approximately 45 MiB to 161 MiB because sorting retains whole arrays. The setting remains disabled by default. These local Fast Test measurements do not replace release-build performance CI. Final VerdictStatus: ✅ Approve. No additional changes requested. |
e9a718e to
fbc2aa6
Compare
|
@ylw510 do you plan to keep working on this PR? |
Yes, I’m planning to continue implementing it. Could you review it first? Some things might need to be changed, but I didn’t realize it. |
…initializers. Add the three query plan through-array-join settings to the current 26.9 compatibility block so settings_changes_history CI passes. Initialize the new ArrayJoin::source_columns field where the struct is constructed directly.
| if (limit->withTies()) | ||
| return 0; | ||
|
|
||
| if (settings.push_down_limit_through_array_join) |
There was a problem hiding this comment.
Do we need LIMIT-only push-down in this PR? As the issue says, it saves about one block, because LimitTransform already stops the pipeline. It becomes useful only with the follow-up that postpones reading the array
I'd remove it from here and add it together with that follow-up. That removes hasEquivalentLimitBelow, hasSortingBelow, the flag in ExtraSettings and 05022. If you want to keep it, then make it a separate optimization in the list, with its own setting and for a single step only
There was a problem hiding this comment.
Agreed — I'll remove it from this PR. Thanks!
We can do the limit + late materialization optimization in a follow-up PR. Let's keep this PR as small as possible instead of making it a giant.
Keep a single-step top-K rewrite, disable it by default under 26.10, and remove LIMIT push-down and order-preservation through ARRAY JOIN after review. Convert the rows_before_limit check to SQL and drop the obsolete tests.
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
|
@groeneai Help investigate the CI failures. If they are related and true, give advice on how to address them. |
|
I looked at the current head ( 1. SELECT x, e FROM (SELECT x, arr AS e FROM t_aj ARRAY JOIN arr ORDER BY x LIMIT 1 BY x LIMIT 5) ORDER BY x, e
Measured on a master-only debug build (26.10.1.1, i.e. without this branch and without the new setting), same table, CI-randomized The fix is to assert only what the query determines, i.e. drop SELECT x FROM (SELECT x, arr AS e FROM t_aj ARRAY JOIN arr ORDER BY x LIMIT 1 BY x LIMIT 5) ORDER BY x30/30 runs gave 2. It fails only in
3. All four lines report Optional hardening for 05020: its reference pins |
…opKThroughArrayJoin.cpp`, shorten the comment
…tepForReadInOrder` finds the read, use `optimize_read_in_order` in 05020
…est, the moved sort keeps whole arrays
Cherry pick #116550 to 26.10: Apply `SORT + LIMIT` before `ARRAY JOIN`
Includes the backport of #116550, which this change needs and which is not in 26.10 yet.
Related: #115157
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Queries with
ARRAY JOINfollowed byORDER BY ... LIMITcan run faster when the sort keys do not depend on expanded columns. The query planner can move bounded sorting below the expansion so only the top-n input rows are expanded, while the outerLIMITstill truncates the expanded output. For an innerARRAY JOIN, an emptiness guard is inserted so rows whose arrays are all empty are filtered before the moved sort. The rewrite is controlled byquery_plan_top_k_through_array_joinand is disabled by default.Workflow [PR]
Sync PR [sync-upstream/pr/116550]
Version info
26.11.1.839-master(included in26.11and later)