Skip to content

WIP Add Sorting Optimization with General Data Hints#48800

Open
TrueAstralpirate wants to merge 73 commits intoClickHouse:masterfrom
TrueAstralpirate:feature/optimizeSorting
Open

WIP Add Sorting Optimization with General Data Hints#48800
TrueAstralpirate wants to merge 73 commits intoClickHouse:masterfrom
TrueAstralpirate:feature/optimizeSorting

Conversation

@TrueAstralpirate
Copy link
Copy Markdown

@TrueAstralpirate TrueAstralpirate commented Apr 14, 2023

Changelog category (leave one):

  • Performance Improvement

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

todo

@CLAassistant
Copy link
Copy Markdown

CLAassistant commented Apr 14, 2023

CLA assistant check
All committers have signed the CLA.

@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-feature Pull request with new product feature label Apr 14, 2023
@nickitat nickitat self-assigned this Apr 14, 2023
@robot-ch-test-poll1 robot-ch-test-poll1 added pr-performance Pull request with some performance improvements and removed pr-feature Pull request with new product feature labels Apr 14, 2023
@TrueAstralpirate TrueAstralpirate force-pushed the feature/optimizeSorting branch from 934d43c to 65b6d19 Compare April 15, 2023 00:45
@nickitat nickitat added the can be tested Allows running workflows for external contributors label Apr 15, 2023
@TrueAstralpirate TrueAstralpirate force-pushed the feature/optimizeSorting branch 18 times, most recently from f687ced to 76ac6ee Compare April 22, 2023 07:47
@TrueAstralpirate TrueAstralpirate force-pushed the feature/optimizeSorting branch 2 times, most recently from 4c6195e to 39f32a4 Compare May 1, 2023 12:22
@robot-ch-test-poll3
Copy link
Copy Markdown
Contributor

robot-ch-test-poll3 commented May 1, 2023

This is an automated comment for commit 2cae61d 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
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 keeper imageThe check to build and optionally push the mentioned image to docker hub✅ success
Docker server imageThe check to build and optionally push the mentioned image to docker hub✅ success
Docs checkBuilds and tests the documentation✅ 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
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
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
Stateful testsRuns stateful functional tests for ClickHouse binaries built in various configurations -- release, debug, with sanitizers, etc✅ success
Stress testRuns stateless functional tests concurrently from several clients to detect concurrency-related errors✅ 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
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⏳ pending
Integration testsThe integration tests report. In parenthesis the package type is given, and 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

@TrueAstralpirate TrueAstralpirate force-pushed the feature/optimizeSorting branch 2 times, most recently from 69e705a to f99b81a Compare May 9, 2023 13:46
.returns_single_stream = false,
.preserves_number_of_streams = true,
.preserves_sorting = false,
.preserves_data_hints = false,
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'm not sure how array join could change min/max values?

.returns_single_stream = false,
.preserves_number_of_streams = true,
.preserves_sorting = true,
.preserves_data_hints = false,
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.

also should be true I think

.returns_single_stream = true,
.preserves_number_of_streams = false,
.preserves_sorting = false,
.preserves_data_hints = false,
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 guess it preserves for columns that are present in output header

getTraits(actions_dag_, input_stream_.header, input_stream_.sort_description))
, actions_dag(actions_dag_)
{
/// For now we only preserve hints of untouched columns
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.

this comment should be by the function definition/implementation or it will start lying as soon as smth change

, filter_column_name(std::move(filter_column_name_))
, remove_filter_column(remove_filter_column_)
{
for (const auto & output_node_ptr : actions_dag->getOutputs())
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.

it seems not enough, because inside the action dag might happen all sorts of things. including aliases and some non-monotonic functions.
so I think we should first check that there is nothing harmful and if so just apply it to lower and upper bound to see what they'll become.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

But it is a filter, not an expression, how can I "apply" it to something? It will return either True or False.
What's going on here: inside updateDataHintsWithFilterActionsDAG I find INPUT columns (not ALIAS), and then try to build restrictions on such columns via <, >, <=, >= predicates with AND.

Comment on lines +108 to +109
output_stream->hints = input_streams[0].hints;
unionJoinDataHints(output_stream->hints, input_streams[1].hints, join->getTableJoin());
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.

just would be more accurate

Suggested change
output_stream->hints = input_streams[0].hints;
unionJoinDataHints(output_stream->hints, input_streams[1].hints, join->getTableJoin());
output_stream->hints = unionJoinDataHints(input_streams[0].hints, input_streams[1].hints, join->getTableJoin());

.returns_single_stream = should_produce_results_in_order_of_bucket_number,
.preserves_number_of_streams = false,
.preserves_sorting = false,
.preserves_data_hints = false,
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.

also should preserve for key columns

prewhere_info,
enable_vertical_final);

/// Build data hints for output stream
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.

same comment as in FilterStep

.returns_single_stream = true,
.preserves_number_of_streams = false,
.preserves_sorting = false,
.preserves_data_hints = false,
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.

should preserve for key columns

updateOutputDataHints();
}

