Skip to content

Apache DataSketches Support for Cross-Service Sketch Interoperability & Analytics - #95045

Open
MaheshGPai wants to merge 87 commits into
ClickHouse:masterfrom
MaheshGPai:mahesh_pr
Open

MaheshGPai wants to merge 87 commits into
ClickHouse:masterfrom
MaheshGPai:mahesh_pr

Conversation

@MaheshGPai

@MaheshGPai MaheshGPai commented Jan 24, 2026 •

Copy link
Copy Markdown

Closes: #95046

Add Apache DataSketches-compatible HLL, quantiles, and TDigest aggregate and scalar functions for importing, merging, and extracting metrics from externally produced sketches.

Changelog category (leave one):

  • New Feature

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

Add Apache DataSketches-compatible HLL, quantiles, and TDigest sketch functions for cross-service sketch import, merging, and metric extraction.


Workflow [PR]
Sync PR [sync-upstream/pr/95045]

@CLAassistant

CLAassistant commented Jan 24, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@clickhouse-gh

clickhouse-gh Bot commented Jan 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [855237b]

Summary: ❌

job_name test_name status info comment
Build (arm_tidy, 1/4) FAIL
Build ClickHouse FAIL cidb
Build (arm_tidy, 2/4) FAIL
Build ClickHouse FAIL cidb
Build (arm_tidy, 3/4) FAIL
Build ClickHouse FAIL cidb
Build (arm_tidy, 4/4) FAIL
Build ClickHouse FAIL cidb
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED

AI Review

⚠️ Review sessions stopped as a cybersecurity risk

The model provider stopped these review sessions as a possible cybersecurity risk:

  • attempt 1: gpt-6.1-sol

This summary comes from a session with gpt-5.4. A session is typically stopped when it reaches a memory-safety finding, and the finding is lost with it, so this review can miss a real defect. Please review the change in detail, and run the review internally with a model that has cyber access.

Summary

This PR adds Apache DataSketches-based serialized* / mergeSerialized* aggregates plus scalar extractors for HLL, Quantiles, and TDigest, and most of the earlier interoperability and failure-mode issues look addressed in the current head. I still see one remaining contract problem: serializedQuantiles and serializedTDigest accept 128/256-bit integers but immediately coerce them to Float64, so distinct large integers can collapse before they ever reach the sketch.

Findings

⚠️ Majors

  • [src/AggregateFunctions/AggregateFunctionSerializedQuantiles.cpp:53] [src/AggregateFunctions/AggregateFunctionSerializedQuantiles.cpp:93] [src/AggregateFunctions/AggregateFunctionSerializedTDigest.cpp:57] [src/AggregateFunctions/AggregateFunctionSerializedTDigest.cpp:97] These builders admit Int128 / UInt128 / Int256 / UInt256, but add reads every value through getFloat64. Above 2^53, adjacent integers are no longer uniquely representable as Float64, so different upstream values can collapse into the same serialized sketch input. Suggested fix: reject the wide integer types up front (matching the narrower quantileTDigest surface) or make the lossy coercion an explicit documented contract and cover it with regression tests.

💡 Nits

  • [src/AggregateFunctions/AggregateFunctionSerializedHLL.cpp:246] [src/AggregateFunctions/AggregateFunctionMergeSerializedHLL.cpp:309] [src/AggregateFunctions/AggregateFunctionMergeSerializedQuantiles.cpp:204] [src/AggregateFunctions/AggregateFunctionMergeSerializedTDigest.cpp:164] The structured FunctionDocumentation still leaves FunctionDocumentation::Parameters empty for these new functions, so the autogenerated pages from the new stubs will not explain the meaning, defaults, or ranges of lg_k, type, and base64_encoded. mergeSerializedHLL also documents only ([base64_encoded, lg_k, type]), even though the parser and tests intentionally support mergeSerializedHLL(10)(...), mergeSerializedHLL(14, 'HLL_4')(...), and mergeSerializedHLL(14, 'HLL_4', 1)(...) too.
Final Verdict

Status: ⚠️ Request changes

  • Narrow serializedQuantiles / serializedTDigest input validation so unsupported wide integers are rejected, or explicitly define and document the lossy Float64 coercion.
  • Add a focused regression using adjacent large wide integers (for example 2^53 and 2^53 + 1 in a UInt256 / Int256 column).

@alexey-milovidov

