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

Analyzer: Optimize resolution of in(LowCardinality, ConstantSet) #64060

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

ZhiguoZh
Copy link
Contributor

When the FunctionIn applies to a LowCardinality and a constant set, its return type is expected to be resolved as LowCardinality also so that its argument of LowCardinality column would not be converted to a full one and much computation cost for iterating the rows in DB::Set::executeImplCase could be saved during the execution phase.

This condition is fulfilled when FunctionNode::getArgumentColumns returns a LowCardinality column for FunctionIn's 1st argument, and a ColumnConst for the other. However, it's actually unfulfilled as a null column is returned for the 2nd argument instead in the Analyzer.

This commit revised FunctionNode::getArgumentColumns to return a ColumnConst(ColumnSet) in such cases in order to turn on the optimization of LowCardinality. A significant performance gain of 1.39x is observed in query 3.3 of Star Schema Benchmark on the Intel ICX server with 160 vcpus.

Changelog category (leave one):

  • Performance Improvement

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

The queries of 3.3, 3.4, 4.1 and 4.2 from Star Schema Benchmark share a common pattern of predicate: col = a or col = b where col is a LowCardinality(String). And during syntax optimization, this predicate is then transformed equivalently to col in (a, b), which is executed by FunctionIn with col and a constant tuple (a, b) as its arguments.

The return type of in(LowCardinality, ConstantSet) determines its execution flow: if it is non-LowCardinality, FunctionIn's LowCardinality argument would be converted to a full column and the Set operations on the full column would be much more expensive. And this optimization works by rectifying this function's return type.

The performance experiments of SSB on the ICX device (Intel Xeon Platinum 8380 CPU, 80 cores, 160 threads) show that this change could bring the improvements of 39.3%, 2.8%, 2.6% and 1.2% to the QPS of the query 3.3, 3.4, 4,1, and 4.2 respectively while having no impact on others.

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

Modify your CI run

NOTE: If your merge the PR with modified CI you MUST KNOW what you are doing
NOTE: Checked options will be applied if set before CI RunConfig/PrepareRunConfig step

Include tests (required builds will be added automatically):

  • Fast test
  • Integration Tests
  • Stateless tests
  • Stateful tests
  • Unit tests
  • Performance tests
  • All with ASAN
  • All with TSAN
  • All with Analyzer
  • All with Azure
  • Add your option here

Exclude tests:

  • Fast test
  • Integration Tests
  • Stateless tests
  • Stateful tests
  • Performance tests
  • All with ASAN
  • All with TSAN
  • All with MSAN
  • All with UBSAN
  • All with Coverage
  • All with Aarch64
  • Add your option here

Extra options:

  • do not test (only style check)
  • disable merge-commit (no merge from master before tests)
  • disable CI cache (job reuse)

Only specified batches in multi-batch jobs:

  • 1
  • 2
  • 3
  • 4

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label May 17, 2024
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-performance Pull request with some performance improvements label May 17, 2024
@robot-ch-test-poll3
Copy link
Contributor

robot-ch-test-poll3 commented May 17, 2024

This is an automated comment for commit 8440017 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
Mergeable CheckChecks if all other necessary checks are successful❌ failure
Stateful testsRuns stateful functional tests for ClickHouse binaries built in various configurations -- release, debug, with sanitizers, etc❌ failure
Unit testsRuns the unit tests for different release types❌ error
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
Integration testsThe integration tests report. In parenthesis the package type is given, and in square brackets are the optional part/total tests✅ 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
Stateless testsRuns stateless 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
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

@ZhiguoZh ZhiguoZh force-pushed the 20240517-low-cardinality-opt branch from 428f851 to 8440017 Compare May 21, 2024 01:45
When the FunctionIn applies to a LowCardinality and a constant
set, its return type is expected to be resolved as LowCardinality
also so that its argument of LowCardinality column would not be
converted to a full one and much computation cost for iterating
the rows in DB::Set::executeImplCase could be saved during the
execution phase.

This condition is fulfilled when FunctionNode::getArgumentColumns
returns a LowCardinality column for FunctionIn's 1st argument,and
a const column for the other. However, it's actually unfulfilled
as a null column is returned for the 2nd argument instead in the
Analyzer.

This commit revised FunctionNode::getArgumentColumns to return a
ColumnConst(ColumnSet) in such cases in order to turn on the opti-
mization of LowCardinality. A significant performance gain of 1.39x
is observed in query 3.3 of Star Schema Benchmark on the Intel ICX
server with 160 vcpus.
For `k::LowCardinality(UInt8)`, the resolution of `k IN (1, NULL)`
results in type LowCardinality(UInt8). This commit converts the
return type to LowCardinality(Nullable(UInt8)).
@ZhiguoZh
Copy link
Contributor Author

The reported issues (timeout, binary_tidy, etc.) seem not related to this code change. I think this PR is ready for your review. Thanks in advance for your help!

@ZhiguoZh
Copy link
Contributor Author

Hi Nikita, thanks for your interest into this work! Could you kindly review this PR also? Thanks again for your help!

@nikitamikhaylov

{
/// Created but not filled for the analysis during function resolution.
FutureSetPtr empty_set;
argument_column.column = ColumnConst::create(ColumnSet::create(1, empty_set), 1);
Copy link
Member

Choose a reason for hiding this comment

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

Could you please point out where is it used during analysis? Can't it be constant-folded ? If yes, shouldn't it contain real value instead of empty set?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The second argument of FunctionIn is required to be a ColumnConst to resolve the return type as a LowCardinality column (IFunctionOverloadResolver::getReturnType), and the ColumnSet, though not necessary in the function resolution, is used here as a placeholder to denote its data type. And it's implemented as an empty set as its value is found not used in the later phases: after the build of the query tree, the CollectSetsVisitor would collect the sets in the query to execute IN function and place them in the planner_context.prepared_sets, through which the ColumnSet is created and filled as the argument of the ActionDAG::Node in PlannerActionsVisitorImpl::makeSetForInFunction.

And I think containing the real value may not aid the constant-folding optimization, as unlike 1 IN 1, where both arguments are constant, this pattern has one column argument, which prevent the result of the FuncionIn being determined at the query's compile time. We also implemented one POC of filling the FutureSet with the real value in current stage, but found no difference in the query plan and even observed slight performance regressions.

But I'm not sure if there are alternative ways for achieving the constant-fold or the POC follows the suggested approach. Could you further share with me your insights? Thanks!

@vdimir vdimir requested a review from novikd May 24, 2024 13:47
@novikd novikd self-assigned this May 24, 2024
@ZhiguoZh
Copy link
Contributor Author

ZhiguoZh commented May 29, 2024

Hi Dmitry, thanks so much for your review! As I'm actually not sure if this optimization make sense and the next steps for pushing it forward, it will be great if you could share with me your insights once the review is completed. Thanks!

And to make the motivation clearer, here attaches the snippets of the function hotspots of the baseline (Fig 1) and optimized binaries (Fig 2), when both of them execute Q3.3 for the exact iterations. They combinedly show that the total cycles for executing this query reduces by 36.03% and cycle ratios of Set::executeImplCase and ColumnString::indexImpl, which were originally 20.95% and 17.11%, now shrink to 0.37% and 0.04%, disappearing in the top list of hotspots. The reduction in the CPU cycles is believed the origin of this significant performance gain.

image
Fig 1. Set::executeImplCase and ColumnString::indexImpl consume extraordinary CPU cycles

image
Fig 2. Function hotspots with this optimization, reduction of 36.03% in the CPU cycles

@novikd

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.

None yet

5 participants