Repository navigation
Push ORDER BY ... LIMIT n through LEFT/RIGHT joins - #104268
Conversation
Adds a query-plan-level optimization that pushes a `Sort + Limit n` onto the preserved input of a `LEFT` or `RIGHT` join when the sort key only references columns from that side. The transformation rewrites: Limit(n) <- Sort(K) <- ... <- Join(L, R) into Limit(n) <- Sort(K) <- ... <- Join(Limit(n) <- Sort(K) <- L, R) for `LEFT` joins (mirrored for `RIGHT`). The outer `Sort + Limit n` is kept because a single L row may be multiplied by the join into several output rows; the outer `LIMIT` clips them. Soundness relies on every L row producing at least one output row, which only holds for the preserved side of `LEFT` / `RIGHT` joins - the optimization is therefore restricted to those kinds. `INNER`, `FULL`, `CROSS`, `Comma`, and `Paste` joins are skipped, as are `LIMIT WITH TIES` and ambiguous columns that appear on both inputs. The pattern is recognized through a small chain of pass-through `ExpressionStep` nodes (e.g. `Before ORDER BY + Projection`, `Post Join Actions`) and works on both `JoinStepLogical` (the analyzer's first-pass plan) and `JoinStep` (post-lowering). Gated by a new setting `query_plan_top_k_through_join` (default `true`). On the Stack Overflow benchmark from https://cedardb.com/blog/ski_parquet/ the optimization produces a ~6x speedup on Q3 (multi-table self-join with `ORDER BY q.CreationDate DESC LIMIT 10`), a ~1.5x speedup on Q5, and does not fire on the rest (verified by EXPLAIN).
|
Workflow [PR], commit [f37c5e8] Summary: ✅ AI ReviewSummaryThis PR adds a first-pass Final VerdictStatus: ✅ Approve |
…sort The first revision of the optimization unconditionally inserted `Sort + Limit n` on the preserved input. When the preserved input was a single MergeTree whose primary key was a prefix of the sort description, this masked the second-pass `optimize_read_in_order` opportunity that would have streamed rows in sort-key order from storage without materializing a sort - strictly better than what this pass produces. Walk down a single-child chain looking for `ReadFromMergeTree`, compare its primary-key prefix against the sort description (using the unqualified suffix to handle analyzer-prefixed names like `__table1.Time`), and skip the optimization when they match. This restores the plan shape expected by `tests/queries/0_stateless/04024_pr_read_in_order_through_join.sql`. Q3 and Q5 of the Stack Overflow benchmark are unaffected: their `posts` and `postlinks` tables sort by other columns (`PostTypeId`/`PostId`), so the deferral check does not fire and the 6x / 1.5x speedups are preserved.
Three changes to `tryTopKThroughJoin`:
1. Declare `auto * reading` as `const auto * reading` in `findMergeTreeRead`
to satisfy `clang-tidy`'s `readability-qualified-auto` (the `arm_tidy`
build runs warnings as errors).
2. Reject `LimitStep`s with `alwaysReadTillEnd` set. When `WITH TOTALS` or
`exact_rows_before_limit` requires reading past the limit, truncating the
preserved-side input would understate the totals and the
`rows_before_limit_at_least` count.
3. Reject `JoinStrictness::Semi` and `JoinStrictness::Anti`. The soundness
sketch relies on every preserved-side row producing at least one output
row, but `LEFT SEMI` drops unmatched rows and `LEFT ANTI` drops matched
ones (mirrored for `RIGHT`). Pushing `Sort + Limit n` onto the preserved
side could discard rows that actually survive the join, changing the
top-n result.
`tests/queries/0_stateless/04208_top_k_through_join_safety.{sql,reference}`
covers the new guards: `LEFT/RIGHT SEMI/ANTI` correctness checks and
`EXPLAIN`-based assertions that no inner `Sort + Limit` is grafted onto
the preserved side for `LEFT SEMI` or for `LIMIT WITH TOTALS`.
Addresses the AI review on PR #104268.
… steps The EXPLAIN assertion in `04207_top_k_through_join.sql` failed across 9 stateless test variants on `d3d4f1db` because optional plan steps (`BuildRuntimeFilter`, `JoinLazyColumnsStep`, `LazilyReadFromMergeTree`) appeared non-deterministically inside the join's input subtree, depending on the data shape and runtime heuristics. The numeric correctness rows were always right; only the plan-shape rows diverged. Disable those optional optimizations on the two `EXPLAIN` queries so the plan structure exercised by the assertion is determined solely by `query_plan_top_k_through_join` itself. Other queries in the test (the correctness checks) continue to run with full optimizations on. Failed CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104268&sha=d3d4f1dbb4e87d033f3edffad9edd35d62865c5f&name_0=PR PR: #104268 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…wing `tryTopKThroughJoin` peels through `ExpressionStep`s between Sort and Join, allowing the optimization to fire when the sort key column is preserved unchanged by each step. The previous check only verified the sort column name was present in the expression's input header, which admits a soundness hole: an output named like an input column can still be a freshly computed expression. Concretely, in ```sql SELECT l.id, l.k + r.bonus AS k FROM l LEFT JOIN r ON r.id = l.id ORDER BY k DESC LIMIT 1 ``` the sort key `k` is the function `l.k + r.bonus`, but the join's input header also exposes `l.k` (sometimes under the same name `k`), so the header-presence check passes and the optimization would push `Sort + Limit` onto the left input using `l.k` alone - silently producing a wrong top-1. Replace the header-name check with an `ActionsDAG`-level walk: for each sort column we look up the output node by name and follow `ALIAS` chains; the column passes through only if the chain ends at an `INPUT` node. The sort column name is then rewritten to the input's name and the check is repeated at each peeled `ExpressionStep`. After all peeling the new description is what we install on the `SortingStep` we graft in front of the preserved input - it now references the names visible at the join's input level, not the post-join names. `04208_top_k_through_join_safety.sql` gets a regression case for the alias-shadowing example above (correctness assertion). Existing tests continue to pass. PR: #104268 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ttings The CI stateless-test runner randomizes `query_plan_join_swap_table` and `query_plan_max_limit_for_top_k_optimization`, both of which change the shape of the EXPLAIN plan: * `query_plan_join_swap_table` (auto / true / false) decides whether to swap join inputs - with swap, the optimization moves `Limit + Sorting` onto what is now the right (build) side; without swap, it stays on the left. * `query_plan_max_limit_for_top_k_optimization` caps the `LIMIT n` value for which the TopK family of optimizations fires. When randomized to `1`, our `LIMIT 10` exceeds the cap and the optimization correctly declines, but the EXPLAIN reference assumed it would fire. Also pin `query_plan_read_in_order_through_join = false` defensively; the deferral inside `topKThroughJoin` does not engage for this test (sort key `k` is not the storage primary key `id`), but disabling the pass keeps the plan stable against future changes there. Reference updated to the unswapped form. Reference: #104268
`tryTopKThroughJoin` defers to `optimizeReadInOrder` when the preserved input can stream sort-key rows from MergeTree's primary key. The check previously gated only on `query_plan_read_in_order` - but the second-pass through-join read-in-order optimization itself only runs when `query_plan_read_in_order_through_join` is also enabled. With the former on and the latter off, `topKThroughJoin` would defer, the second pass would refuse to apply, and the query would lose both optimizations. Plumb `read_in_order_through_join` into `Optimization::ExtraSettings` and require both flags to be set before deferring. Adds `04209_top_k_through_join_read_in_order_gate` covering both flag states (sort key matches storage primary key, deferral path) plus result-equivalence across the two configurations. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…_top_k_through_join_read_in_order_gate` The first `EXPLAIN` query checks that when `query_plan_read_in_order` and `query_plan_read_in_order_through_join` are both on, `topKThroughJoin` defers to the second-pass through-join read-in-order optimization, leaving only the outer Sort + Limit in the plan. The deferral inside `topKThroughJoin` actually keys on `optimize_read_in_order && query_plan_read_in_order` (the same flag that gates the second-pass optimization itself, so the deferral is sound) and on the preserved input's plan tree containing a `ReadFromMergeTree` step. The stateless-test runner randomizes both `optimize_read_in_order` and `enable_parallel_replicas`; with `optimize_read_in_order = 0` the deferral gate is closed and the optimization fires, yielding `2 2` instead of `1 1` in the EXPLAIN counters, and with parallel replicas on the preserved-side read step is no longer a plain `ReadFromMergeTree` so the deferral cannot locate the storage step. Pin both settings in the `EXPLAIN` queries so the test exercises the deferral path deterministically. Also pin `optimize_read_in_order = 1` in the `through_join_off` query for parity, even though that branch's expected `2 2` result does not depend on the first-pass deferral. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104268&sha=47500a29aacc2d75d242be696d8d9e53b0b62189&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20targeted%29 PR: #104268 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
… strictness
`topKThroughJoin` deferred to `optimizeReadInOrder` whenever both flags
were on and the preserved input chained down to a `ReadFromMergeTree`,
but the second-pass optimization is narrower than that. In
`optimizeReadInOrder` the join-traversal branch only applies to
`INNER`/`LEFT` joins with `ANY`/`ALL` strictness, via the left child:
```
if ((strictness == JoinStrictness::Any || strictness == JoinStrictness::All)
&& isInnerOrLeft(kind) && !join_ptr->hasDelayedBlocks())
```
For a `RIGHT` join (or `LEFT ASOF`/etc.) the second pass never propagates
read-in-order through the join, so deferring here meant both
optimizations were silently skipped and the query lost both ways.
Tighten the deferral check to require `LEFT` kind and `ANY`/`ALL`
strictness in addition to the existing flag/storage conditions. `INNER`
is already excluded earlier in the function. Add a regression test
`04210_top_k_through_join_right_join_deferral` that EXPLAINs a `RIGHT
JOIN` whose sort key is the right table's primary key and asserts that
the inner Sort + Limit pair is still inserted.
Reviewer comment: #104268
PR: #104268
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Under the `Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel)` job, `enable_parallel_replicas` is on by default. That wraps the local plan in a `Union` over a `ReadFromRemoteParallelReplicas` step, which: * changes the EXPLAIN structure in `04207_top_k_through_join` (extra `Union` + `ReadFromRemoteParallelReplicas` after the local plan), and * inflates the `Sorting`/`Limit` count from 1 to 2 in `04208_top_k_through_join_safety` (`left_semi_plan_sort_count`). In `04209_top_k_through_join_read_in_order_gate` and `04210_top_k_through_join_right_join_deferral`, the result-equivalence `SELECT`s use `ORDER BY ... DESC LIMIT 10` over a table whose primary key matches the sort key. Read-in-order engages in `ReverseOrder` direction, and under parallel replicas the coordinator can receive announcements with mismatched modes, raising `Coordination mode mismatch for stream ...: got ReverseOrder, expected Default` from `ParallelReplicasReadingCoordinator::getOrCreateCoordinator`. These tests verify plan-level behavior and result equivalence, not distributed execution, so pinning `enable_parallel_replicas = 0` on the affected queries is the correct fix. CI report: #104268 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Also, please introduce a performance test (tests/performance), highlighting this optimization. |
Highlights the `query_plan_top_k_through_join` optimization with three queries over 5M-row `MergeTree` tables: a single `LEFT JOIN`, a 4-table `LEFT JOIN` chain (mirroring the Stack Overflow Q3 pattern), and an `INNER JOIN` control. Sort key (`sipHash64(id)`) is uncorrelated with the storage primary key (`id`) so `read_in_order` cannot satisfy the `ORDER BY` directly - this is the regime the optimization targets. Local timings (`clickhouse-local`, ARM, warm cache): - Single `LEFT JOIN`: ~115 ms -> ~47 ms (2.4x) - 4-table chain: ~197 ms -> ~154 ms (1.3x) - `INNER JOIN` control: unchanged (optimization correctly does not fire)
Address review on PR #104268: `wouldReadInOrderBeUseful` matches the storage sorting key against the requested sort description but is unaware of FINAL-time gating in `ReadFromMergeTree::requestReadingInOrder`, which rejects `direction != 1 && query_info.isFinal()`. Without the FINAL+descending gate, the deferral would fire on the name match, the second pass would still reject the read, and both optimizations would silently disable for queries like `... FROM t FINAL LEFT JOIN r ... ORDER BY t.k DESC LIMIT 10`. Skip the deferral when `reading->isQueryWithFinal()` and any sort column is descending. Conservative: may forgo deferral in the rare reverse-storage-key case where pass 2 would have succeeded with direction 1, but never silently disables both passes. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
@groeneai, the failure of Issue #89042 was closed but the flakiness is clearly still present. Could you investigate and provide a fix in a separate PR? If a fix is already in progress, please link it here. |
LLVM Coverage Report
Changed lines: 92.90% (170/183) · Uncovered code |
|
@groeneai, the failure of The test exception is Tracked in #103819 (open). Please investigate and provide a fix in a separate PR. If a fix is already in progress, link it here. |
alexey-milovidov
left a comment
There was a problem hiding this comment.
The code LGTM.
|
@alexey-milovidov thanks for flagging. Quick summary of where things stand on
Follow-up fix in #105112 bumps the default Separately, there is one unrelated master failure on |
The `_wait_for_pause_effective` probe added in ClickHouse#104167 polls a sibling ClickHouse instance with a tight `remote(...)` query until the freeze of the target container blocks fresh handshakes. The 30-second default was sufficient on debug and release builds but not on the slowest CI jobs: - `Integration tests (amd_msan, 1/6)` — 2026-05-13 master run - `Integration tests (amd_asan_ubsan, db disk, old analyzer, 1/6)` — 2026-05-12 master run both produced `pause_container('node1') did not become observably effective within 30.0s`. Under MSan/ASan+UBSan instrumentation each probe iteration (subprocess spawn, sibling-node query, handshake failure path) takes a few seconds, so only a handful of probes fit in a 30-second budget; meanwhile the Docker cgroup freezer + kernel TCP race window is itself wider when the whole node graph is sanitizer-slow. Bump the default `wait_timeout` in `ClickHouseCluster.pause_container` and `pause_container_using_signal` from 30s to 90s. This is a 3x budget, keeps the probe useful when something is genuinely wrong with the pause, and matches the empirical worst case observed on those CI shards. No caller in `tests/integration/` overrides `wait_timeout`, so this is the only place the value needs to change. Tracked in ClickHouse#103819. Surfaced on PR ClickHouse#104268 by @alexey-milovidov.
|
The performance test added in this PR is flaky, with over 40% of the time saying it's faster/slower with the same binary -> #100759 |
`LimitTransform::makeChunkWithPreviousRow` asserts `row < chunk.getNumRows()` and is called from `preparePair` with `data.current_chunk.getNumRows() - 1` whenever `with_ties && rows_read == offset + limit`. This silently assumes the current chunk has at least one row. The read-in-order pipeline violates that assumption. With settings `optimize_read_in_order = 1`, `read_in_order_use_virtual_row = 1` and `read_in_order_use_virtual_row_per_block = 1`, `VirtualRowTransform` emits zero-row chunks carrying `MergeTreeReadInfo` as sort-key markers for `MergingSortedTransform`. In the single-stream case there is no merging, so `RemoveVirtualRowTransform` is inserted to clean up — but it only stripped the `ChunkInfo` and left the empty chunk on the pipeline. When such a chunk arrived at `LimitTransform` after the previous data chunk had pushed `rows_read` to exactly `offset + limit`, the call became `makeChunkWithPreviousRow(empty_chunk, 0 - 1)` and the `UInt64` underflow tripped the assertion (server abort in debug builds; surfaces as a `LOGICAL_ERROR` in release builds). The AST fuzzer hit this on master across multiple unrelated PRs (#99495, #104268, #101158) over the past 30 days. Minimal reproducer: CREATE TABLE t (id UInt64, m Map(String, String), INDEX idx_mk mapKeys(m) TYPE bloom_filter GRANULARITY 1) ENGINE = MergeTree ORDER BY id SETTINGS index_granularity = 1; INSERT INTO t VALUES (1, {'1':'1'}); INSERT INTO t VALUES (2, {'2':'2'}); INSERT INTO t VALUES (3, {'3':'3'}); SELECT id FROM t PREWHERE mapContains(m, toFixedString('1', 1)) ORDER BY id ASC LIMIT 1 WITH TIES SETTINGS optimize_read_in_order = 1, read_in_order_use_virtual_row = 1, read_in_order_use_virtual_row_per_block = 1; Two fixes: 1. `LimitTransform.cpp`: skip the `makeChunkWithPreviousRow` call when the current chunk has zero rows. There is no row to remember and the `previous_row_chunk` saved from the prior non-empty chunk is still the correct tie key for the boundary. 2. `RemoveVirtualRowTransform` (`SortingStep.cpp`): actually consume the virtual-row chunk — `chunk.clear()` it and enable `skip_empty_chunks` on the base `ISimpleTransform` so it is not re-emitted. This matches the existing comment ("we need to remove virtual row before output") and protects other downstream transforms from receiving these pointless markers. Regression test `04247_99495_limit_with_ties_virtual_row_empty_chunk` aborts master in debug builds and passes after this change. CI report: https://s3.amazonaws.com/clickhouse-test-reports/PRs/99495/b699481fd40feb67d515e47725de159f20dd1ff0/ast_fuzzer_amd_debug/ Related: #99495 (sighting PR)
…d a constant predicate A constant-true predicate (AND 1) combined with a LEFT JOIN, ORDER BY and LIMIT used to throw NOT_FOUND_COLUMN_IN_BLOCK: the optimizer looked for the whole merged filter expression as a materialized input column instead of evaluating it. Regression from ClickHouse#104268, fixed on master. This test locks the fix in, pinning the three default-on optimizations that must all be enabled to trigger the defect. Closes: ClickHouse#111452 Co-Authored-By: Claude Opus 4.8 <[email protected]>
…d a constant predicate A constant-true predicate (AND 1) combined with a LEFT JOIN, ORDER BY and LIMIT used to throw NOT_FOUND_COLUMN_IN_BLOCK: the optimizer looked for the whole merged filter expression as a materialized input column instead of evaluating it. Regression from ClickHouse#104268, fixed on master. This test locks the fix in, pinning the three default-on optimizations that must all be enabled to trigger the defect. Closes: ClickHouse#111452 Co-Authored-By: Claude Opus 4.8 <[email protected]>
`LimitTransform::makeChunkWithPreviousRow` asserts `row < chunk.getNumRows()` and is called from `preparePair` with `data.current_chunk.getNumRows() - 1` whenever `with_ties && rows_read == offset + limit`. This silently assumes the current chunk has at least one row. The read-in-order pipeline violates that assumption. With settings `optimize_read_in_order = 1`, `read_in_order_use_virtual_row = 1` and `read_in_order_use_virtual_row_per_block = 1`, `VirtualRowTransform` emits zero-row chunks carrying `MergeTreeReadInfo` as sort-key markers for `MergingSortedTransform`. In the single-stream case there is no merging, so `RemoveVirtualRowTransform` is inserted to clean up — but it only stripped the `ChunkInfo` and left the empty chunk on the pipeline. When such a chunk arrived at `LimitTransform` after the previous data chunk had pushed `rows_read` to exactly `offset + limit`, the call became `makeChunkWithPreviousRow(empty_chunk, 0 - 1)` and the `UInt64` underflow tripped the assertion (server abort in debug builds; surfaces as a `LOGICAL_ERROR` in release builds). The AST fuzzer hit this on master across multiple unrelated PRs (ClickHouse#99495, ClickHouse#104268, ClickHouse#101158) over the past 30 days. Minimal reproducer: CREATE TABLE t (id UInt64, m Map(String, String), INDEX idx_mk mapKeys(m) TYPE bloom_filter GRANULARITY 1) ENGINE = MergeTree ORDER BY id SETTINGS index_granularity = 1; INSERT INTO t VALUES (1, {'1':'1'}); INSERT INTO t VALUES (2, {'2':'2'}); INSERT INTO t VALUES (3, {'3':'3'}); SELECT id FROM t PREWHERE mapContains(m, toFixedString('1', 1)) ORDER BY id ASC LIMIT 1 WITH TIES SETTINGS optimize_read_in_order = 1, read_in_order_use_virtual_row = 1, read_in_order_use_virtual_row_per_block = 1; Two fixes: 1. `LimitTransform.cpp`: skip the `makeChunkWithPreviousRow` call when the current chunk has zero rows. There is no row to remember and the `previous_row_chunk` saved from the prior non-empty chunk is still the correct tie key for the boundary. 2. `RemoveVirtualRowTransform` (`SortingStep.cpp`): actually consume the virtual-row chunk — `chunk.clear()` it and enable `skip_empty_chunks` on the base `ISimpleTransform` so it is not re-emitted. This matches the existing comment ("we need to remove virtual row before output") and protects other downstream transforms from receiving these pointless markers. Regression test `04247_99495_limit_with_ties_virtual_row_empty_chunk` aborts master in debug builds and passes after this change. CI report: https://s3.amazonaws.com/clickhouse-test-reports/PRs/99495/b699481fd40feb67d515e47725de159f20dd1ff0/ast_fuzzer_amd_debug/ Related: ClickHouse#99495 (sighting PR)
A query-plan-level optimization that pushes
Sort + Limit nonto the preserved input of aLEFTorRIGHTjoin when the sort key only references columns from that side. Triggered by analysis of the Stack Overflow benchmark queries from https://cedardb.com/blog/ski_parquet/, whereORDER BY t.col DESC LIMIT 10over a join chain was a major remaining gap vs CedarDB.The transformation rewrites:
into
for
LEFTjoins (mirrored forRIGHT). The outerSort + Limit nis preserved because a single L row may be multiplied into several output rows; the outerLIMITclips them. Soundness relies on every L row producing at least one output row, which only holds for the preserved side - soINNER,FULL,CROSS,Comma, andPastejoins are skipped, as areLIMIT WITH TIESand ambiguous columns appearing on both inputs.The pattern is recognized through a small chain of pass-through
ExpressionStepnodes (e.g.Before ORDER BY + Projection,Post Join Actions) and works on bothJoinStepLogicalandJoinStep.Gated by a new setting
query_plan_top_k_through_join(defaulttrue).Measured on Stack Overflow (Posts/Users/Badges, 96 threads, warm cache):
ORDER BY q.CreationDate DESC LIMIT 10): 1958 ms -> 315 ms (6.2x)postlinkschain): 500 ms -> 325 ms (1.5x)Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Push
ORDER BY ... LIMIT nthroughLEFT/RIGHTjoins when the sort key only references columns from the side preserved by the join, restricting how many rows the preserved-side input must produce before joining. Controlled by the new settingquery_plan_top_k_through_join(default enabled).Documentation entry for user-facing changes
Version info
26.5.1.651