Skip to content

Enable reading in reverse order optimization for FINAL queries - #58361

Closed
cwurm wants to merge 1 commit into
ClickHouse:masterfrom
cwurm:final_read_reverse_order
Closed

cwurm wants to merge 1 commit into
ClickHouse:masterfrom
cwurm:final_read_reverse_order

Conversation

@cwurm

@cwurm cwurm commented Dec 29, 2023

Copy link
Copy Markdown
Member

Enable reading in reverse order when sorting against the sorting key in FINAL queries. Addresses slowness explained in #58035. Closes #58035.

The reason for previously disabling it seems to have been some concerns about incorrect behavior of merging algorithms (see deleted comment). But no specific incorrect behavior is mentioned, and all the tests I wrote seem to work fine. Maybe CI will find something (I don't have a full setup myself that can run all tests).

As expected, performance is much improved for the queries mentioned in #58035:

arrakis :) SELECT x FROM numbers FINAL ORDER BY x DESC LIMIT 1 SETTINGS optimize_read_in_order = 0

┌─────────x─┐
│ 499999999 │
└───────────┘

1 row in set. Elapsed: 8.583 sec. Processed 500.00 million rows, 2.00 GB (58.25 million rows/s., 233.01 MB/s.)
Peak memory usage: 8.13 MiB.

arrakis :) SELECT x FROM numbers FINAL ORDER BY x DESC LIMIT 1 SETTINGS optimize_read_in_order = 1

┌─────────x─┐
│ 499999999 │
└───────────┘

1 row in set. Elapsed: 1.183 sec. Processed 793.56 thousand rows, 3.17 MB (670.57 thousand rows/s., 2.68 MB/s.)
Peak memory usage: 1.88 GiB.

Changelog category (leave one):

  • Performance Improvement

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

Enable reading in reverse order optimization for FINAL queries.

@cwurm
cwurm force-pushed the final_read_reverse_order branch from 52f8aad to eaa13d6 Compare December 29, 2023 21:23
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-performance Pull request with some performance improvements label Dec 29, 2023
@robot-ch-test-poll4

robot-ch-test-poll4 commented Dec 29, 2023 •

Copy link
Copy Markdown
Contributor

This is an automated comment for commit 2d24cb4 with description of existing statuses. It's updated for the latest CI running

❌ Click here to open a full report in a separate page

Check nameDescriptionStatus
A SyncIf it fails, ask a maintainer for help⏳ pending
CI runningA meta-check that indicates the running CI. Normally, it's in success or pending state. The failed status indicates some problems with the PR❌ failure
ClickHouse build checkBuilds ClickHouse in various configurations for use in further steps. You have to fix the builds that fail. Build logs often has enough information to fix the error, but you might have to reproduce the failure locally. The cmake options can be found in the build log, grepping for cmake. Use these options and follow the general build process⏳ pending
Fast testNormally this is the first check that is ran for a PR. It builds ClickHouse and runs most of stateless functional tests, omitting some. If it fails, further checks are not started until it is fixed. Look at the report to see which tests fail, then reproduce the failure locally as described here❌ failure
Mergeable CheckChecks if all other necessary checks are successful❌ failure
Successful checks
Check nameDescriptionStatus
Docs checkBuilds and tests the documentation✅ success
PR CheckChecks correctness of the PR's body✅ success
Style checkRuns a set of checks to keep the code style clean. If some of tests failed, see the related log from the report✅ success

@cwurm

cwurm commented Dec 30, 2023

Copy link
Copy Markdown
Member Author

Reading in reverse order for FINAL was disabled in #46009 following bug report #45815. The example provided is working fine with this implementation. FYI @vdimir

@alexey-milovidov alexey-milovidov added the 🎅 🎁 gift🎄 To make people wonder label Dec 30, 2023
@canhld94

canhld94 commented Jan 2, 2024

Copy link
Copy Markdown
Contributor

As in #58035 (comment), I can foresee two cases that read-in-reverse-order may lead to wrong FINAL behaviour:

  1. ReplacingMergeTree
    For example, we read from a level-0 part with two rows 1 and 10 that have duplicated keys. If we use read-in-order, row 10 will be kept (expected); if we use read-in-reverse-order, row 1 will be kept
  2. AggregatingMergeTree
    For example, same situation as above, and aggregate function is anyFirst, anyLast, first_value, last_value, and depending on the data, argMin, argMax may also have issue.