void UnionStep::updateOutputDataHints()
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.

does it really deserves a separate member function?

@nickitat
Copy link
Copy Markdown
Member

nickitat commented Feb 14, 2024

I think it would be valuable now to support propagation of hints through more steps to get more coverage in tests.
in the meantime I'll start looking into the core changes

Comment on lines +110 to +121
auto * rollup_step = typeid_cast<RollupStep *>(node->step.get());
if (rollup_step)
return 0;

auto * cube_step = typeid_cast<CubeStep *>(node->step.get());
if (cube_step)
return 0;

auto * totals_having_step = typeid_cast<TotalsHavingStep *>(node->step.get());
if (totals_having_step)
return 0;

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.

look redundant

Comment on lines +131 to +132
if (aggregating_node->children.size() != 1)
return 0;
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.

it is not possible afaik, could be converted to chassert(...)


}

size_t tryReduceAggregationKeysSize(QueryPlan::Node * node, QueryPlan::Nodes & nodes)
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 create a comment describing the transformation. there are tools like https://asciiflow.com/ that allow to create a visual scheme using ascii charset.
in general we like to write comments.


if (type_name == "UInt8" || type_name == "Int8" || type_name == "UInt16" || type_name == "Int16")
{
new_aggregating_keys.push_back(old_key);
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.

looking at l.155-156 it seems that new_aggregating_keys and changed_aggregating_keys are supposed to be of the same size. but it will not be true if we got into this branch, right?

predecessor_node.children = {next_node};
predecessor_node.step = std::make_unique<ExpressionStep>(input_stream, predecessor_dag);

std::unordered_map<std::string, std::string> changed_to_new_key_mapping;
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
std::unordered_map<std::string, std::string> changed_to_new_key_mapping;
std::unordered_map<std::string, std::string> changed_to_new_key_mapping;
chassert(changed_aggregating_keys.size() == new_aggregating_keys.size());


changed_data_types.push_back(key_column_type);
ColumnWithTypeAndName const_column;
if (hint.lower_boundary->getTypeName() == "Int64")
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.

what if it is some other signed type?


ActionsDAG::NodeRawConstPtrs children = {node_to_remove, hint_node};
auto plus_function = FunctionFactory::instance().get("plus", Context::getGlobalContextInstance());
dag->addOrReplaceInOutputs(dag->addCast(dag->addFunction(plus_function, children, "__uncasted_" + changed_key), changed_data_type, changed_key));
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.

so, in the output header we will have original columns names back, right?


void AggregatingStep::updateParams(const Names & new_keys, const std::unordered_map<std::string, std::string> & changed_to_new_key_mapping)
{
params.keys = new_keys;
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.

that is very slippery road. we store argument column names in many places, e.g. here and here. why it works now btw?)
I think it might be safer to alias columns on themselves. like select x - 100 as x. I remember we discussed it some time ago, could you pls remember what we come up with?

sorting_step->updateInputStream(predecessor_node.step->getOutputStream());

sorting_node->children = {&predecessor_node};

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.

two points here:

  1. let's create a post-step that will drop col - hint.min column in order to preserve the original header
  2. what sort description will the new expression step propagate? probably one with the col - hint.min column? again better to restore everything back to original sort description

Comment on lines +395 to +397
for (size_t i = 254; i > 0; --i)
cnt[i] += cnt[i + 1];
cnt[0] += cnt[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.

Suggested change
for (size_t i = 254; i > 0; --i)
cnt[i] += cnt[i + 1];
cnt[0] += cnt[1];
for (ssize_t i = 254; i >= 0; --i)
cnt[i] += cnt[i + 1];

memset(cnt, 0, sizeof(cnt));

for (auto * it = begin; it != end; ++it)
cnt[data[*it]]++;
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.

maybe we should write here at data[*it] +- 1 to avoid shifting array by one below.

@clickhouse-gh
Copy link
Copy Markdown
Contributor

clickhouse-gh bot commented Jun 25, 2024

Dear @nickitat, this PR hasn't been updated for a while. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@alexey-milovidov alexey-milovidov mentioned this pull request Dec 31, 2024
76 tasks
@nickitat nickitat self-assigned this Feb 27, 2025
@EmeraldShift
Copy link
Copy Markdown
Contributor

I'm curious to learn about this PR, but I don't know what it means. What's a short summary of what this PR is doing? How will it improve performance, and for what kinds of queries?

@clickhouse-gh
Copy link
Copy Markdown
Contributor

clickhouse-gh bot commented Apr 22, 2025

Dear @nickitat, this PR hasn't been updated for a while. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@thevar1able thevar1able self-assigned this Dec 3, 2025
@alexey-milovidov alexey-milovidov mentioned this pull request Dec 31, 2025
72 tasks
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-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants