Skip to content

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

Merged
alexey-milovidov merged 24 commits into
masterfrom
continue-pr-114479-reverse-final
Sep 3, 2026
Merged

alexey-milovidov merged 24 commits into
masterfrom
continue-pr-114479-reverse-final

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 18, 2026 •

Copy link
Copy Markdown
Member

Continue #114479 from @cwurm. This replacement makes its reverse FINAL read optimization merge-clean with current master; the original fork branch could not be updated because the Git HTTPS push transport stalled and the fork API does not grant Git-object write access.

Related: #114479

Changelog category (leave one):

  • Improvement

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

Enable reading ReplacingMergeTree data in reverse order with FINAL.


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

cwurm and others added 13 commits August 12, 2026 13:15
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: #58035

Co-Authored-By: Claude Fable 5 <[email protected]>
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]>
# Conflicts:
#	src/Core/Settings.cpp
@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5f22de8]

Summary: ✅


AI Review

Summary

This PR enables reverse-order read-in-order for FINAL on ReplacingMergeTree behind optimize_read_in_reverse_order_final, threads that mode through the FINAL merge path, and adjusts ReplacingSortedAlgorithm so equal-version ties keep the same winner as the forward read. The current diff is internally consistent, the autogenerated ORDER BY docs source text was updated in ParserSelectQuery.cpp, and the added stateless coverage exercises the main correctness cases, including level-0 parts, version ties, is_deleted, descending sort keys, and the conservative Merge-engine fallback. I did not find any remaining correctness, metadata, or test-evidence issues in the current PR head.

Final Verdict

✅ Approved

LLVM Coverage Report

Measured on commit 5f22de8.

Metric Baseline Current Δ
Lines 88.70% 88.70% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 81.00% 81.00% +0.00%

