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

make nulls direction configuable for FullSortingMergeJoin #60896

Merged
merged 5 commits into from Mar 21, 2024

Conversation

loudongfeng
Copy link
Contributor

@loudongfeng loudongfeng commented Mar 6, 2024

Changelog category (leave one):

  • Improvement

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

Add a flag for SMJ to treat null as biggest/smallest. So the behavior can be compitable with other SQL systems, like Apache Spark.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

@CLAassistant
Copy link

CLAassistant commented Mar 6, 2024

CLA assistant check
All committers have signed the CLA.

Copy link
Member

@vdimir vdimir left a comment

Choose a reason for hiding this comment

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

Thanks for your work on ClickHouse!

Could you please add more details about use-case?
Generally, NULLs should not affect join, because they are never joined.
In case you would like to have specific NULLs direction after join, you may just add ORDER BY with specific modifier, but join itself does not guarantee an order

@loudongfeng
Copy link
Contributor Author

Thanks for you attention.
Actually, the use case is not for ClickHouse user, but for developers who want to use ClickHouse as a vectorization library.
For example, in Apache Gluten, we accelerate spark's Sort Merge Join by offloading it into ClickHouse 's SortingStep and JoinStep with FullSortingMergeJoin. The SortingStep offloading is optional(which means sorting can be done in spark's SortExec in nulls smallest order and then pass data to CH's FullSortingMergeJoin), so we need assign null orders for FullSortingMergeJoin in that case.
From ClickHouse's point of view, it's just an internal API richness.

Copy link
Member

@vdimir vdimir left a comment

Choose a reason for hiding this comment

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

Let's then simply add an argument to the MergeJoinAlgorithm and define it as a constant somewhere outside. This will meet your requirements without introducing significant changes. Especially, adding it as a template argument is questionable since it increases the binary size, but nullableCompareAt already has a runtime argument now.

@@ -356,7 +359,7 @@ void MergeJoinAlgorithm::consume(Input & input, size_t source_num)
cursors[source_num]->setChunk(std::move(input.chunk));
}

template <JoinKind kind>
template <JoinKind kind, NullOrder nullOrder>
Copy link
Member

Choose a reason for hiding this comment

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

Can't we pass direction as a value?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

fixed

@@ -880,6 +880,7 @@ class IColumn;
M(Int64, ignore_cold_parts_seconds, 0, "Only available in ClickHouse Cloud", 0) \
M(Int64, prefer_warmed_unmerged_parts_seconds, 0, "Only available in ClickHouse Cloud", 0) \
M(Bool, iceberg_engine_ignore_schema_evolution, false, "Ignore schema evolution in Iceberg table engine and read all data using latest schema saved on table creation. Note that it can lead to incorrect result", 0) \
M(Bool, nulls_biggest_in_smj, true, "Treat nulls as biggest in sort. Used in sort merge join for compare null keys.", 0) \
Copy link
Member

Choose a reason for hiding this comment

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

Let's not expose it to user

Copy link
Contributor Author

Choose a reason for hiding this comment

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

fixed

@loudongfeng
Copy link
Contributor Author

Hi vdimir, thanks for your review.
I have remove the template argument as you suggested.
But i'm not sure how to fix this one:

Let's then simply add an argument to the MergeJoinAlgorithm and define it as a constant somewhere outside.

Do you mean no changes in JoinStep,QueryPipelineBuilder,MergeJoinTransform etc and only add a runtime argument for MergeJoinAlgorithm?
But how to use a constant to set null_direction_hint, since it is unchangable.
Sample code that gluten uses to offloading SMJ to ClickHouse library:

JoinPtr smj_join = std::make_shared<FullSortingMergeJoin>(table_join, right->getCurrentDataStream().header.cloneEmpty());
QueryPlanStepPtr join_step
                 = std::make_unique<DB::JoinStep>(left->getCurrentDataStream(), right->getCurrentDataStream(), smj_join, 8192, 1, false);

@vdimir vdimir added the can be tested Allows running workflows for external contributors label Mar 12, 2024
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-improvement Pull request with some product improvements label Mar 12, 2024
@robot-ch-test-poll2
Copy link
Contributor

robot-ch-test-poll2 commented Mar 12, 2024

This is an automated comment for commit 96e9043 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
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
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❌ failure
Integration testsThe integration tests report. In parenthesis the package type is given, and in square brackets are the optional part/total tests❌ failure
Mergeable CheckChecks if all other necessary checks are successful❌ failure
Stateless testsRuns stateless functional tests for ClickHouse binaries built in various configurations -- release, debug, with sanitizers, etc❌ failure
Successful checks
Check nameDescriptionStatus
A SyncThere's no description for the check yet, please add it to tests/ci/ci_config.py:CHECK_DESCRIPTIONS✅ success
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
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
PR CheckThere's no description for the check yet, please add it to tests/ci/ci_config.py:CHECK_DESCRIPTIONS✅ 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
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

@vdimir
Copy link
Member

vdimir commented Mar 12, 2024

Yes I mean just like that

auto null_direction = getNullDirection();

JoinPtr smj_join = std::make_shared<FullSortingMergeJoin>(table_join, right->getCurrentDataStream().header.cloneEmpty(), null_direction);
QueryPlanStepPtr join_step
                 = std::make_unique<DB::JoinStep>(left->getCurrentDataStream(), right->getCurrentDataStream(), smj_join, 8192, 1, false);

Also, to be honest I don't fully understand how it can be useful, because handling nulls is FullSortingMergeJoin implementation detail, and if you need particular order after that you may want add specific step further.

@loudongfeng
Copy link
Contributor Author

Particular null order after join does not matter, but null order before Join matters.
I find nulls smaller/bigger matters after digging a result mismatch issue in gluten. Here is the case

-- a simple table
CREATE TABLE item (
  i_current_price DECIMAL(7,2),
  i_category STRING)
USING parquet;

-- data with nulls
insert into item values
(null,null),
(null,null),
(0.63,null),
(0.74,null),
(null,null),
(90.72,'Books'),
(99.89,'Books'),
(99.41,'Books');


-- the following SQL will use SMJ with join type Left Outer
-- expected result is 2, but gluten returns 0 when offloading to ClickHouse
-- notice there are nulls in join key 'i_category'
SELECT  count(*) cnt
FROM item i
where
i.i_current_price > 1.0 *
  (SELECT avg(j.i_current_price)
  FROM item j
  WHERE j.i_category = i.i_category
 )

The reason is sort node's order is asc and nulls first (both in Spark and ClickHouse's SortStep), but FullSortingMergeJoin joins streams treating data in asc order and nulls last. FullSortingMergeJoin will stop when find left/right table start with null, I think. Simply changing null direction in FullSortingMergeJoin can fix it.

@loudongfeng
Copy link
Contributor Author

CI failures seems unrelated. Ready for review.
Thanks, @vdimir

@vdimir
Copy link
Member

vdimir commented Mar 21, 2024

Thanks for your effort on the PR!

@vdimir vdimir merged commit 9b51780 into ClickHouse:master Mar 21, 2024
210 of 218 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Mar 21, 2024
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-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.

None yet

5 participants