Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix optimize read in order from a view. #54628

Merged

Conversation

vitlibar
Copy link
Member

Changelog category:

  • Performance Improvement

Changelog entry:

Enable ORDER BY optimization for reading data in corresponding order from a MergeTree table in case that the table is behind a view.

For example, the following SELECT

CREATE TABLE table1 (x UInt64) ENGINE=MergeTree ORDER BY x;
CREATE VIEW view1 AS SELECT x FROM table1;
...
SELECT * FROM (SELECT * FROM view1) ORDER BY x DESC LIMIT 20;

must understand that the table is already ordered and read only a few rows from the table (before this PR this query used to read the full table).

@nickitat nickitat self-assigned this Sep 14, 2023
@robot-ch-test-poll robot-ch-test-poll added pr-performance Pull request with some performance improvements pr-status-⏳ PR with some pending statuses labels Sep 14, 2023
@robot-ch-test-poll
Copy link
Contributor

robot-ch-test-poll commented Sep 14, 2023

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

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

Successful checks
Check nameDescriptionStatus
AST fuzzerRuns randomly generated queries to catch program errors. The build type is optionally given in parenthesis. If it fails, ask a maintainer for help✅ success
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✅ success
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✅ success
Compatibility checkChecks that clickhouse binary runs on distributions with old libc versions. If it fails, ask a maintainer for help✅ success
Docker image for serversThe check to build and optionally push the mentioned image to docker hub✅ success
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✅ success
Flaky testsChecks if new added or modified tests are flaky by running them repeatedly, in parallel, with more randomization. Functional tests are run 100 times with address sanitizer, and additional randomization of thread scheduling. Integrational tests are run up to 10 times. If at least once a new test has failed, or was too long, this check will be red. We don't allow flaky tests, read the doc✅ success
Install packagesChecks that the built packages are installable in a clear environment✅ success
Integration testsThe integration tests report. In parenthesis the package type is given, and in square brackets are the optional part/total tests✅ success
Mergeable CheckChecks if all other necessary checks are successful✅ success
Performance ComparisonMeasure changes in query performance. The performance test report is described in detail here. In square brackets are the optional part/total tests✅ success
Push to DockerhubThe check for building and pushing the CI related docker images to docker hub✅ success
SQLTestThere's no description for the check yet, please add it to tests/ci/ci_config.py:CHECK_DESCRIPTIONS✅ success
SQLancerFuzzing tests that detect logical bugs with SQLancer tool✅ success
SqllogicRun clickhouse on the sqllogic test set against sqlite and checks that all statements are passed✅ success
Stateful testsRuns stateful functional tests for ClickHouse binaries built in various configurations -- release, debug, with sanitizers, etc✅ success
Stateless testsRuns stateless functional tests for ClickHouse binaries built in various configurations -- release, debug, with sanitizers, etc✅ 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
Unit testsRuns the unit tests for different release types✅ success
Upgrade checkRuns stress tests on server version from last release and then tries to upgrade it to the version from the PR. It checks if the new server can successfully startup without any errors, crashes or sanitizer asserts✅ success
Check nameDescriptionStatus
Stress testRuns stateless functional tests concurrently from several clients to detect concurrency-related errors❌ failure

/// Depending on the argument the function materialize() is either a constant or works as identity().
/// In both cases this function is monotonic and non-decreasing.
return {.is_monotonic = true, .is_always_monotonic = true};
}
Copy link
Member Author

Choose a reason for hiding this comment

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

StorageView implicitly applies the materialize() function to each column of the result of an internal query (see StorageView::read). And then optimize_read_in_order checks the monotonicity of applied functions (see matchTrees()). So if materialize() becomes monotonic then the optimization optimize_read_in_order can work for views.

@vitlibar
Copy link
Member Author

vitlibar commented Sep 14, 2023

Also EXPLAIN shows the change this PR makes (notice the ReadType):

Before:

> EXPLAIN actions=1 SELECT * FROM (SELECT * FROM view1) ORDER BY x DESC LIMIT 20;