Copy link
Copy Markdown
Member

@clickhouse-gh clickhouse-gh Bot added pr-feature Pull request with new product feature submodule changed At least one submodule changed in this PR. labels Jan 26, 2026
@MaheshGPai
MaheshGPai force-pushed the mahesh_pr branch 7 times, most recently from a81e079 to 10a07f2 Compare January 26, 2026 14:12
@UnamedRus

UnamedRus commented Jan 26, 2026 •

Copy link
Copy Markdown
Contributor

Why not use combinators -Merge/-State for some custom aggregateFunction to implement behavior of serializedHLL/mergeSerializedHLL.
So, it would be more ~native look for ClickHouse.

@MaheshGPai

MaheshGPai commented Jan 26, 2026 •

Copy link
Copy Markdown
Author

Why not use combinators -Merge/-State for some custom aggregateFunction to implement behavior of serializedHLL/mergeSerializedHLL. So, it would be more ~native look for ClickHouse.

The merge functions provided are for merging sketches produced external to CH. For example, an upstream service can perform first level aggregation of data and insert sketches as bytes (either raw or base64 encoded)
They can be used also to merge sketches stored in external files (CSV, JSON, Parquets etc..)

@UnamedRus

UnamedRus commented Jan 26, 2026 •

Copy link
Copy Markdown
Contributor

The merge functions provided are for merging sketches produced external to CH.

I understand, but what is blocking us to interpret those sketches.
IE, merges of externally produced sketches and internally (if used) will have the same interface.

We just had success, with use cases where people generate/converting and importing in ClickHouse TDigest/(some other agg functions) state and use native functions. So, it should be doable.

@MaheshGPai

Copy link
Copy Markdown
Author

We just had success, with use cases where people generate/converting and importing in ClickHouse TDigest/(some other agg functions) state and use native functions. So, it should be doable.

I'm not familiar with that. If you can point me to an example, I can have a look.

@UnamedRus

Copy link
Copy Markdown
Contributor

As simplest example, centroids from TDigest:
https://kb.altinity.com/altinity-kb-functions/how-to-encode-decode-quantiletdigest-state/

So, basically i think there are several options exist:

  1. If logic of Apache DataSketches exactly match logic of function in ClickHouse, it make sense to implement regular CH function, which will convert from DataSketches State to CH state and back.
  2. If logic is different, set of new aggregate functions can be added, which will generate/use state like in DataSketches format. (afaik uniqThetaSketch was added in that way)

UnamedRus added a commit to UnamedRus/ClickHouse that referenced this pull request Oct 10, 2026
The HIP estimate and the bytes of the sketch depend on the order of the updates and of the merges, so the planner must keep an `ORDER BY` below the function and below its `-State`, `-Merge` and `-If` forms. The property was copied from `uniq`, whose result does not depend on the order.

Related: ClickHouse#95045

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: UnamedRus <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Continued on 2026-10-17: merged current master (6156 commits, no conflicts) and pushed d0203306131..1ebcc11dc2c to MaheshGPai:mahesh_pr. The PR diff is unchanged (57 files). Built clickhouse locally, and all 18 stateless tests this PR adds pass. All review threads are resolved. CI has not run on the new head yet: the PR needs manual approval.

@UnamedRus, thanks for #124667 (uniqApacheHLL, which imports and exports library-compatible states through -State/-Merge). It is the alternative design you suggested earlier, for the HLL part. The maintainers still have to choose between the two designs:

If #124667 is chosen, the HLL functions here (serializedHLL, mergeSerializedHLL, cardinalityFromHLL) should be dropped in favour of it, and this PR reduced to the Quantiles/TDigest parts or reworked the same way. I have not changed the design here while that decision is open.

Related: #124667

