Repository navigation
Extend reading in reverse order with FINAL to Merge tables and topKThroughJoin - #118008
Conversation
…roughJoin `ReadFromMergeTree` gets `canReadInReverseOrder`, which holds the check that `requestReadingInOrder` did inline: without `FINAL` a reverse read is always accepted, with `FINAL` only for `ReplacingMergeTree` when `optimize_read_in_reverse_order_final` is enabled. `ReadFromMerge::requestReadingInOrder` rejected every reverse order request with `FINAL`. It now asks the reading steps of all children with `canReadInReverseOrder` before switching any of them, and passes the request on when all of them accept it. `topKThroughJoin` deferred to the read-in-order optimization through the join only when all sort columns were ascending with `FINAL`. It now gets the input order the second pass would request from `getInputOrderIfReadInOrderIsUseful` (renamed from `wouldReadInOrderBeUseful`) and defers exactly when the second pass accepts that direction, which also handles descending sorting keys. Closes: #117961 Related: #115345 Related: #111609 Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
Workflow [PR], commit [f422ec5] Summary: ✅
AI ReviewSummaryThis PR extends reverse-order read-in-order support for Final Verdict
LLVM Coverage ReportMeasured on commit f422ec5.
Changed lines: Changed C/C++ lines covered: 139/147 (94.56%) · Uncovered code |
Build profile diff (arm_release)Commit See the job log for details. |
|
📊 Cloud Performance Report ✅ AI verdict: This PR changes when topKThroughJoin defers to read-in-order, adds reverse-order FINAL reads through Merge tables, and moves the existing ReplacingMergeTree reverse-read check into a canReadInReverseOrder() helper without changing what it does. None of the four flagged ClickBench queries (Q18, Q28, Q33, Q34) use a JOIN, FINAL or a Merge table, so the changed code does not run for them. All four stay not_sure: the +7% to +11% slowdowns are either inside master's normal range (Q18, Q28) or borderline with the two tests disagreeing (Q33, Q34). They share a similar 4-6% CPU rise, which points to the run environment rather than this diff, and the envelope-based suppressions match what the diff touches. clickbenchFlagged queries (4 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
…bles The AI review pointed out that the structured docs still said reverse-order reading with `FINAL` works only for `ReplacingMergeTree`. Update the `optimize_read_in_reverse_order_final` doc string in `src/Core/Settings.cpp` and the `ORDER BY` optimization text in `src/Parsers/ParserSelectQuery.cpp`, which is the source of truth for the autogenerated `order-by.mdx`, to also mention `Merge` tables over such children. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…equests Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
🕵 Updated to
The only red, |
…gh a `Merge` table `topKThroughJoin` deferred to the second pass of the read-in-order optimization only when the preserved side of the join was a `ReadFromMergeTree`, so with the default `query_plan_top_k_through_join = 1` a `Merge` table with `FINAL` behind a `LEFT JOIN` still got an inner `Sort + Limit` although the second pass can now read its children in reverse order through the join. - `ReadFromMerge::canReadInReverseOrder` holds the check of the children that `requestReadingInOrder` did inline. - `getInputOrderIfReadInOrderIsUseful` gets an overload for `ReadFromMerge` that matches every selected child table the same way the second pass does (`buildInputOrderFromSortDescription` for `Merge`). - `topKThroughJoin` probes a `ReadFromMerge` on the preserved side with them and defers exactly when the second pass would accept the request; with parallel replicas the `Merge` read is expanded later, so the explicit `Sort + Limit` is kept there. `05193_top_k_through_join_final_reverse_order` now expects no inner sort for the `Merge` table with `topKThroughJoin` enabled. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
🕵 Updated to
|
…Useful` in `WhatIfProjectionEstimator` A new caller of `wouldReadInOrderBeUseful`, which this PR renamed, came from master. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…allel replicas may expand it The probe was skipped whenever the session could use parallel replicas, but only the plan-based parallel replicas expand a `Merge` read, and only when `parallel_replicas_allow_merge_tables = 1` and the read is not `FINAL`. In the other cases the second pass still sees the `ReadFromMerge`, so `topKThroughJoin` now defers there as well (`ReadFromMerge::mayBeExpandedForParallelReplicas`). Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
🕵 Updated to
|
alexey-milovidov
left a comment
There was a problem hiding this comment.
Good implementation, I like it.
…-topk # Conflicts: # tests/queries/0_stateless/04234_top_k_through_join_final_desc_gate.sql
…k_through_join_final_reverse_order` Master made `query_plan_read_in_order` obsolete; the plan optimization is now gated by `optimize_read_in_order` alone, which the test already sets. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… real expandability verdict `ReadFromMerge::mayBeExpandedForParallelReplicas` judged by the settings and `FINAL` alone, but `expandMergeReadsForParallelReplicas` also requires every child to be a plain `ReadFromMergeTree` without a set-building root that `mergeTreeReadCanBeShipped` accepts. When it refuses (for example, non-replicated children with the default `parallel_replicas_for_non_replicated_merge_tree = 0`), the `ReadFromMerge` stays in the plan and the second pass can read it in order, but `topKThroughJoin` still injected the avoidable inner `Sort + Limit`. The gate now asks the same question as `getExpandableReads`, with the same `mergeTreeReadCanBeShipped` predicate (no longer `static`). The answer is computed by the new uncached `computeExpandableReads`, because the first pass can run before the child plans get their last pushed-down filters, and the cached answer that `applyParallelReplicas` relies on must not be pinned by this earlier probe. `05193` covers the non-shippable case. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Updated to
Local: |
|
Acknowledged. No fix is in progress for this one. What I measured so far: |
|
The fix is in #123755. The slow binaries run the same instructions as the fast ones but miss the uop cache about 80x more often, mostly in the per-document allocation and freeing of rapidjson's two parse stacks (14-19% of the query's cycles). The PR serves those stacks from a 2 KB buffer inside the parser, which makes |
|
🕵 Merged @groeneai, thanks for tracking the The failures on the previous commit
@groeneai, investigate the |
|
All three already have a fixing PR:
|
…`optimizeReadInOrder` does `topKThroughJoin` deferred to the second-pass read-in-order when an arbitrary single-child chain below the join led to a `ReadFromMergeTree` or `ReadFromMerge`. But `optimizeReadInOrder`'s `findReadingStep` descends only through expressions, filters, preliminary `DISTINCT`, set-building steps and suitable joins, so for a preserved side such as `(SELECT DISTINCT k, src FROM t_merge FINAL)` the deferral fired, the second pass stopped at the final `DistinctStep`, and neither optimization applied. Export `findReadingStepForReadInOrder`, a wrapper over `findReadingStep`, and use it for the deferral probe, so both passes agree on whether the read is reachable. Add plan and result checks for a `DISTINCT` subquery on the preserved side. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118008&sha=392eaf5e8599cfd7c69b1213835c94a7f5a719a3&name_0=PR&name_1=Performance%20Comparison%20%28amd_release%2C%20master_head%2C%203%2F6%29 ( |
|
This is the same slowdown as The fix in progress is #107554, which replaces this |
…ughJoin` probe `topKThroughJoin` looks for the preserved-side read and probes a `ReadFromMerge` in the first optimization pass. Both create the child plans (`filterTablesAndCreateChildrenPlans`), and they are created only once, before the second pass applies the filters to the read (`applyFilters`). So `getSelectedTables` could not use a filter on `_database` or `_table`, and the children read tables which the filter excludes. Drop the child plans which the probe created, so that they are created again when needed. Child plans that already existed are kept: under `make_distributed_plan`, the children carry their own verdict on distribution, which recreating them would lose. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
I opened #124340, the smaller change offered above: integer keys are compared inline in the |
Closes: #117961
Related: #115345
Related: #111609
#115345 enabled the read-in-order optimization for
FINALqueries that sort in reverse order of the sorting key onReplacingMergeTreetables, and left two places out: theMergeengine and thetopKThroughJoinoptimization. This change covers both.ReadFromMergeTreegetscanReadInReverseOrder, which holds the check thatrequestReadingInOrderused inline: withoutFINALa reverse read is always accepted, withFINALonly forReplacingMergeTreewithoptimize_read_in_reverse_order_finalenabled.ReadFromMerge::requestReadingInOrderrejected every reverse order request withFINAL, soSELECT ... FROM merge_table FINAL ORDER BY key DESC LIMIT nread all the data of the children. It now asks every child reading step withcanReadInReverseOrderand passes the request on when all of them accept it. The children are asked before any of them is switched to reading in order, so a rejected request leaves the child plans untouched. AMergetable with a child that cannot read in reverse order withFINAL(for example, aCollapsingMergeTree) keeps the previous plan.topKThroughJoindecides whether to inject its ownSort + Limiton the preserved side of aLEFT JOIN, or to defer to the read-in-order optimization through the join. ForFINALit deferred only when all columns of the sort description were ascending, because the second pass rejected every reverse read withFINAL. It now gets the input order that the second pass would request fromgetInputOrderIfReadInOrderIsUseful(renamed fromwouldReadInOrderBeUseful, which returned only a flag) and defers exactly when the second pass accepts that direction: a reverse direction is accepted whencanReadInReverseOrderholds. The direction is the one computed for the storage's sorting key, so a descending sorting key read by an ascending sort description is a reverse read, and by a descending one a direct read, which the previous column-based heuristic got wrong in both directions. The same deferral now also applies to aMergetable on the preserved side:ReadFromMerge::canReadInReverseOrderholds the check of the children, and aReadFromMergeoverload ofgetInputOrderIfReadInOrderIsUsefulmatches every selected child table the way the second pass does, soMerge ... FINAL LEFT JOIN ... ORDER BY key DESC LIMIT nreads the children in reverse order through the join without an innerSort + Limit. With parallel replicas, where theMergeread is expanded into its tables later, the explicitSort + Limitis kept.Tests:
05192_read_in_reverse_order_final_merge_tablecovers aMergetable overReplacingMergeTreechildren (level-0 duplicates, duplicates across parts, overlapping children with several parts and granules, a descending sorting key, the setting disabled, and a child engine that cannot read in reverse order).05193_top_k_through_join_final_reverse_ordercovers the deferral decision oftopKThroughJoinforReplacingMergeTreewith the setting on and off,AggregatingMergeTree, a descending sorting key, and aMergetable behind the join, and compares the rows with a plain read.04234_top_k_through_join_final_desc_gatedisablesoptimize_read_in_reverse_order_finalto keep testing the case it was written for.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Queries with
FINALthat sort in reverse order of the sorting key, such asSELECT ... FROM t FINAL ORDER BY key DESC LIMIT n, now read in order also throughMergetables overReplacingMergeTreetables, and thetopKThroughJoinoptimization defers to reading in reverse order below aLEFT JOINwhen the table supports it. This extends #115345.Measured locally (release build,
Mergeover twoReplacingMergeTreetables of 20M rows each,SELECT k, v FROM m FINAL ORDER BY k DESC LIMIT 10):optimize_read_in_reverse_order_finalThe
LEFT JOINshape oftopKThroughJoin(SELECT a.k, r.v FROM a FINAL LEFT JOIN r ON a.k = r.k ORDER BY a.k DESC LIMIT 10,aaReplacingMergeTreeof 20M rows):optimize_read_in_reverse_order_finalWorkflow [PR]
Sync PR [sync-upstream/pr/118008]
Version info
26.10.1.1718-master(included in26.10and later)