Skip to content

feat: add DDSketch quantile#56342

Merged
al13n321 merged 65 commits into
ClickHouse:masterfrom
srikanthccv:ddsketch-quantile
Jan 18, 2024
Merged

feat: add DDSketch quantile#56342
al13n321 merged 65 commits into
ClickHouse:masterfrom
srikanthccv:ddsketch-quantile

Conversation

@srikanthccv

@srikanthccv srikanthccv commented Nov 5, 2023

Copy link
Copy Markdown
Contributor

Fixes #6739

Changelog category (leave one):

  • New Feature

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

Add quantileDDSketch aggregate function as well as the corresponding quantilesDDSketch and medianDDSketch. It is based on the DDSketch https://www.vldb.org/pvldb/vol12/p2195-masson.pdf.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

  • Motivation: It is very important to calculate accurate quantiles fast. The OpenTelemetry project is the emerging standard in the observability ecosystem, and the preferred way to record the latencies is ExponentialHistogram. Having this feature in ClickHouse makes it more adaptable.

  • Parameters: relative accuracy

  • Example use:

SELECT quantileDDSketch(0.01, 0.42)(number)
FROM numbers_mt(1000000000)

Query id: 0f273858-44eb-4359-9108-198f0179fc5e

┌─quantileDDSketch(0.01, 0.42)(number)─┐
│                   417841070.41428167 │
└──────────────────────────────────────┘
CREATE TABLE default.comparision
(
    `id` UInt64,
    `sketch` AggregateFunction(quantilesDDSketch(0.02, 0.9), UInt64),
    `td` AggregateFunction(quantilesTDigest(0.5, 0.9, 0.99), UInt64),
    `bf` AggregateFunction(quantilesBFloat16(0.5, 0.9, 0.99), UInt64)
)
ENGINE = SummingMergeTree
ORDER BY id
SETTINGS index_granularity = 8192


insert into comparision
select
    number % 10000 as id,
    quantilesDDSketchState(0.02, 0.9)(number) as sketch,
    quantilesTDigestState(0.5, 0.9, 0.99)(number) as td,
    quantilesBFloat16State(0.5, 0.9, 0.99)(number) as bf  
from numbers(100000000)
group by id;


SELECT
    quantilesDDSketchMerge(0.02, 0.9)(sketch) AS sketch
FROM comparision

SELECT
    quantileTDigestMerge(0.9)(td) AS td
FROM comparision

SELECT
    quantileBFloat16Merge(0.9)(bf) AS bf
FROM comparision

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

@srikanthccv

Copy link
Copy Markdown
Contributor Author

@SmitaRKulkarni I had to close this #55305 because of a messed up rebase. Please review this instead. I added the docs and address comments from the other PR

@srikanthccv

Copy link
Copy Markdown
Contributor Author

I would appreciate it if someone could trigger workflows.

@den-crane den-crane added the can be tested Allows running workflows for external contributors label Nov 5, 2023
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-feature Pull request with new product feature label Nov 5, 2023
@robot-ch-test-poll2

robot-ch-test-poll2 commented Nov 5, 2023

Copy link
Copy Markdown
Contributor

This is an automated comment for commit 068f6e2 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 image for serversThe 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
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
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
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

@SmitaRKulkarni SmitaRKulkarni self-assigned this Nov 6, 2023
@srikanthccv

srikanthccv commented Nov 6, 2023

Copy link
Copy Markdown
Contributor Author

2023.11.06 11:36:06.177838 [ 895 ] {80ce4c2c-097e-47a1-8870-042595f45cd7} : Logical error: 'std::exception. Code: 1001, type: std::length_error, e.what() = vector (version 23.11.1.1), Stack trace:
2023.11.06 11:36:06.178402 [ 921 ] {} BaseDaemon: ########## Short fault info ############
2023.11.06 11:36:06.178441 [ 921 ] {} BaseDaemon: (version 23.11.1.1, build id: 548B41F3A0C69477122CCC46FB1DC905F5EA412C, git hash: 47efee857a245ba5f5a79a11eb1bbfa4b2bebb70) (from thread 895) Received signal 6
2023.11.06 11:36:06.178469 [ 921 ] {} BaseDaemon: Signal description: Aborted
2023.11.06 11:36:06.178489 [ 921 ] {} BaseDaemon:
2023.11.06 11:36:06.178518 [ 921 ] {} BaseDaemon: Stack trace: 0x00007f5df92f69fc 0x00007f5df92a2476 0x00007f5df92887f3 0x00005574a14112c8 0x00005574a141e055 0x00005574a14218f1 0x00005574b96432dd 0x00005574b966d967 0x00005574a16fff49 0x00005574a170e48d 0x000055748e2f70ab 0x00007f5df92f4ac3 0x00007f5df9386a40
2023.11.06 11:36:06.178546 [ 921 ] {} BaseDaemon: ########################################
2023.11.06 11:36:06.178616 [ 921 ] {} BaseDaemon: (version 23.11.1.1, build id: 548B41F3A0C69477122CCC46FB1DC905F5EA412C, git hash: 47efee857a245ba5f5a79a11eb1bbfa4b2bebb70) (from thread 895) (query_id: 80ce4c2c-097e-47a1-8870-042595f45cd7) (query: SELECT arrayMap(a -> round(0), quantilesDDSketch(1.1754943508222875e-38, 0, 0.001, 1., 1.1754943508222875e-38, 0.1, 1.1920928955078125e-7, 0.9999, 0.4, -0., -0., 0.9999, 0.5, 0.0001, 1.1920928955078125e-7, 0.999, 1)(x)) FROM (SELECT number AS x FROM system.numbers LIMIT 65536)) Received signal Aborted (6)