I cannot figure out if there is any issue with CollapsingMergeTree or VersionedCollapsingMergeTree yet (we usually don't use FINAL for such engines).

@canhld94

canhld94 commented Jan 2, 2024

Copy link
Copy Markdown
Contributor

As in #58035 (comment), I can foresee two cases that read-in-reverse-order may lead to wrong FINAL behaviour:

  1. ReplacingMergeTree
    For example, we read from a level-0 part with two rows 1 and 10 that have duplicated keys. If we use read-in-order, row 10 will be kept (expected); if we use read-in-reverse-order, row 1 will be kept
  2. AggregatingMergeTree
    For example, same situation as above, and aggregate function is anyFirst, anyLast, first_value, last_value, and depending on the data, argMin, argMax may also have issue.

I cannot figure out if there is any issue with CollapsingMergeTree or VersionedCollapsingMergeTree yet (we usually don't use FINAL for such engines).

Simple way to bypass these issues is to only use read-in-reverse-order if there is no level-0 part in source parts.

@cwurm

cwurm commented Jan 2, 2024

Copy link
Copy Markdown
Member Author

As in #58035 (comment), I can foresee two cases that read-in-reverse-order may lead to wrong FINAL behaviour:

  1. ReplacingMergeTree
    For example, we read from a level-0 part with two rows 1 and 10 that have duplicated keys. If we use read-in-order, row 10 will be kept (expected); if we use read-in-reverse-order, row 1 will be kept

Indeed, you're right. I need to think about what to do about this case and others. For now, I've added a test for it that will fail with the current implementation.

Simple way to bypass these issues is to only use read-in-reverse-order if there is no level-0 part in source parts.

Yeah, that could be the easy way to go.

@UnamedRus

Copy link
Copy Markdown
Contributor

and depending on the data, argMin, argMax may also have issue.

They aren't stable if you have the same number for value.
So, it's kinda OK

ssize_t version_column_number = -1;
bool cleanup = false;

int read_direction = 1;

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.

when we have only two alternatives - it is handy to use some type with two possible values


CREATE TABLE t_02947_reverse_order_final (x int, y int, z int)
ENGINE = ReplacingMergeTree ORDER BY (x, y);

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.

Suggested change
system stop merges t_02947_reverse_order_final;

ENGINE = ReplacingMergeTree(ver) ORDER BY x;

-- Level-0 part with duplicate rows
INSERT INTO t_02947_reverse_order_final SETTINGS optimize_on_insert = 0 VALUES (0, 0, 0), (0, 1, 0), (1, 0, 0), (1, 1, 1);

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.

let's add a similar test, but each row will be inserted separately (to form 4 distinct parts).
I am a little concerned about these lines: https://github.com/ClickHouse/ClickHouse/pull/58361/files#diff-c2317ca02dca707ab63917057efaf36ca941e500948fc64857e1b7b0f29bff51R127-R128
but probably everything is ok, since we continue to process parts themselves from left to right

@nickitat

Copy link
Copy Markdown
Member

pls merge with master

@alexey-milovidov

Copy link
Copy Markdown
Member

@cwurm, please merge with master.

@cwurm
cwurm force-pushed the final_read_reverse_order branch from 8191fb6 to 2d24cb4 Compare June 14, 2024 13:00
@cwurm

cwurm commented Jun 14, 2024

Copy link
Copy Markdown
Member Author

I've rebased it. But the problem now is that it doesn't seem to work anymore with the Level-0 parts; it doesn't de-duplicate. I need to look into it but it's hard to find the time.

@alexey-milovidov alexey-milovidov removed the 🎅 🎁 gift🎄 To make people wonder label Jul 5, 2024
@alexey-milovidov

Copy link
Copy Markdown
Member

@cwurm, 57 tests from the fast test suite have failed.

cwurm added a commit to cwurm/ClickHouse that referenced this pull request Jul 22, 2026
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: among rows with
equal keys and equal (or absent) versions, the previously selected row
is kept unless the current row comes from another (newer) data part,
which mirrors the "last row wins" rule of the direct reading order.
The other engines keep the old behavior since their merging algorithms
rely on the direct order of rows.

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

Not built or tested yet (WIP).

Co-Authored-By: Claude Fable 5 <[email protected]>
cwurm added a commit to cwurm/ClickHouse that referenced this pull request Jul 23, 2026
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]>
cwurm added a commit to cwurm/ClickHouse that referenced this pull request Jul 23, 2026
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]>
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

6 participants