Skip to content

Apply SORT + LIMIT before ARRAY JOIN - #116550

Merged
yariks5s merged 32 commits into
ClickHouse:masterfrom
ylw510:topk-through-array-join
Oct 27, 2026
Merged

yariks5s merged 32 commits into
ClickHouse:masterfrom
ylw510:topk-through-array-join

Conversation

@ylw510

@ylw510 ylw510 commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Related: #115157

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Queries with ARRAY JOIN followed by ORDER BY ... LIMIT can 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 outer LIMIT still truncates the expanded output. For an inner ARRAY JOIN, an emptiness guard is inserted so rows whose arrays are all empty are filtered before the moved sort. The rewrite is controlled by query_plan_top_k_through_array_join and is disabled by default.


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

Version info

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

ylw510 added 5 commits August 21, 2026 13:21
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.
@ylw510
ylw510 marked this pull request as ready for review August 26, 2026 16:19
@ylw510

ylw510 commented Aug 26, 2026

Copy link
Copy Markdown
Contributor Author

@yariks5s I've made an initial attempt at this. Could you review it when you get a chance? Thanks!

@yariks5s yariks5s self-assigned this Aug 26, 2026
@yariks5s

Copy link
Copy Markdown
Member

Will try to take a look shortly, thank you for the contribution!

@yariks5s

yariks5s commented Aug 26, 2026 •

Copy link
Copy Markdown
Member

Be aware that I'm planning to intoduce several optimizations/changes for ArrayJoin (that will probably be merged before this one): #112241

@yariks5s yariks5s added the can be tested Allows running workflows for external contributors label Aug 26, 2026
@clickhouse-gh clickhouse-gh Bot closed this Aug 26, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 26, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f9738a5]

Summary: ✅


AI Review

Summary

Adds an opt-in optimization that moves bounded sorting below an eligible ARRAY JOIN, filtering empty arrays for inner joins. Reviewed head f9738a5b280f890d163f1aeec753bde9c3aa043d, including all prior discussion and the current code. Earlier findings are addressed; no new actionable findings remain. All four added stateless tests matched their reference files using the exact-head CI Fast Test binary. The performance workload completed with the optimization off and on across three rounds.

Performance & Safety

The 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 Verdict

Status: ✅ Approve. No additional changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 26, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 4, 2026
@ylw510
ylw510 force-pushed the topk-through-array-join branch from e9a718e to fbc2aa6 Compare September 13, 2026 04:27
@yariks5s

Copy link
Copy Markdown
Member

@ylw510 do you plan to keep working on this PR?

@ylw510

ylw510 commented Sep 16, 2026

Copy link
Copy Markdown
Contributor Author

@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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Comment thread src/Core/SettingsChangesHistory.cpp Resolved
Comment thread src/Core/SettingsChangesHistory.cpp Resolved
Comment thread src/Core/Settings.cpp Resolved
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.
@clickhouse-gh

clickhouse-gh Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 36 queries analysed

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
  • StressHouse run: 245dc306-debf-4f9a-a7df-9f49e29dc899
  • MIRAI run: dd2cd567-978c-470b-a68a-4c2e72b52849
  • PR check IDs:
    • clickbench_2359027_1790675062
    • clickbench_2359039_1790675062
    • clickbench_2359045_1790675062
    • tpch_adapted_1_official_2359051_1790675062
    • tpch_adapted_1_official_2359083_1790675062
    • tpch_adapted_1_official_2359097_1790675063

@ylw510

ylw510 commented Sep 24, 2026

Copy link
Copy Markdown
Contributor Author

@groeneai Help investigate the CI failures. If they are related and true, give advice on how to address them.

@groeneai

Copy link
Copy Markdown
Collaborator

I looked at the current head (9772d258). All six red checks trace back to the three new tests (Mergeable Check and PR are just the aggregators), all three failures are real and reproducible, and none of them looks like a bug in the optimization itself: they are all test-level.

1. 05019_top_k_through_array_join: the LIMIT BY case has an unspecified result.

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