How can I get the fuzzer to pass a reasonable relative accuracy? The value 1.1754943508222875e-38 (understandably) crashes the build. I am thinking of throwing an exception in case of provided relative accuracy is too low. I think most practical applications will be fine with something like 0.0003 i.e. no more than 0.03%. Let me know what you think.

@bharatnc

bharatnc commented Nov 9, 2023

Copy link
Copy Markdown
Contributor

How can I get the fuzzer to pass a reasonable relative accuracy? The value 1.1754943508222875e-38 (understandably) crashes the build. I am thinking of throwing an exception in case of provided relative accuracy is too low. I think most practical applications will be fine with something like 0.0003 i.e. no more than 0.03%. Let me know what you think.

It looks like the msan fuzzer builds indicate possible memory violations here: src/AggregateFunctions/QuantileDDSketch.h:25 and here src/AggregateFunctions/QuantileDDSketch.h:31.

@srikanthccv

Copy link
Copy Markdown
Contributor Author

SELECT round(quantileDDSketch(1.1754943508222875e-38)(number)) FROM numbers(255) GROUP BY -2 / (number + 3) WITH ROLLUP

They are failing because the passed relative accuracy is too low which demands bins beyond allocatable and program crashes. If you change the relative accuracy to a reasonable value it works without crashing.

@srikanthccv

Copy link
Copy Markdown
Contributor Author

QuantileBFloat16 test is failing for ubsan, ParallelReplicas and QuantileDDSketch if failing for ubsan. It seems like a timeout. How can I troubleshoot or are they occasional intermittent failures?

@srikanthccv

Copy link
Copy Markdown
Contributor Author

I will resolve the conflicts

@bharatnc

Copy link
Copy Markdown
Contributor

QuantileBFloat16 test is failing for ubsan, ParallelReplicas and QuantileDDSketch if failing for ubsan. It seems like a timeout. How can I troubleshoot or are they occasional intermittent failures?

I think QuantileBFloat16 test failure is un-related, it's failing because its not able to connect to the server (likely the server has crashed from the other test failure.)

The main error seems to be the following

SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /build/src/AggregateFunctions/Store.h:106:35 in 

Possible overflows are happening here during addition. Probably, the easiest way is to fix is to use NO_SANITIZE_UNDEFINED (i.e. to suppress undefined behavior sanitizer) in the function signature of serialize. Here is an example for this. There are also arithmeticOverflow helper functions that basically do the same (suppresses the UBSAN) to handle the overflows for you while doing arithmetic operations. Better way is to actually handle overflows without suppressing the UBSAN if you're able to do so realistically .

@srikanthccv

Copy link
Copy Markdown
Contributor Author

@bharatnc Thanks, that was helpful. I saw other files but didn't pay attention to stderr.log. This happens when the store is empty. I pushed a fix (check for the empty state) to solve it.

Comment thread src/AggregateFunctions/DDSketch/Store.h Outdated
Comment thread src/AggregateFunctions/DDSketch/Store.h Outdated
@al13n321

al13n321 commented Jan 9, 2024

Copy link
Copy Markdown
Member

I don't have solid expertise with C++. Few suggestions from the previous review didn't make much difference. I will be happy to make changes if it gives such a significant improvement.

I would do something like this: https://pastila.nl/?0052513d/409c97e2bb061b060eacf41ae73ceae2#IkYx5MhJoZnbPjohZ4NQNw== (untested), on the off chance you're in the mood for rewriting everything.

Comment thread src/AggregateFunctions/DDSketch/Store.h Outdated
@srikanthccv

Copy link
Copy Markdown
Contributor Author

I don't have solid expertise with C++. Few suggestions from the previous review didn't make much difference. I will be happy to make changes if it gives such a significant improvement.

I would do something like this: https://pastila.nl/?0052513d/409c97e2bb061b060eacf41ae73ceae2#IkYx5MhJoZnbPjohZ4NQNw== (untested), on the off chance you're in the mood for rewriting everything.