┌─explain─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ Expression (Projection)                                                                                                                                                                                         │
│ Actions: INPUT :: 0 -> x UInt64 : 0                                                                                                                                                                             │
│ Positions: 0                                                                                                                                                                                                    │
│   Limit (preliminary LIMIT (without OFFSET))                                                                                                                                                                    │
│   Limit 20                                                                                                                                                                                                      │
│   Offset 0                                                                                                                                                                                                      │
│     Sorting (Sorting for ORDER BY)                                                                                                                                                                              │
│     Sort description: x DESC                                                                                                                                                                                    │
│     Limit 20                                                                                                                                                                                                    │
│       Expression ((Before ORDER BY + (Projection + (Before ORDER BY + (Convert VIEW subquery result to VIEW table structure + (Materialize constants after VIEW subquery + (Projection + Before ORDER BY))))))) │
│       Actions: INPUT : 0 -> x UInt64 : 0                                                                                                                                                                        │
│                FUNCTION materialize(x :: 0) -> materialize(x) UInt64 : 1                                                                                                                                        │
│                ALIAS materialize(x) :: 1 -> x UInt64 : 0                                                                                                                                                        │
│       Positions: 0                                                                                                                                                                                              │
│         ReadFromMergeTree (default.table1)                                                                                                                                                                      │
│         ReadType: Default                                                                                                                                                                                       │
│         Parts: 1                                                                                                                                                                                                │
│         Granules: 1                                                                                                                                                                                             │
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘

After:

> EXPLAIN actions=1 SELECT * FROM (SELECT * FROM view1) ORDER BY x DESC LIMIT 20;

┌─explain─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ Expression (Projection)                                                                                                                                                                                         │
│ Actions: INPUT :: 0 -> x UInt64 : 0                                                                                                                                                                             │
│ Positions: 0                                                                                                                                                                                                    │
│   Limit (preliminary LIMIT (without OFFSET))                                                                                                                                                                    │
│   Limit 20                                                                                                                                                                                                      │
│   Offset 0                                                                                                                                                                                                      │
│     Sorting (Sorting for ORDER BY)                                                                                                                                                                              │
│     Prefix sort description: x DESC                                                                                                                                                                             │
│     Result sort description: x DESC                                                                                                                                                                             │
│     Limit 20                                                                                                                                                                                                    │
│       Expression ((Before ORDER BY + (Projection + (Before ORDER BY + (Convert VIEW subquery result to VIEW table structure + (Materialize constants after VIEW subquery + (Projection + Before ORDER BY))))))) │
│       Actions: INPUT : 0 -> x UInt64 : 0                                                                                                                                                                        │
│                FUNCTION materialize(x :: 0) -> materialize(x) UInt64 : 1                                                                                                                                        │
│                ALIAS materialize(x) :: 1 -> x UInt64 : 0                                                                                                                                                        │
│       Positions: 0                                                                                                                                                                                              │
│         ReadFromMergeTree (default.table1)                                                                                                                                                                      │
│         ReadType: InReverseOrder                                                                                                                                                                                │
│         Parts: 1                                                                                                                                                                                                │
│         Granules: 1                                                                                                                                                                                             │
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘

@robot-ch-test-poll3 robot-ch-test-poll3 added pr-status-❌ PR with some error/faliure statuses and removed pr-status-⏳ PR with some pending statuses labels Sep 14, 2023
@SaltTan
Copy link
Contributor

SaltTan commented Sep 15, 2023

related #34720
maybe also #18561?


SYSTEM FLUSH LOGS;

SELECT concat('read_rows=', if(read_rows<40, 'ok', toString(read_rows))) FROM system.query_log WHERE current_database = currentDatabase() AND query LIKE '%test 02877, query 1%' AND type='QueryFinish';
Copy link
Member

Choose a reason for hiding this comment

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

imo it is better to check the query plan

Copy link
Member Author

Choose a reason for hiding this comment

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

Ok, I've rewritten the test.

@robot-clickhouse robot-clickhouse added pr-status-⏳ PR with some pending statuses and removed pr-status-❌ PR with some error/faliure statuses labels Sep 20, 2023
@vitlibar
Copy link
Member Author

related #34720 maybe also #18561?

#34720 - yes
#18561 - no

@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added pr-status-❌ PR with some error/faliure statuses and removed pr-status-⏳ PR with some pending statuses labels Sep 20, 2023
@vitlibar vitlibar merged commit b3d3ad0 into ClickHouse:master Sep 20, 2023
277 of 278 checks passed
@vitlibar vitlibar deleted the fix-optimize-read-in-order-from-view branch September 20, 2023 17:14
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 pr-status-❌ PR with some error/faliure statuses
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

7 participants