Skip to content

Implement vertical replacing FINAL - #54366

Merged
alexey-milovidov merged 25 commits into
ClickHouse:masterfrom
canhld94:final_no_copy
Jan 14, 2024
Merged

alexey-milovidov merged 25 commits into
ClickHouse:masterfrom
canhld94:final_no_copy

Conversation

@canhld94

@canhld94 canhld94 commented Sep 6, 2023 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Performance Improvement

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

More cache-friendly final implementation.
Note on the behaviour change: previously queries with FINAL modifier that read with a single stream (e.g. max_threads=1) produced sorted output without explicitly provided ORDER BY clause. This behaviour no longer exists when enable_vertical_final = true (and it is so by default).


Original idea from @jorisgio , this PR is co-authored by @jorisgio

Explanation of the idea (original comment):

One way to think about this is like vertical vs horizontal merges.

Currently, FINAL is a merge sort that works on rows using sort_cursors. For each row, it iterates on all columns, and copy the data to a new block. But if the block is big enough, with enough input stream, it means when it comes back to read/write the next value in one column, the column was evicted from CPU cache because too many data was read/writen in between. With big enough table, it means that every copy of the rows ends up being a memory access, which slows down everything.

The idea of this implementation is to prevent that and be more cache friendly. So instead of copying all columns for each rows when merge sort happens, it only works on sorting key to perform merge sorts, and writes an index for all blocks. The index tells if the row must be filtered out, because it is replaced by a another row with more recent version, or kept. This minimize data that is read/written during merge sort, and reduces cache usage. It just emits back the blocks that come from reading, extended with an index.

Then after this there is a filter transform. The filter process the blocks, and removes rows based on the index, "collapsing" the columns. This happens columns by columns, and is optimized, so it is also cache friendly because it works vertically instead of horizontally, so memcpy is fast.

The pros:

  • It is cache friendly, and fast on medium/big tables
    this allows to skip non-overlapping blocks and pass it as is with a constant index, which means 0 work for "lonely" chunks. This happens relatively frequently in practice, since there is usually small parts that have low overlap with big old parts.

The cons:

  • This is obviously more work, so for very small tables, there is some expectation that it slower than current implementation, as the cache benefit will not kick in.
  • If FINAL had to filter a lot of data, that would end up with very small blocks, which in practice was a performance regression on some corner cases, because the next stages of the pipelines would get significantly smaller block size.

Information about CI checks: https://clickhouse.com/docs/en/development/continuous-integration/

@canhld94 canhld94 changed the title wip: more cache-friendly final implementation wip: more cache-friendly replacing FINAL implementation Sep 6, 2023
@nickitat nickitat self-assigned this Sep 6, 2023
@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Sep 6, 2023
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-performance Pull request with some performance improvements label Sep 6, 2023
@robot-clickhouse-ci-1

robot-clickhouse-ci-1 commented Sep 6, 2023 •

Copy link
Copy Markdown
Contributor