I will give it a try. If you believe it could improve the performance by multifold I want to give it a try.

@srikanthccv

Copy link
Copy Markdown
Contributor Author
   /// (No need to write mapping and scale, they're determined by parameters, which should match
    ///  between serializer and deserializer. Unless again you need to be compatible with some
    ///  other system for some reason. No need for changeMapping() for the same reason.
    ///  Unless I'm missing something?)

To give some clarity on this, I was trying to keep the state compatible with the DDSketch proto https://github.com/DataDog/sketches-java/blob/master/src/protobuf/proto/DDSketch.proto. The clickHouse-go client would directly write the rows with the compatible serialized state. This will enable ingesting the pre-aggregated sketches (usually on the web service application) and then computing percentiles at the query time.

@al13n321

al13n321 commented Jan 9, 2024

Copy link
Copy Markdown
Member

I will give it a try. If you believe it could improve the performance by multifold I want to give it a try.

Cool! Hack a quick prototype first, to check if it's really fast enough to be worth rewriting the rest. (Though it's also less code, so might be worth rewriting even if not much faster, but that's less important and more subjective.)

@al13n321

al13n321 commented Jan 9, 2024

Copy link
Copy Markdown
Member
   /// (No need to write mapping and scale, they're determined by parameters, which should match
    ///  between serializer and deserializer. Unless again you need to be compatible with some
    ///  other system for some reason. No need for changeMapping() for the same reason.
    ///  Unless I'm missing something?)

To give some clarity on this, I was trying to keep the state compatible with the DDSketch proto https://github.com/DataDog/sketches-java/blob/master/src/protobuf/proto/DDSketch.proto. The clickHouse-go client would directly write the rows with the compatible serialized state. This will enable ingesting the pre-aggregated sketches (usually on the web service application) and then computing percentiles at the query time.

Makes sense, please add a comment about it in the code, with the link. Otherwise it just looks like random crazy overengineering tbh :)

@srikanthccv

Copy link
Copy Markdown
Contributor Author

@al13n321 I tried the suggestion in a separate branch and it improved the performance by ~20%. And then I revisited your comment here about the virtual functions #56342 (comment). The last time when I added final it didn't make a difference but I removed the inheritance and virtual functions and that change also improved the performance, i.e. ~20%. I pushed the updated changes, please take a look again.

@srikanthccv

Copy link
Copy Markdown
Contributor Author

I started looking into small object optimization. Is it okay if that is addressed in the follow-up PR? This has gone through many changes at this point and has been reviewed. Since it will be an enhancement that doesn't break anything, I think it's better to address it in a follow-up PR without adding more new changes to this already reviewed PR. Let me know what do you think?

@alexey-milovidov

Copy link
Copy Markdown
Member

@srikanthccv, totally ok.

@al13n321

al13n321 commented Jan 18, 2024

Copy link
Copy Markdown
Member

Looks mergable, except for the fuzzer failure from before: https://s3.amazonaws.com/clickhouse-test-reports/56342/b55529b5850abc4cc3578b96582c92476c1b558a/fuzzer_astfuzzerubsan/report.html - did you explain or fix it? It didn't happen this time, but I don't see anything that looks like a fix, so it's probably not fixed and will come back.

Maybe try to reproduce it by running the last few queries with substring "DDSketch" from fuzzer.log and server.log.zst (from the link above), in UBSAN build (or with a manual overflow check for the particular subtraction that overflowed). If that doesn't work, just add an overflow check in getNewLength(), and we'll hope that my explanation in #56342 (comment) is correct.

@srikanthccv

Copy link
Copy Markdown
Contributor Author

hmm, I posted a comment before resolved but it seems to have been not delivered.

@al13n321 The commit I made which caused the overflow was an incorrect change and shouldn't have been committed.

Here is what happened. The new_length returned occasionally would be smaller than the length of the current bins after the suggestion bins.resize(bins.capacity()); is incorporated - the size of the current bins is enough to adjust the layout. Originally there was no check before resizing and as a result, some previous counts got wiped out. I added the check in this commit d831792 (#56342). The overflow shouldn't happen the keys are going to be well within the range. We do not allow relative accuracy no less than 1e-6. So the max possible value is 1.79769e+308 and it's the corresponding key is 354891355 so we are fine. Let me know if this answers your question.

@al13n321
al13n321 dismissed alexey-milovidov’s stale review January 18, 2024 03:50

All requested things are done.

@al13n321
al13n321 merged commit c23c7e0 into ClickHouse:master Jan 18, 2024
@srikanthccv

Copy link
Copy Markdown
Contributor Author

@al13n321 @alexey-milovidov @bharatnc Thanks for the reviews and help. I will send a follow-up PR for small object optimization after testing against the ClickBench data.

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-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

DDSketch Quantiles

7 participants