Resolve the `contrib/datasketches-cpp` submodule conflict by taking master's
`5.3.0` commit: merging `ClickHouse/5.3.0` into the PR's
`ClickHouse/5.2.0-tdigest-iterator` yields a tree identical to `5.3.0`, which
already contains the `tdigest` `const_iterator` and the `quantiles_sketch`
deserialization fix used by this PR.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Continued on 2026-10-21: merged current master and pushed 1ebcc11dc2c..60237c99f28 to MaheshGPai:mahesh_pr.

  • Conflict (the PR was CONFLICTING). Only contrib/datasketches-cpp: master moved it to upstream 5.3.0 (5b5524f), while this PR pointed at d71c42b (ClickHouse/5.2.0-tdigest-iterator). Merging 5.3.0 into that branch gives a tree identical to 5.3.0, so upstream already contains the tdigest const_iterator and the quantiles_sketch deserialization fix this PR needs. The submodule now points at master's commit, and the PR no longer changes contrib/datasketches-cpp (56 files in the diff, down from 57).
  • Verification. Built clickhouse locally from the merged tree; all 18 stateless tests this PR adds pass.
  • Review. No unresolved review threads. The alternative design in uniqApacheHLL aggregate function #124667 (from @UnamedRus) is still a decision for maintainers.

alexey-milovidov and others added 2 commits October 28, 2026 22:40
…infinite values

Quantiles sketches accept `+inf` / `-inf`, and `writeText` printed them as bare
`inf`, which is not valid JSON. Serialize values with `writeJSONNumber`, so
non-finite values are quoted as in the `JSON` output formats and still
round-trip through `JSONExtract`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=95045&sha=60237c99f2862bc82e097ae12871174a3852b7d8&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29 (Logical error: Context has expired in FunctionTimeSeriesStoreTags::executeImpl) and provide a fix in a separate PR. If the fix is already in progress, link it here. It looks like #126492 addresses it.

@groeneai

Copy link
Copy Markdown
Collaborator

This is the bug #126492 fixes. The stack here is WithContextImpl::getContext() <- FunctionTimeSeriesStoreTags::executeImpl (timeSeriesStoreTags.cpp:117, STID 1805-578d): since #104948 the function reads the tags collector through its weakly held creation context at execution time, and that context can already be gone when parallel replicas build a local plan from a cloned query tree. #126492 captures the collector in the constructor again (and does the same for timeSeriesTagsToGroup); its head is green and mergeable, and it has no review yet.

Not caused by this PR: the same abort hit the Stress tests of 12 other PRs in the last 30 days.

Comment thread src/AggregateFunctions/HLLSketchData.h Resolved
@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
alexey-milovidov and others added 3 commits November 5, 2026 09:01
… without parameters

`hll_union::update` ignores empty sketches, so merging only empty upstream
sketches without explicit `lg_k` / `type` re-emitted an empty sketch with the
default configuration. Track the configuration of empty inputs (smallest
`lg_k`, widest type, so it is order-independent) and use it when the union
result is empty.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Continued on 2026-11-05: pushed 8d4671ec68c5..1670e510e291 to MaheshGPai:mahesh_pr.

  • Review thread (empty sketches in mergeSerializedHLL). Fixed in ada1300, test added in 1670e51 (05508_datasketches_merge_hll_empty_sketch_roundtrip). When lg_k or type is omitted and only empty upstream sketches come in, the merge now returns an empty sketch with their configuration instead of the default one. With several empty inputs it takes the smallest lg_k and the widest type, so input order does not matter. The configuration also survives merge and write/read.
  • Merged current master (the base was from 2026-10-28). No conflicts.
  • CI failures from the previous run:
    • 05397_clickhouse_local_locked_path_untouched on Fast test (arm_darwin) is not caused by this PR. Skip 05397_clickhouse_local_locked_path_untouched on macOS #128088 fixed it and is now part of this branch.
    • hash_join_probe_continuation #1 (+15.6% on Performance Comparison (arm_release, master_head, 6/6)) is probably unrelated. This PR only adds new functions and does not touch HashJoin. The next run, against the updated base, will show whether it repeats.
  • Verification. Built clickhouse locally from the merged tree. The new test and all 19 existing DataSketches stateless tests of this PR pass.

Comment thread src/AggregateFunctions/HLLSketchData.h Resolved
Comment thread src/AggregateFunctions/HLLSketchData.h Resolved
alexey-milovidov and others added 6 commits November 13, 2026 09:40
…ging master

Master stopped including `FormatSettings.h` (and with it `writeJSONNumber`) transitively from `WriteHelpers.h`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e input precision

`HLLSketchData` could hold both an update sketch and a union at once: values inserted after a
merge (e.g. by `arrayReduceInRanges`) went to the update sketch, while `size`/`serializedData`
read only the union and `write`/`merge` only the update sketch, losing data. Now values are
inserted directly into the union once it exists, and creating a union folds the update sketch in.