Changed lines: Changed C/C++ lines covered: 143/145 (98.62%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Aug 18, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 5f22de8ea with master a748a4544 (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

@cwurm

cwurm commented Aug 20, 2026

Copy link
Copy Markdown
Member

Fyi, AI review had the same findings on my PR #111609. It first wanted to extend it to the Merge engine, then to topKThroughJoin, then wanted to fix a bunch of unrelated issues in topKThroughJoin, then make topKThroughJoin + Merge work. The diff became bigger and bigger and harder for human review.

Eventually, I abandoned trying to please the AI and went back to just the straightforward FINAL on ReplacingMergeTree implementation that should cover 90% of workloads that benefit in #114479.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Both stress-test failures on 946f0026 are unrelated to this change — neither failing query involves FINAL, reverse order, or ReplacingMergeTree:

  • Stress test (arm_asan_ubsan): Logical error: 'Equal values are not contiguous within the range assumed to be sorted' on SELECT count() FROM (SELECT DISTINCT s FROM merge_distinct__fuzz_3 ORDER BY s ASC LIMIT 100) SETTINGS optimize_distinct_in_order = 1 — ascending, no FINAL, from the fuzzer. Tracked in Logical error: 'Equal values are not contiguous within the range assumed to be sorted' (STID: 2508-3319) #115455. CIDB shows it fleet-wide (26 distinct PRs on 2026-08-18, 14 on 2026-08-19, including master runs).
  • Stress test (amd_msan): Logical error: No host found for exchange stream A on SELECT count() FROM clusterAllReplicas(view(SELECT DISTINCT t2_04341.val FROM t1_04341 INNER JOIN t2_04341 ... SETTINGS make_distributed_plan = 1, distributed_plan_execute_locally = 1, serialize_query_plan = 1)) — a distributed-plan exchange issue with no MergeTree FINAL involved. CIDB shows it fleet-wide starting 2026-08-18 (12 PRs on 08-18, 20 on 08-19, including 3 master runs); I could not find an open issue for it.

@groeneai, please investigate the No host found for exchange stream failure (src/Server/DistributedQuery/StreamingExchangeLookup.cpp:45) and provide a fix in a separate PR: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115345&sha=946f0026cecfdcd37c65bb61c0caffd5dc25da60&name_0=PR&name_1=Stress%20test%20%28amd_msan%29 — if a fix is already in progress, please link it here.

`ReadFromMerge::requestReadingInOrder` rejects a reverse order request with
`FINAL`, so a `Merge` table over a `ReplacingMergeTree` does not use this
optimization. That is conservative, not incorrect: the plan keeps its sorting
step. Assert the result of such a query.
@groeneai

Copy link
Copy Markdown
Collaborator

The fix for this one is already merged: #113422 (merged 2026-08-19 22:26:54Z, 90e6c433), so no separate PR is needed.

Root cause: the decision on distributed_plan_execute_locally was taken twice from two different sources. QueryPlan::convertToDistributed read it from the interpreter's optimization_settings, while createExchangeLookup re-read it from CurrentThread::tryGetQueryContext(). A subquery carrying its own SETTINGS clause gets a context the outer interpreter never sees, so the two could disagree: the plan left the exchange-stream host list empty while the lookup was still built for streaming exchanges, and resolving a stream then threw at StreamingExchangeLookup.cpp:45. That is exactly the shape of the query that failed here, with make_distributed_plan, distributed_plan_execute_locally and serialize_query_plan scoped inside the view(...). The fix decides once and threads the value through.

Your head 946f0026 is from 2026-08-19 12:30:43Z and its Stress run started at 15:14:13Z, about 7 hours before the fix merged, so the failure is expected on that base.

On the tail: CIDB has 6 rows for this signature timestamped after the merge, but every one belongs to a workflow run created before it (17:39Z through 22:22Z; the two most recent are re-run attempts of runs created at 18:04Z and 18:46Z). The last occurrence anywhere is 2026-08-20 02:19:44. Since then there are 8310 Stress test rows across 197 commits with zero occurrences, and restricted to master runs whose commit I verified to be a descendant of 90e6c433, 942 rows across 18 commits, also zero. The pre-fix rate over 08-18 and 08-19 was 27 hits across 793 Stress commits, which would predict roughly 7 in that window.

@mintlify

mintlify Bot commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
ClickHouse-docs 🟢 Ready View Preview Aug 22, 2026, 6:52 AM

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (e0f90730) into the branch — the merge was clean, ninja clickhouse builds, and 04506_read_in_reverse_order_final and 02564_read_in_order_final_desc both pass locally against the freshly built binary.

The only red on fce6a335 is Stress test (arm_debug): Logical error: 'Equal values are not contiguous within the range assumed to be sorted' in DistinctSortedStreamTransform — a DISTINCT-in-order fuzzer failure with no FINAL, no reverse order and no ReplacingMergeTree in the stack, so it is unrelated to this change. It is the known fleet-wide failure tracked in #115455, and a fix is already in flight in #113242 (still open), so nothing to do here.

The one remaining unresolved thread (the ReadFromMerge::requestReadingInOrder blanket guard for direction != 1 && FINAL) was answered earlier: the guard is conservative, not incorrect — the plan keeps its sorting step so the result is identical, only unoptimized — and the behaviour is covered by the Merge-over-ReplacingMergeTree case in 04506_read_in_reverse_order_final. The latest AI Review reports ✅ no new findings.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (63b0fabe) into the branch — the merge was clean again (GitHub's CONFLICTING flag was stale for the third time), ninja clickhouse builds, and 04506_read_in_reverse_order_final and 02564_read_in_order_final_desc both pass locally against the freshly built binary.

Both reds on the previous head e0f90730 are unrelated to this change, and one of them is cleared by this merge:

  • Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 04510_not_has_function_explain: Code: 53. DB::Exception: CAST AS Array can only be performed between same-dimensional array types on has(_CAST([[('k', NULL)]], 'Array(Map(String, Nullable(Nothing)))'), m) — no FINAL, no reverse order, no ReplacingMergeTree. It was fleet-wide (41 distinct PRs on 2026-08-22) and is fixed on master by cd4cff64 ("Fix CAST of an Array(Map) constant sent to a remote server", 2026-08-22 01:06 UTC), which landed after e0f90730 was cut and is now included by this merge.
  • Stress test (arm_msan) / Hung check failed, possible deadlock found: the reported stack is a CPU-bound FunctionConvert<DataTypeDecimal<Decimal32>, NameToDecimal32>::executeInternal evaluation, i.e. the known uninterruptible CPU-bound function evaluation tracked in Uninterruptible CPU-bound function evaluation over a large value #112203, not a FINAL or read-in-order deadlock. The hung check is failing across the whole stress fleet — in the last 7 days it hit every stress variant (amd_debug, amd_msan, amd_tsan, amd_asan_ubsan, arm_debug, arm_msan, arm_tsan, arm_release, azure, s3), roughly one PR per variant per day.

The latest AI Review verdict on e0f90730 is ✅ no new findings. The single unresolved thread (the ReadFromMerge::requestReadingInOrder blanket guard for direction != 1 && FINAL) was answered earlier: the guard is conservative, not incorrect — the plan keeps its sorting step, so the result is identical, only unoptimized — and that behaviour is covered by the Merge-over-ReplacingMergeTree case in 04506_read_in_reverse_order_final.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (94701318) into the branch — clean again (the CONFLICTING flag was stale for the fourth time) — and fixed both new CI reds in 4d2ed8b6, both caused by master moving under the branch:

  • Style check (settings_changes_history): master rolled over to 26.9, so the record for optimize_read_in_reverse_order_final moved from the 26.8 block to the 26.9 block of src/Core/SettingsChangesHistory.cpp.
  • Docs check (Mintlify): the edit to docs/reference/statements/select/order-by.mdx now falls inside an AUTOGENERATED region, so it is reverted; the setting remains documented via its DECLARE doc string in src/Core/Settings.cpp, which is the source of truth for the generated docs.

SettingsChangesHistory.cpp compiles; no functional code changed in this pass.

Comment thread src/Core/Settings.cpp Resolved
@cwurm

cwurm commented Aug 27, 2026

Copy link
Copy Markdown
Member

My original PR #114479 was already approved and this is the same. Can we merge it?

alexey-milovidov and others added 2 commits August 29, 2026 07:56
…e `FINAL` reads

The autogenerated page `docs/reference/statements/select/order-by.mdx` is
generated from the doc text in `ParserSelectQuery.cpp`, which still said the
read-in-order optimization does not work together with the `FINAL` modifier.
Update it to state that with `FINAL` the optimization works in the direct
order of the sorting key, and for `ReplacingMergeTree` tables also in the
reverse order, controlled by `optimize_read_in_reverse_order_final`.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (7e56c3c8) into the branch — clean again (the CONFLICTING/UNKNOWN mergeability flag was stale for the fifth time) — and addressed the AI review Major in d6b0abfb: the doc text in ParserSelectQuery.cpp that generates docs/reference/statements/select/order-by.mdx no longer claims the read-in-order optimization does not work with FINAL; it now documents the direct-order behavior and the reverse-order path for ReplacingMergeTree under optimize_read_in_reverse_order_final.

ninja clickhouse builds, and 04506_read_in_reverse_order_final and 02564_read_in_order_final_desc both pass locally against the freshly built binary.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (6f1a3d76) into the branch as 27d7f304 — clean once again (GitHub reported the mergeability as UNKNOWN for the sixth time; the flag is stale for this branch, so it is always worth trying the merge). ninja clickhouse builds, and 04506_read_in_reverse_order_final and 02564_read_in_order_final_desc both pass locally against the freshly built binary.

Nothing to fix from the previous run on d6b0abfb:

  • The AI Review verdict on d6b0abfb is ✅ No new findings — the ORDER BY docs Major addressed in d6b0abfb (the doc string in ParserSelectQuery.cpp, which is the source of truth for the autogenerated page) is confirmed resolved.
  • There are no unresolved review threads left.
  • The ten jobs the CI summary listed with status ERROR (Fast test (arm_darwin), Build (amd_darwin), Build (arm_darwin), Build (arm_v80compat), Build (amd_freebsd), Build (ppc64le), Build (amd_compat), Build (amd_musl), Build (riscv64), Build (s390x)) never actually ran: the corresponding GitHub jobs have conclusion skipped, a 0 s duration, no steps and no logs, so nothing failed there. The same holds for Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6), whose report also contains a single 0 s job-level entry with no test results. The fresh run on 27d7f304 will re-cover them.

@cwurm the change is unchanged in substance from your #114479 — it just keeps being brought up to date with a moving master. The merge itself is a human decision, once this run is green.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (85ac0152) into the branch as 5f22de8e — clean again (the mergeability flag was UNKNOWN for the seventh time; it is stale for this branch). ninja clickhouse builds, and 04506_read_in_reverse_order_final and 02564_read_in_order_final_desc both pass locally against the freshly built binary.

All three reds on the previous head 27d7f304 are unrelated to this change, and the only test failure is cleared by this merge:

  • Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, parallel, 1/3) / 03707_autopr_unsupported_cases: supported_aggregation/supported_join counters came out as 0 0 under the old analyzer — no FINAL, no reverse order, no ReplacingMergeTree. It was fleet-wide (about 100 PRs plus master on 2026-08-31, 40 more on 2026-09-01; tracked in Flaky test: 03707_autopr_unsupported_cases #117480) and is fixed on master by Force the analyzer in 03707_autopr_unsupported_cases #117364 ("Force the analyzer in 03707_autopr_unsupported_cases", merged 2026-08-31 22:05 UTC, after 27d7f304 was cut), which is now included by this merge.
  • Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6): ERROR: session-timeout occurred during test execution — a job-level timeout with no failed test.
  • Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6): Container memory budget exceeded (/docker) — the report itself classifies it as an infrastructure/resource failure, with no failed test.

The AI Review verdict on 27d7f304 is ✅ Approved, and there are no unresolved review threads. The merge itself remains a human decision once this run is green.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Ok.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 3, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

@cwurm, yes as it is 100% green and passed review.

Merged via the queue into master with commit 3075b40 Sep 3, 2026
174 checks passed
@alexey-milovidov
alexey-milovidov deleted the continue-pr-114479-reverse-final branch September 3, 2026 22:22
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 3, 2026
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]>

This branch was successfully deployed

1 active deployment
staging - docs — 5f22de8e Deployed Sep 3, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants