Skip to content

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

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

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

Conversation

@cwurm

@cwurm cwurm commented Aug 12, 2026 •

Copy link
Copy Markdown
Member

Closes: #58035
Related: #58361
Related: #111609

When a query with FINAL sorts in reverse order of the sorting key, for example ORDER BY key DESC LIMIT n, the read-in-order optimization was disabled and the query read the whole table. It now applies for ReplacingMergeTree.

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. That 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 the parts still arrive from the oldest to the newest one. This is what makes the reverse read select the same row of a duplicate key group as a direct read, which is the correctness concern that stopped #58361.

The other engines keep the previous behavior, since their merging algorithms depend 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, and so on.

On a 110 million row ReplacingMergeTree table with two overlapping parts, SELECT x FROM t FINAL ORDER BY x DESC LIMIT 1 (measured on a RelWithDebInfo build):

before after
Rows read 110.1 million 1.71 million
Elapsed 4.5 s 0.22 s
Peak memory 41 MB 23 MB

Trade-off: as with 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. A query that reads the full result with ORDER BY key DESC and no small LIMIT may therefore become slower on a wide or mostly merged table. The new setting optimize_read_in_reverse_order_final (default enabled) turns the optimization off, and compatibility with an earlier version restores the previous plans.

Out of scope, to keep this change reviewable: Merge tables over ReplacingMergeTree, and the interaction with topKThroughJoin, which keeps its own optimization for ... FINAL LEFT JOIN ... ORDER BY key DESC LIMIT n. Both can follow separately.

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 the FINAL modifier that sort in reverse order of the sorting key on ReplacingMergeTree tables, so that 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.


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

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, 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,
`SELECT x FROM t FINAL ORDER BY x DESC LIMIT 1` reads 1.71 million rows
instead of 110.1 million, in 0.22s instead of 4.5s.

Closes: ClickHouse#58035

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

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8fade83]

Summary: ✅


AI Review

Summary

This PR enables reverse-order read-in-order for FINAL on ReplacingMergeTree by threading read_in_reverse through the FINAL merge path, fixing equal-version tie-breaking in ReplacingSortedAlgorithm, adding a compatibility setting, and covering the new plans/results with focused stateless tests. I did not find any new correctness, safety, performance, or PR-metadata issues in the current code; the earlier descending-key gap is covered by the added regression and remains resolved.

Final Verdict

✅ No new findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.80% 86.80% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.20% 79.20% +0.00%

Changed lines: Changed C/C++ lines covered: 140/142 (98.59%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 12, 2026
cwurm and others added 2 commits August 13, 2026 11:13
The page stated that the read-in-order optimization does not work with
the FINAL modifier at all, which was already inaccurate for the direct
order, and is now inaccurate for the reverse order of a
ReplacingMergeTree table.

The new setting is named without a link, because the settings pages are
regenerated by the nightly documentation workflow, so its anchor does
not exist yet and the blocking link check would fail on it.

Co-Authored-By: Claude Fable 5 <[email protected]>
@cwurm
cwurm marked this pull request as ready for review August 13, 2026 09:45
@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 8fade83e3 with master c545616f6 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 702.05 MiB 699.03 MiB -3.02 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

119 translation units recompiled, 1321 s compile time in total, 119 of them have a recent master baseline.

Job report

@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 3 query(s) improved out of 34 analysed

PR #114479 adds the optimize_read_in_reverse_order_final optimization, which only affects FINAL reads of ReplacingMergeTree tables (the rest of the diff is a mechanical extraction of the range-splitting helper). None of the flagged ClickBench or TPC-H queries use FINAL or ReplacingMergeTree, so the diff cannot plausibly move their runtimes, and Q13/16/18/28/30/31 were downgraded as off-path variance. Three large improvements — ClickBench Q23 (×2.3 faster) and TPC-H Q7 (×8.6 faster) and Q8 (×2.2 faster) — remain flagged because their large, consistent deltas are locked by the trust override and match CPU drops, but given the unrelated code path they most likely reflect an environment/build difference. The low source-run count (6 vs 30) reinforces reading all of these with caution rather than as real effects of this change.

clickbench

🟢 1 improved · ⚠️ 7 inconclusive

Flagged queries (8 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 23 improvement 167 74 ×2.3 faster <0.0001 cpu: Large delta (×2.3 faster) confirmed by both tests and matched by a CPU drop, so the verdict stands; but the diff only touches FINAL on ReplacingMergeTree, so the real cause is likely a build/environment shift.
⚠️ 13 not_sure 426 365 -14.4% <0.0001 This PR only changes the FINAL reverse-order path for ReplacingMergeTree; this ClickBench SELECT uses neither, so the -14.4% is off the changed code path and reads as run-to-run variance.
⚠️ 16 not_sure 793 707 -10.8% <0.0001 The change is confined to FINAL on ReplacingMergeTree, which this query does not exercise, so the -10.8% cannot be attributed to the diff.
⚠️ 18 not_sure 1298 1224 -5.7% <0.0001 Off the changed path (no FINAL, no ReplacingMergeTree); the -5.7% is small and best read as measurement noise.
⚠️ 28 not_sure 1048 1152 +9.9% <0.0001 The +9.9% regression is on a plain SELECT that never touches FINAL or ReplacingMergeTree, so the diff cannot cause it; treat as variance.
⚠️ 30 not_sure 279 247 -11.5% <0.0001 This PR touches only the FINAL reverse-read path; this query doesn't use it, so the -11.5% is off-path and not attributable to the change.
⚠️ 31 not_sure 395 332 -15.9% <0.0001 No FINAL / ReplacingMergeTree involvement, so the -15.9% is off the changed code path rather than a real PR effect.
⚠️ 32 not_sure 1320 1422 +7.7% 0.0012 Borderline with mixed signals from the two tests, and off the changed code path anyway; no reliable PR effect here.

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

🟢 2 improved

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 7 improvement 574 67 ×8.6 faster <0.0001 join_operator: Very large delta (×8.6 faster) with a big matching CPU drop locks the verdict; this join query uses no FINAL/ReplacingMergeTree, so the cause is most likely environmental rather than this diff.
🟢 8 improvement 175 78 ×2.2 faster <0.0001 join_operator: Large delta (×2.2 faster) backed by a CPU drop keeps the verdict, but this query is off the changed FINAL path, so read the cause as a build/environment shift.

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.

Debug info
  • StressHouse run: 2fc22095-674c-4a2b-aaed-cfc504072593
  • MIRAI run: c5602001-9b9c-4f4e-b45a-c8b8be450b10
  • PR check IDs:
    • clickbench_1701769_1786946934
    • clickbench_1701775_1786946934
    • clickbench_1701788_1786946933
    • tpch_adapted_1_official_1701798_1786946934
    • tpch_adapted_1_official_1701810_1786946934
    • tpch_adapted_1_official_1701840_1786946934

@alexey-milovidov alexey-milovidov left a comment

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.

Looks good and clear.

@alexey-milovidov alexey-milovidov self-assigned this Aug 14, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Superseded by #115345. I could not push the clean merge resolution to the fork here: git push stalled in the HTTPS transport and the fork does not grant Git-object API write access. The replacement preserves Christoph Wurm’s original commits and updates the feature onto current master.

@cwurm

cwurm commented Aug 18, 2026

Copy link
Copy Markdown
Member Author

I could have merged master...

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

2 participants