LIMIT 1 BY x keeps one row out of the 2-row run each x expands into, and which one survives is not determined by the query, since the sort key ties on both rows. The invariant in the file header ("a LIMIT that is a multiple of 2 never splits an expanded run") does not cover LIMIT 1 BY, which splits the run by construction.

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 max_threads = 2, max_block_size = 47058: that query returned 19 distinct outputs in 30 runs, and the row set in your reference was one of them, once. Two signals in CI agree: the failing hunk includes the query_plan_top_k_through_array_join = 0 arm, and the runner's own diagnosis reports 142/142 failures with randomization off ("not a randomization issue"), so no tag or per-setting clamp will help here. It is build-dependent, which is why the test passes 50x each in the asan/msan/tsan/binary flaky checks and fails in all three amd_debug legs.

The fix is to assert only what the query determines, i.e. drop e from that one case:

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 x

30/30 runs gave 0, 2, 4, 6, 8 for me. That keeps what the case is for (results unchanged with LIMIT BY between the sort and the join), and the plan-level "LIMIT BY blocks the rewrite" is already asserted in 05020. It is the same rule your t_aj_ragged block already applies. A tiebreak in the inner ORDER BY would also make it deterministic, but sorting on a joined column disables the rewrite, so the case would stop testing what it was written for.

2. 05020_top_k_through_array_join_explain: the plan text depends on parallel replicas.

It fails only in Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel), 3/3 reruns, and is OK in every other leg including 200 flaky-check runs. In that leg the initiator plan gains Union and ReadFromRemoteParallelReplicas, and the rewrite is absent below it, which is your own design decision: shouldSkipTopKAboveMergeTreeInput returns true on reading->isParallelReadingFromReplicas(). So the behavior is right and only the reference does not describe that configuration.

-- Tags: no-parallel-replicas as the first line addresses it: the ParallelReplicas preset passes --no-parallel-replicas (ci/jobs/functional_tests.py), so the test is skipped there, and the tag also pins enable_parallel_replicas = 0 in the other legs (FEATURE_TAG_OVERRIDES in tests/clickhouse-test), so the randomizer cannot turn it back on. About 250 of the 1324 stateless .sql tests containing EXPLAIN carry that tag. If you would rather cover that skip than lose it, one extra case with enable_parallel_replicas = 1 asserting that Sorting stays above ArrayJoin would pin the bail-out.

3. 05021_top_k_through_array_join_rows_before_limit: same leg, pre-existing counter behavior.

All four lines report {"rows_before_limit_at_least":0} there, including the two query_plan_top_k_through_array_join = 0 arms, so the counter is not reported through a parallel-replicas read at all and this is independent of your change. -- Tags: no-parallel-replicas is what the in-tree rows_before_limit tests do for the same reason: 01913_exact_rows_before_limit_full, 03408_limit_by_rows_before_limit_mem, 03644_rows_before_aggregation_in_order, 04539_lazy_final_read_in_order_limit_disabled, 04845_distinct_limit_hint_with_ties, 04510_preferred_local_prelimit_runtime.

Optional hardening for 05020: its reference pins Parts: 1 | Granules: 1, and on builds that are not sanitizer/debug/coverage the runner randomizes index_granularity in [1, 65536] (MergeTreeSettingsRandomizer in tests/clickhouse-test), so a value below 100 would change the granule count of the 100-row table; no-random-merge-tree-settings removes that risk.

@yariks5s
yariks5s added this pull request to the merge queue Oct 27, 2026
Merged via the queue into ClickHouse:master with commit b4fae47 Oct 27, 2026
178 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 27, 2026
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 24, 2026
robot-ch-test-poll4 added a commit that referenced this pull request Nov 24, 2026
Cherry pick #116550 to 26.10: Apply `SORT + LIMIT` before `ARRAY JOIN`
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 24, 2026
yariks5s added a commit that referenced this pull request Nov 24, 2026
Includes the backport of #116550, which this change needs and which is not in 26.10 yet.
yariks5s added a commit that referenced this pull request Nov 24, 2026
Includes the backports of #116550, #128015 and #128926, which this change needs and which are not in 26.10 yet.
yariks5s added a commit that referenced this pull request Nov 24, 2026
Includes the backports of #116550 and #128015, which this change needs and which are not in 26.10 yet.
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-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants