Skip to content

Enable reading in reverse order with FINAL for ReplacingMergeTree - #111609

Closed
cwurm wants to merge 14 commits into
ClickHouse:masterfrom
cwurm:final-reverse-read-in-order
Closed

cwurm wants to merge 14 commits into
ClickHouse:masterfrom
cwurm:final-reverse-read-in-order

Conversation

@cwurm

@cwurm cwurm commented Jul 23, 2026

Copy link
Copy Markdown
Member

Closes: #58035
Related: #58361

Second attempt at #58361, this time scoped to ReplacingMergeTree only.

When a query with FINAL sorts in reverse order of the sorting key (e.g. ORDER BY key DESC LIMIT n), the read-in-order optimization now applies instead of falling back to a full read.

ReplacingSortedAlgorithm learns a read_in_reverse mode: a row with a strictly higher version always replaces the selected one; among rows with equal (or absent) versions, the previously selected row is kept unless the current row comes from a newer data part. This mirrors the "last written row wins" rule of the direct reading order, because in the reverse reading order rows within one part arrive backwards while parts still arrive from the oldest to the newest one. This addresses the correctness concern that stopped the first attempt (#58361 (comment)): duplicate keys inside a single level-0 part now select the same row in both reading directions.

The other engines keep the old behavior (no reverse reading with FINAL), since their merging algorithms rely on the direct order of rows: the sequence of sign rows in CollapsingMergeTree, the order of rows fed to order-dependent aggregate functions in AggregatingMergeTree, etc.

On a 110M-row ReplacingMergeTree table (two overlapping parts), SELECT x FROM t FINAL ORDER BY x DESC LIMIT 1:

optimization on optimization off
Rows read 1.71 million 110.1 million
Wall time 0.22 s 4.5 s
Peak memory 23 MB 41 MB

Trade-offs: like the already-existing direct-order in-order reads with FINAL, an in-order plan disables vertical FINAL and the splitting of parts ranges into intersecting and non-intersecting ones (the plain parallel read of non-intersecting ranges does not produce key-sorted streams). A full-result ORDER BY key DESC query without a small LIMIT on a wide or mostly-merged table may therefore regress; the new setting optimize_read_in_reverse_order_final (default true) allows disabling the optimization, and compatibility with versions before 26.7 restores the previous plans.

Changelog category (leave one):

  • Performance Improvement

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

Enable the read-in-order optimization for queries with FINAL that sort in reverse order of the sorting key on ReplacingMergeTree tables. This makes queries such as SELECT ... FROM t FINAL ORDER BY key DESC LIMIT n read only the relevant tail of the data instead of the whole table. Can be disabled with the new setting optimize_read_in_reverse_order_final.

Second attempt at ClickHouse#58361,
scoped to ReplacingMergeTree only. Addresses
ClickHouse#58035.

When a query with FINAL sorts in reverse order of the sorting key
(e.g. ORDER BY key DESC LIMIT n), the read-in-order optimization now
applies instead of falling back to a full read.

ReplacingSortedAlgorithm learns a read_in_reverse mode: a row with a
strictly higher version always replaces the selected one; among rows
with equal (or absent) versions, the previously selected row is kept
unless the current row comes from a newer data part. This mirrors the
"last written row wins" rule of the direct reading order, because in
the reverse reading order rows within one part arrive backwards while
parts still arrive from the oldest to the newest one.

The other engines keep the old behavior (no reverse reading with
FINAL), since their merging algorithms rely on the direct order of
rows: the sequence of sign rows in CollapsingMergeTree, the order of
rows fed to order-dependent aggregate functions in
AggregatingMergeTree, etc.

The new setting optimize_read_in_reverse_order_final (default true)
allows disabling the optimization.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [459fe78]

Summary: ❌

job_name test_name status info comment
Stress test (arm_asan_ubsan, s3) FAIL
Sanitizer (STID: 2064-2dbf) FAIL cidb

AI Review

Summary

This PR enables reverse-order read-in-order for FINAL queries on ReplacingMergeTree, threads that support through the ReplacingSortedAlgorithm, ReadFromMergeTree, StorageMerge, and the topKThroughJoin gate, and adds focused stateless/performance coverage. I found one material regression in the new topKThroughJoin deferral logic: under make_distributed_plan, the reverse-FINAL JOIN ... ORDER BY ... LIMIT shape can now lose both topKThroughJoin and pass-2 read-in-order, so I would not merge as-is.

Findings

⚠️ Majors

  • [src/Processors/QueryPlan/Optimizations/topKThroughJoin.cpp:434] The new reverse-FINAL deferral assumes pass 2 will still be able to reach the preserved-side ReadFromMergeTree, but make_distributed_plan rewrites the read before optimizeReadInOrder runs. tryMakeDistributedRead inserts a GatherExchange, findReadingStep does not descend through exchanges, and the second pass therefore never installs requestReadingInOrder. Before this PR, descending FINAL never deferred here, so the query still kept topKThroughJoin's inner Sort + Limit; after it, ... FINAL LEFT JOIN ... ORDER BY key DESC LIMIT n SETTINGS make_distributed_plan = 1 loses both optimizations.
    Suggested fix: disable this deferral when make_distributed_plan is enabled, or preserve the through-join read-in-order contract across the distributed-read rewrite.
Missing context / blind spots
  • ⚠️ I did not execute the new stateless tests locally because this checkout has no prebuilt clickhouse binary or build directory; the review is based on the final diff, surrounding code, and the full GitHub thread history.
Final Verdict

⚠️ Needs changes before merge.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.60% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.90% +0.10%

Changed lines: Changed C/C++ lines covered: 180/185 (97.30%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jul 23, 2026
cwurm and others added 3 commits July 30, 2026 13:35
…lacingMergeTree

ReadFromMerge::requestReadingInOrder kept the old blanket guard against
reverse order with FINAL, so a Merge table over ReplacingMergeTree
children could not use the optimization. Replace the guard with a
precise upfront check that every selected child table is a
ReplacingMergeTree: the check must happen before delegating to the
children, because the delegation loop switches the children to in-order
reading one by one, and a child must not be left switched when a later
child rejects the request.

Addresses the review comment
ClickHouse#111609 (comment).

Co-Authored-By: Claude Fable 5 <[email protected]>
…y block

The 26.8 release cycle started on master, and the style check requires
new settings to be recorded under the current version block.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Storages/StorageMerge.cpp Resolved
A nested Merge table does not receive the read-in-order optimization in
any direction, because recursivelyApplyToReadingSteps does not descend
into the child plans of a nested ReadFromMerge (they are not plan-node
children). The query falls back to the unoptimized plan and stays
correct. Pin this behavior with a test.

Related to the review comment
ClickHouse#111609 (comment).

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 150/153 (98.04%) · Uncovered code

Full report · Diff report

cwurm and others added 3 commits August 4, 2026 13:43
topKThroughJoin chooses between itself and the second-pass read-in-order
through the join, and blocked the deferral for every descending FINAL
sort, because requestReadingInOrder used to reject a reverse direction
with FINAL unconditionally. A query like
`... FROM replacing FINAL LEFT JOIN ... ORDER BY key DESC LIMIT n`
therefore kept the injected Sort + Limit over a full read instead of
reading in reverse order.

Extract the engine and setting check into
ReadFromMergeTree::canReadInReverseOrderWithFinal so that both
requestReadingInOrder and topKThroughJoin use one source of truth, and
relax the guard accordingly. The conservative any_desc heuristic stays
in place for the engines that do not support reading in reverse order.

The test compares the rows selected by FINAL behind a join against a
read with both optimizations disabled, for duplicates within a level-0
part, duplicates across parts, version ties, is_deleted, and descending
sorting keys, so that a reverse read cannot silently pick another row of
a duplicate key group.

Addresses the review comment
ClickHouse#111609 (comment).

Co-Authored-By: Claude Fable 5 <[email protected]>
The test pins that topKThroughJoin does not defer to a second pass that
would reject the read, using a ReplacingMergeTree table sorted in
descending order. Reading in reverse order with FINAL is now supported
for that engine, so the second pass accepts it and the deferral is
sound. Pin optimize_read_in_reverse_order_final = 0 to keep the test
exercising a rejected read, which keeps its reference unchanged. The
accepted case is covered by
04657_top_k_through_join_final_reverse_order.

Co-Authored-By: Claude Fable 5 <[email protected]>
topKThroughJoin decided whether the second pass would reject a reverse
FINAL read from the sort description alone (any column descending). That
misses the sorting key's per-column reverse flags: a table ordered by
`k DESC` queried as `ORDER BY k ASC` reads in reverse order even though
no sort column is descending, so the deferral fired, the second pass
rejected the read, and both optimizations were lost. It also blocked the
deferral for the opposite case, a descending sort description of a
descending sorting key, which is a direct read the second pass accepts.

wouldReadInOrderBeUseful already computed the input order and reduced it
to a bool, so return it instead (as getInputOrderIfReadInOrderIsUseful)
and gate on `direction != 1`, the same value the second pass uses.

Because the plan shape of a sound deferral and of one whose second pass
rejects the read afterwards is the same, the new test cases also count
the reading types of the plan.

Co-Authored-By: Claude Fable 5 <[email protected]>
cwurm and others added 3 commits August 8, 2026 16:59
…ehind a join

Covers the interaction of the reverse order FINAL read with
ReadFromMerge::requestReadingInOrder and the read-in-order through join
pass: with topKThroughJoin disabled, the second pass reads the children
of a Merge table in reverse order through the join, and the selected
rows must match a read with no optimization at all.

topKThroughJoin itself never defers for a Merge table, because it looks
for a MergeTree read on the preserved input while a Merge table reads
through its own step, so it wins the plan by default. That predates this
change and holds for every reading direction, with and without FINAL;
the test pins the current behavior rather than changing it.

Related to the review comment
ClickHouse#111609 (comment).

Co-Authored-By: Claude Fable 5 <[email protected]>
Measured in CI: with topKThroughJoin enabled, the Merge table plan has
one reverse order read, not none. The optimization injects its
Sort + Limit because it does not defer for a Merge table, but reading in
order then satisfies that injected sort, so the children are read in
reverse order anyway and the missing deferral only costs the extra sort
step.

Reference of https://s3.amazonaws.com/clickhouse-test-reports/PRs/111609/1b48419047f4cb65b18d854abdc2130f04f2e880/fast_test.html

Co-Authored-By: Claude Fable 5 <[email protected]>
…tests

Drop the links to the SELECT and FINAL documentation from the setting
description: only one other setting links the former, and both commands
are well known. Reword the settings history entry so it reads as prose.
Keep the comment change in 04234 to the sentence this change makes
untrue.

Shrink 04657 from 357 to 213 lines. The settings that are only pinned
against the randomization of the test runner move to session level, so
every query states just the setting it varies. The cases that read the
version column and is_deleted behind a join are removed, because the
FINAL merge runs below the join and 04506 already pins those semantics
without one; so are the INNER JOIN cases, which are not a shape
topKThroughJoin defers for, and the two cases that only read rows
through the topKThroughJoin path.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Storages/StorageMerge.cpp Resolved
cwurm and others added 2 commits August 9, 2026 12:00
The gate checked the enumerated storages, but those are not always the
ones a read goes through: `tableForRead` maps a table through
`IDatabase::getTableForRead`, which for a `MaterializedPostgreSQL`
database returns a `StorageMaterializedPostgreSQL` wrapper over a nested
ReplacingMergeTree. The wrapper is not a `MergeTreeData`, so the gate
rejected such tables even though the read reaches a `ReadFromMergeTree`
over a table that does support reading in reverse order with FINAL.

Ask the reading steps of the child plans instead, which is the same
question the second pass asks. A child plan without a reading step of
its own is still rejected, because `recursivelyApplyToReadingSteps` does
not descend into a nested `ReadFromMerge`: its tables would never be
switched to reading in reverse order while this step claims that its
output is sorted in that order.

Addresses the review comment
ClickHouse#111609 (comment).

Co-Authored-By: Claude Fable 5 <[email protected]>
/// Note that 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
/// here, and a descending sort description of it is a direct one.
const bool final_blocks_pass2 = order_info && reading->isQueryWithFinal()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

topKThroughJoin now defers this reverse-FINAL shape to pass 2 whenever the local ReadFromMergeTree says it can read in order, but that assumption stops being true once make_distributed_plan is enabled. In optimizeTreeSecondPass, tryMakeDistributedRead runs before optimizeReadInOrder and wraps the preserved-side ReadFromMergeTree in a GatherExchange (src/Processors/QueryPlan/Optimizations/optimizeTree.cpp:365-376). findReadingStep in src/Processors/QueryPlan/Optimizations/optimizeReadInOrder.cpp:126-172 does not descend through exchanges, so pass 2 never reaches the read to install requestReadingInOrder.

Before this patch, descending FINAL never deferred here, so ... FINAL LEFT JOIN ... ORDER BY key DESC LIMIT n SETTINGS make_distributed_plan = 1 still got topKThroughJoin's inner Sort + Limit. After this change it loses both optimizations. Can we block this deferral when make_distributed_plan is on, or otherwise preserve the through-join read-in-order contract across the distributed-read rewrite?

@cwurm

cwurm commented Aug 12, 2026

Copy link
Copy Markdown
Member Author

Closing in favor of #114479, which implements the same optimization for straightforward queries on ReplacingMergeTree and nothing else.

This pull request had grown to 22 files: besides the reverse FINAL read it changed ReadFromMerge::requestReadingInOrder so that Merge tables over ReplacingMergeTree benefit too, changed the deferral in topKThroughJoin so that ... FINAL LEFT JOIN ... ORDER BY key DESC LIMIT n reaches the new path, and changed the wouldReadInOrderBeUseful signature that both use. Every review comment here was about those parts rather than about the optimization itself, and each of them needed knowledge of a separate optimization to answer, which made the whole change hard to review.

The replacement keeps only the reverse FINAL read for a single ReplacingMergeTree table: 12 files, no change outside the FINAL read path, and no change to topKThroughJoin, StorageMerge or optimizeReadInOrder. It is strictly better than the current behavior for the queries in #58035 and leaves every other plan as it is today, which the unchanged 04234 and 04209 gate tests confirm.

The findings from this thread are kept:

  • The Merge table support, including asking the reading steps of the child plans rather than the enumerated storages, so that wrappers such as StorageMaterializedPostgreSQL are not rejected. Can be a follow-up on top of the new pull request.
  • The topKThroughJoin issues, which turned out to be pre-existing and independent of this work: the deferral infers the reading direction from the sort description instead of computing it, which loses both optimizations for a descending sorting key, and it does not account for make_distributed_plan. Both are described in the comments above, with reproducers; neither is a correctness problem, only a missed optimization.

alexey-milovidov added a commit to valerypetrov/ClickHouse that referenced this pull request Oct 7, 2026
…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: ClickHouse#117961
Related: ClickHouse#115345
Related: ClickHouse#111609

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

FINAL reads all data when sorting in reverse order

1 participant