`hll_union` adapts downward to the input `lg_k` only for dense inputs; sparse inputs are streamed
into its own `MAX_LG_K` sketch. Track the smallest `lg_k` of non-empty inputs when `lg_k` is not
explicit and downsample the result to it, also across partial-state serialization.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… and `percentileFromTDigest`

Comparisons with `NaN` are false, so `NaN` passed the range check and reached the sketch library,
which casts the rank to an unsigned integer (undefined behavior).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… and t-digests

Imported sketches were merged into freshly created default sketches (`k = 128` for Quantiles,
`k = 100` for t-digest), degrading upstream precision. Adopt the first imported sketch as is and
keep the larger `k` when merging exact-mode Quantiles sketches or t-digests, so the result does
not depend on the merge order.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Add pages with autogenerated markers for `serializedHLL`, `mergeSerializedHLL`, `serializedQuantiles`,
`mergeSerializedQuantiles`, `serializedTDigest`, `mergeSerializedTDigest` and `uniqHLL`, so the docs
generator picks up their `FunctionDocumentation`, together with slug map, redirect and navigation entries.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@mintlify

mintlify Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit 855237b.

Approve preview

alexey-milovidov and others added 3 commits November 20, 2026 22:33
Conflict: `docs/_migration/slug-map.csv` was deleted on master (the whole `docs/_migration` folder was removed), while this branch added rows to it. Resolved by keeping the deletion.
…ters

`serializedHLL`, `mergeSerializedHLL`, `mergeSerializedQuantiles` and `mergeSerializedTDigest` read these parameters through `FieldVisitorConvertToNumber<UInt64>`, which truncates fractional `Float64` and `Decimal` literals and wraps negative ones around. So `mergeSerializedHLL(0.5)` silently disabled base64 decoding and `serializedHLL(10.9)` used `lg_k = 10`. Now only a non-negative integer literal is accepted; anything else throws `ILLEGAL_TYPE_OF_ARGUMENT`.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Continued on 2026-11-20: pushed 4d8472c8c692..855237b373b3 to MaheshGPai:mahesh_pr.

  • Conflict (the PR was CONFLICTING). Merged current master. The only conflict was docs/_migration/slug-map.csv: master removed the whole docs/_migration folder, while this PR added seven rows to that file. I kept the deletion. The redirects this PR adds to docs/_site/redirects.json are unchanged.
  • CI (Build (arm_tidy, 1/4..3/4)). readability-ambiguous-smartptr-reset-call on sk_update.reset() in HLLSketchData.h. Fixed in f5b5db6 by assigning nullptr. I did not run clang-tidy locally, so the next CI run has to confirm it.
  • Review thread (fractional parameters). Fixed in 855237b: lg_k and base64_encoded must now be non-negative integer literals, otherwise the functions throw ILLEGAL_TYPE_OF_ARGUMENT. New test: 05839_datasketches_integer_parameters.
  • Verification. Built clickhouse locally from the merged tree. The new test and 21 of the 25 existing DataSketches stateless tests pass under clickhouse local. The other four (05508, 05629, 05631, 05632) use remote and need a running server, so they were not run here.

const DataTypePtr & data_type = argument_types[0];

WhichDataType which(*data_type);
if (which.isNumber())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[Major] This validator accepts 128/256-bit integers as if this sketch could preserve them exactly, but the implementation immediately coerces every input to Float64 in add (column.getFloat64(row_num) here and in serializedTDigest). That makes distinct large integers collapse before they ever reach DataSketches — for example toUInt256(9007199254740992) and toUInt256(9007199254740993) become the same double.

That is a real contract problem for the serialized sketch surface: callers can hand you legal Int128/UInt128/Int256/UInt256 columns and get a sketch that no longer distinguishes adjacent values. Please either reject the wide integer types up front (matching the narrower quantileTDigest surface, which sticks to basic numerics) or make this lossy cast an explicit documented contract with focused regression coverage. The same issue exists in src/AggregateFunctions/AggregateFunctionSerializedTDigest.cpp:97 / src/AggregateFunctions/AggregateFunctionSerializedTDigest.cpp:57.

This branch has not been deployed

No deployments
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 comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). external Author is not a member of the ClickHouse organization manual approve Manual approve required to run CI pr-feature Pull request with new product feature submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Apache DataSketches Support for Cross-Service Sketch Interoperability & Analytics

8 participants