This is an automated comment for commit 458c8d7 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
ClickBenchRuns [ClickBench](https://github.com/ClickHouse/ClickBench/) with instant-attach table✅ 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
Docs checkThere's no description for the check yet, please add it to tests/ci/ci_config.py:CHECK_DESCRIPTIONS✅ 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
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
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
Performance ComparisonMeasure changes in query performance. The performance test report is described in detail here. In square brackets are the optional part/total tests❌ failure
Stateless testsRuns stateless functional tests for ClickHouse binaries built in various configurations -- release, debug, with sanitizers, etc❌ failure
Stress testRuns stateless functional tests concurrently from several clients to detect concurrency-related errors❌ failure

@nickitat

Copy link
Copy Markdown
Member

pls resolve conflicts

@canhld94

Copy link
Copy Markdown
Contributor Author

@nickitat sorry, I've been busy with other works. Will go back to this PR as soon as I can

    - resolve conflicts

Signed-off-by: Duc Canh Le <[email protected]>
Signed-off-by: Duc Canh Le <[email protected]>
@canhld94 canhld94 changed the title wip: more cache-friendly replacing FINAL implementation Implement vertical replacing FINAL Oct 6, 2023
@canhld94

canhld94 commented Oct 6, 2023 •

Copy link
Copy Markdown
Contributor Author
image

Start testing with some prod data. It's a huge win for our tables, especially in term of memory usage.

@jorisgio

jorisgio commented Oct 6, 2023 •

Copy link
Copy Markdown
Contributor

Start testing with some prod data. It's a huge win for our tables, especially in term of memory usage.

@canhld94 repeating publicly, not that i think this idea is bad, but i fell into this trap myself 6 months ago.
It is indeed a huge wins when you read a lot of columns, the key for this speedup is the star. So every time i think it is amazing, but then i try it on actual queries, and there is no change in speed, this is why i left the initial PR rot a bit. But i think it would be interesting to see the results of a benchmark run. I mean it is amazing speedup, but i suspect it is less amazing than it looks.

canhld94 and others added 2 commits October 10, 2023 11:31
Signed-off-by: Duc Canh Le <[email protected]>
Co-authored-by: Joris Giovannangeli <[email protected]>
Signed-off-by: Duc Canh Le <[email protected]>
canhld94 and others added 3 commits October 11, 2023 10:30
Co-authored-by: Joris Giovannangeli <[email protected]>
Signed-off-by: Duc Canh Le <[email protected]>
Co-authored-by: Joris Giovannangeli <[email protected]>
Signed-off-by: Duc Canh Le <[email protected]>
Signed-off-by: Duc Canh Le <[email protected]>
@canhld94

Copy link
Copy Markdown
Contributor Author

Test 02447_drop_database_replica is flaky

Fix flaky test 02447_drop_database_replica
@canhld94

canhld94 commented Oct 16, 2023 •

Copy link
Copy Markdown
Contributor Author

Performance Comparison [1/4] — 5 slower, 1 unstable Details
Performance Comparison [2/4] — 1 faster Details
Performance Comparison [3/4] — 1 too long, 1 faster, 1 unstable Details
Performance Comparison [4/4] — 30 faster Details

The overall performance improvement for FINAL is good.
In general, skipping final will: (1) has less memory usage compared to origin FINAL in most cases, (2) run faster than origin FINAL when: query read a big column, or when query has WHERE, (3) may run slower if query has ORDER BY [primary key] and result has > 10000 rows.
We plan to test it more thoroughly with our prod workload this week.
@nickitat pls help to review this PR when you have time [THANKS]. Currently I'm setting use_skipping_final to true by default to test performance and correctness.

@nickitat

Copy link
Copy Markdown
Member

these two descriptions look a little bit orthogonal:

M(Bool, use_skipping_final, true, "If enable, remove duplicated rows during FINAL by marking rows as deleted and filtering them later instead of merging rows", 0)

Reimplementation of #46810: instead of rewriting chunks row by row, we create an index column for each input chunk to store selected rows, then later use IColumn::index to get selected rows.

could you pls describe exactly the new approach, its pros and cons?

@jorisgio

Copy link
Copy Markdown
Contributor

Let me describe the original idea, hopefully @canhld94 can provide details of the new implemenation which is more advanced.

One way to think about this is like vertical vs horizontal merges.
The original idea came when i spent quite a lot of time profiling FINAL queries with many columns, and seeing again and again that the bottleneck was memcpy. At first, i thought that it was maxing memory bandwidth, and that was kind of unavoidable, but after running more tests (running the queries pinned to some socket, and running memory tests in the background) i realize it was far from maxing memory bandwidth. In fact it was not using more than half of it.

So i came to the realization that the bottlneck was not in memory bandwidth, but in memory latency, and the performance cliff happened when cpu cache was full. I confirmed that with trying with different block size and columns size, and FINAL runs fast until there is enough data to fill the cache.

Currently, FINAL is a merge sort that works on rows using sort_cursors. For each row, it iterates on all columns, and copy the data to a new block. But if the block is big enough, with enough input stream, it means when it comes back to read/write the next value in one column, the column was evicted from CPU cache because too many data was read/writen in between. With big enough table, it means that every copy of the rows ends up being a memory access, which slows down everything.

The idea of this implementation is to prevent that and be more cache friendly. So instead of copying all columns for each rows when merge sort happens, it only works on sorting key to perform merge sorts, and writes an index for all blocks. The index tells if the row must be filtered out, because it is replaced by a another row with more recent version, or kept. This minimize data that is read/written during merge sort, and reduces cache usage. It just emits back the blocks that come from reading, extended with an index.

Then after this there is a filter transform. The filter process the blocks, and removes rows based on the index, "collapsing" the columns. This happens columns by columns, and is optimized, so it is also cache friendly because it works vertically instead of horizontally, so memcpy is fast.

The pros:

  • it is cache friendly, and fast on medium/big tables
  • this allows to skip non-overlapping blocks and pass it as is with a constant index, which means 0 work for "lonely" chunks. This happens relatively frequently in practice, since there is usually small parts that have low overlap with big old parts.

The cons:

  • this is obviously more work, so for very small tables, there is some expectation that it slower than current implementation, as the cache benefit will not kick in.
  • On top of that, i am not sure about the current implemenation, but my first implementation was not merging chunks after the filter transform. So if FINAL had to filter a lot of data, that would end up with very small blocks, which in practice was a performance regression on some corner cases, because the next stages of the pipelines would get significantly smaller block size.

@nickitat nickitat 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.

I almost finished

/// In the first case, we create a cloned chunk with only one row from `selected_row.row_num` and let selected_row point to it
/// In the second case, we mark selected_row.owned_chunk = nullptr
/// In either case, the chunk is "lonely" and if later selected_row is inserted to final result, the chunk will be emitted
/// immediately. This will create some blocks with only single row, but it's not a big problem.

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.

I think we need to consider the possible issue of having too many small chunks (what jorisgio@ pointed out). e.g. we could do the same thing that is done in aggregation by partitions

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Honestly I don't want to squash chunks because the whole point of skipping algorithm is to prevent copy row-by-row.
But squashing into 1MB blocks doesn't look too bad. I will try and see the result.

@canhld94

canhld94 commented Nov 3, 2023

Copy link
Copy Markdown
Contributor Author

Kindly ping @nickitat @alexey-milovidov

@nickitat nickitat 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.

only few minor suggestions

@canhld94

canhld94 commented Nov 14, 2023 •

Copy link
Copy Markdown
Contributor Author

@nickitat sorry for late response, dealing with issues in our clusters for a week long..
Review addressed.
This week we upgraded our big cluster to include this PR (up to 1668763) and the result is quite good (can see visible drop in P99 and P95), as we're mainly using FINAL with aggregations:

image

Signed-off-by: Duc Canh Le <[email protected]>
Resolve conflicts + add some comments

Signed-off-by: Duc Canh Le <[email protected]>
Signed-off-by: Duc Canh Le <[email protected]>
@canhld94

Copy link
Copy Markdown
Contributor Author

@nickitat @alexey-milovidov can you also help to review this PR [THANKS]. We've been running this on prod for a month without any issue and stable performance.
FTR performance test:
image

Resolve conflicts

Signed-off-by: Duc Canh Le <[email protected]>

@nickitat nickitat 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.

pls merge with master

@canhld94

Copy link
Copy Markdown
Contributor Author

@nickitat I resolves the conflicts, with some small changes:

  1. Setting name use_skipping_final -> enable_vertical_final
  2. Simplify performance tests, before there're two similar tests but only different in storage engine (collapsing vs replacing), I think one test with replacing is enough

Do you think we can enable enable_vertical_final by default?

@canhld94

Copy link
Copy Markdown
Contributor Author

While there's improvement for FINAL:
image

There're weird regression for base64 which I've not yet understand why it could happen. Will check a little more tomorrow.
image

@nickitat

Copy link
Copy Markdown
Member

There're weird regression for base64 which I've not yet understand why it could happen. Will check a little more tomorrow.

take it with a pinch of salt. it might be just unstable

@nickitat

Copy link
Copy Markdown
Member

Do you think we can enable enable_vertical_final by default?

I wouldn't think - I'd just enable )

@alexey-milovidov
alexey-milovidov merged commit 65ac905 into ClickHouse:master Jan 14, 2024
@alexey-milovidov

Copy link
Copy Markdown
Member

The slowdown of base64 has confirmed after merge, so it is stable enough: https://s3.amazonaws.com/clickhouse-test-reports/0/65ac9050322c6e7f37d0e45fabe6e52e558d2a98/performance_comparison_[2_4]/report.html

But we cannot do much about it - maybe it is just related to some re-arrangement of the code.

@jorisgio

Copy link
Copy Markdown
Contributor

Regarding enabling by default is't it a breaking change? I am not sure if is documented but as far as I know if you run select final without order by and max final thread 1 you will still get results in orders now it won't be true anymore I think? Unless I am mistaken but it might be worth a mention as a breaking change

@nickitat nickitat added the pr-backward-incompatible Pull request with backwards incompatible changes label Jan 16, 2024
@UnamedRus

Copy link
Copy Markdown
Contributor

About result in order, i guess #58120 also can cause results out of order.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-backward-incompatible Pull request with backwards incompatible changes pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants