Skip to content

Bump contrib/datasketches-cpp to fix reading compressed Theta sketch states - #116642

Closed
groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:datasketches-bump-116587
Closed

groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:datasketches-bump-116587

Conversation

@groeneai

@groeneai groeneai commented Aug 27, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #116587

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed uniqTheta and its variants silently returning a value that is too low when reading an AggregateFunction(uniqTheta, ...) state that another Apache DataSketches implementation had serialized in the compressed Theta sketch form. Two decoding bugs in contrib/datasketches-cpp corrupted or dropped retained values.

Description

Reported by @ UnamedRus in #116587, who asked for the Apache DataSketches HyperLogLog union fix (apache/datasketches-cpp#512, merged upstream 2026-08-15) to be in the tree before Apache DataSketches HyperLogLog support lands. @ alexey-milovidov asked me to take it.

No upstream release carries that fix, so this pins a post-release commit: c8e42183, the upstream master tip as of 2026-08-22. The latest release 5.2.0 (2025-01-15) does carry the Theta decoding fixes below (upstream 5c193334) but not the HyperLogLog one, so that tag would not answer the request. The old pin 76edd74f is from 2024-05-16 and is a strict ancestor, so the move is a fast-forward.

The HyperLogLog fix itself changes nothing today: it touches hll/include, and contrib/datasketches-cpp-cmake/CMakeLists.txt exposes only common/include, count/include and theta/include, so ClickHouse does not compile it. It lands here so it is present when #95045 adds hll/include.

The bump does change one compiled path, and that is the user-visible part. theta/include/bit_packing.hpp mis-decoded the compressed (serialization version 4) Theta sketch format in two places: unpack_bits_33 shifted a uint8_t left by 24 after promotion to int, so a byte above 0x7f became negative and sign-extended into the value's top 32 bits, and unpack_bits_35 masked a two-bit field with 2 instead of 3. ThetaSketchData::read reaches both through compact_theta_sketch::deserialize whenever the state's entry width is not 64 bits. A mis-decoded value either exceeds the sketch theta, so the union stops early, or collides with an earlier value, so it is deduplicated. Either way the estimate comes back too low, with no error. ClickHouse always writes the uncompressed form itself, so this needs a state produced elsewhere.

New test 05046_uniq_theta_compressed_state_116587 pins both routines: 16 and 16 with the bump, 7 and 14 without it. The same bump also fixes two write-side bugs in that format, which no ClickHouse code path reaches today.

Compatibility measurements for the 209-commit drift (click to expand)

Only three directories of the library are on the include path, so the review surface is git diff 76edd74f..c8e42183 -- common/include count/include theta/include = 13 headers, +293/-89. The compressed-read fix above is the only behaviour change reachable from ClickHouse; everything else is uncalled, not included, or value-preserving (MIN_LG_K 5 -> 4 is read by the builder's check_lg_k and by an uncompiled Jaccard header, ClickHouse never sets lg_k, and the two array-sizing sites moved to the new MIN_LG_ARR, whose value is the old 5; the count/ refactor keeps the same hash seeds, the same probe arithmetic and the same serialization layout).

Both persisted carriers were measured for byte identity, in both directions:

carrier measurement result
uniqTheta* state 21 queries: uniqThetaState at n = 0, 1, 2, 7, 8, 100, 4095, 4096, 4097, 10000, 1000000; String and FixedString keys; uniqThetaMergeState; uniqThetaUnion/Intersect/Not incl. an empty operand; max_threads 1 and 8 857,847 bytes of state hex, identical before and after
uniqTheta* state, cross-read every state written by one build finalized by both builds all four combinations agree to the digit
countmin statistics MergeTree with STATISTICS(countmin) on Int64, Float64, String, 20000 rows statistics.packed identical (md5 dc93bc75, 62519 bytes); reading either build's data directory with the other gives identical results

Both comparisons were sensitivity-controlled: a single added element moves the state hex, and changing one row moves the statistics.packed md5.

02751_ip_types_aggregate_functions_states already asserts cityHash64(hex(uniqThetaState(ip))) against a checked-in reference and passes unchanged, as do the uniqTheta and 02864_statistics_* families and the Statistics unit tests.


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

…states

Moves the pin from 76edd74f (2024-05-16) to c8e42183, the upstream master tip
as of 2026-08-22. The old pin is a strict ancestor, so this is a fast-forward.

Requested in ClickHouse#116587 by UnamedRus, to get the Apache DataSketches HyperLogLog
union fix (apache/datasketches-cpp#512, merged upstream 2026-08-15) into the
tree before Apache DataSketches HyperLogLog support lands. No upstream release
carries that fix; the latest, 5.2.0, is from 2025-01-15.

That HyperLogLog fix changes nothing today: it touches hll/include, and
contrib/datasketches-cpp-cmake/CMakeLists.txt exposes only common/include,
count/include and theta/include, so ClickHouse does not compile it.

The same bump does fix a live path. theta/include/bit_packing.hpp mis-decoded
the compressed (serialization version 4) Theta sketch format in two places:

  * unpack_bits_33 did `values[7] |= *ptr++ << 24` on a uint8_t. Integer
    promotion makes that an int shift, so a byte >= 0x80 yields a negative int
    and OR-ing it into a uint64_t sign-extends into the delta's top 32 bits.
    This is not undefined behaviour, which is why UBSan never flagged it.
  * unpack_bits_35 masked a two-bit field with 2 instead of 3, dropping bit 33
    of the third delta in each block of eight.

ThetaSketchData::read calls compact_theta_sketch::deserialize, which dispatches
on the serialized entry_bits and routes anything other than 64 through
unpack_bits_block8 into those routines. Deltas are a prefix sum, so one bad
delta corrupts every later entry. theta_union::update keeps only entries below
theta and early-stops on the first one that is not, because a version-4 sketch
is ordered. So the sign-extension case truncates the retained set and the
dropped-bit case makes an entry collide with an earlier one and deduplicate.
Either way uniqTheta returns a value that is too low, with no error.

ClickHouse always serializes the uncompressed form itself, so a compressed
state has to come from another Apache DataSketches implementation. The new test
covers both routines: 16 and 16 with the bump, 7 and 14 without it.

The bump also fixes two write-side bugs in the same format (pack_bits_13 and a
missing final partial byte); no ClickHouse code path reaches those.

Every uniqTheta* state and the persisted countmin statistics file are
byte-identical across the bump, verified in both directions, so the drift under
the three compiled directories moves no persisted format.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Aug 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 0 findings), plus my own
cold review of the resulting tree, which produced 4.

# Sev Finding Verdict Evidence / action
1 - Independent gate pass: 0 findings none Reviewed the 3-file diff, the exposed upstream header changes, the ClickHouse callers, the sibling serialization paths and the tests
2 ⚠️ The release framing left "why not pin the released 5.2.0 tag?" unanswered AGREE, fixed in the description 5c1933342d7a6 (the Theta bit-packing fix) is an ancestor of 5.2.0 (13 ahead, 0 behind), so only the HyperLogLog half is unreleased. Now said explicitly
3 ⚠️ "MIN_LG_K is read only by the builder's check_lg_k" was checkably false and incomplete AGREE, fixed in the description theta_jaccard_similarity_base.hpp:141 reads it too (uncompiled here), and the point that carries the argument was missing: the two array-sizing sites moved to the new MIN_LG_ARR, whose value is the old 5
4 💡 Four carriers of a submodule move were not enumerated up front AGREE, all four checked, all clean The submodule's own LICENSE/NOTICE feed StorageSystemLicenses' generated raw-string literal (still Apache, no )heredoc token, and the only system.licenses tests assert abseil-cpp and poco); the new common/include/xxhash64.h lands on every dbms translation unit's include path via SYSTEM BEFORE (no other xxhash64.h in the tree, nothing includes that name); the changed std::logic_error text (no test asserts it); the sanitizer ignorelists (no datasketches entry)
5 💡 #95045 was linked twice in the description AGREE, fixed One mention carries both points, and each cross-reference back-links onto that PR

Severity: ❌ blocker / ⚠️ major / 💡 nit. Findings 2, 3 and 5 are description-only and were
corrected before the gate ran, so the gate reviewed the final text.

I re-derived the test's liveness independently, without a build, by reimplementing
unpack_bits_33 and unpack_bits_35 in both the old and the new form (including the
integer promotion) plus theta_union's keep-below-theta, early-stop-on-ordered and
deduplicate semantics, then decoding the two states in the test file. Old pin: 7 and 14.
New pin: 16 and 16. The two arms fail through different mechanisms, union early-stop
truncation and hash-table deduplication, so neither is a weaker copy of the other. Both
states are well formed in every header field, and their declared length equals the
parser's own computed expected size, so the trailing-byte guard cannot fire.

One measurement worth recording because anyone repeating the compatibility sweep will
meet it: finalizing uniqTheta directly and finalizing it from a serialized state give
slightly different estimates at n >= 10000 (for example 10013 against 9897). That is
pre-existing behaviour, not the bump. It reproduces before the bump as well, because a
state read back goes through theta_union::get_result, which recomputes theta. The
bump-relevant fact is that all four writer-by-reader combinations agree to the digit.

Session id: cron:clickhouse-review-slot-8:20260827-041400

@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Aug 27, 2026
@clickhouse-gh clickhouse-gh Bot closed this Aug 27, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 27, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0d97fa8]

Summary: ✅


AI Review

Summary

This PR fast-forwards contrib/datasketches-cpp from 76edd74f5db2 to c8e421830915 and adds 05046_uniq_theta_compressed_state_116587 to lock in the compressed Theta deserialization fix exercised through ThetaSketchData::read. I reviewed the current diff, the full prior PR discussion, the current code paths in ClickHouse that consume the bumped library (uniqTheta and countmin statistics), the exposed upstream header delta under common/include, count/include, and theta/include, and the all-green Praktika report. I did not find a correctness, compatibility, performance, or test-contract issue that warrants an inline review comment.

Final Verdict

✅ No findings.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. One clickhouse local query against 05046_uniq_theta_compressed_state_116587.sql; 100% reproducible, no server, no randomization, no timing.
b Root cause explained? Yes. ThetaSketchData::read calls compact_theta_sketch::deserialize, which routes any state whose entry width is not 64 bits through unpack_bits_33/unpack_bits_35. Both mis-decoded one delta; deltas are a prefix sum, so the corruption spreads. The union then either stops early (the value exceeds theta) or deduplicates (it collides with an earlier value), so the estimate is too low.
c Fix matches root cause? Yes. The defect is upstream's and upstream already fixed it, so the fix is to take the upstream commit rather than work around it in src/. No src/ change at all.
d Test intent preserved / new tests added? No existing test modified or weakened. One new test with two arms, one per decoding routine; each reddens on its own and through a different mechanism (truncation vs deduplication).
e Both directions demonstrated? Yes, on Build-ID-verified binaries: 7 and 14 before the bump, 16 and 16 after. Confirmed independently at the library level by compiling the blob generator against both header sets, which emit byte-identical blobs and differ only in what they decode.
f Fix is general across code paths? Yes. All four upstream version-4 bugs come with the bump, not only the two reachable ones; the two write-side bugs are disclosed as currently unreachable rather than claimed as user-visible.
g Fix generalizes across inputs (params/datatypes/wrappers)? The compatibility sweep covers UInt64, String and FixedString keys, n = 0, 1, 2, the 4095/4096/4097 nominal boundary, estimation mode, an empty operand for all three set operations, and max_threads 1 and 8. The fix is in the bit-packing layer, below the aggregate's key type.
h Backward compatible? Measured, not argued. All uniqTheta* state bytes (857,847 bytes of hex) and the persisted countmin statistics.packed are identical before and after, and cross-reading works in both directions. No setting default changes, so no SettingsChangesHistory.cpp row; no format change, so no versioning obligation.
i Invariants and contracts preserved? The invariant is that every ClickHouse-persisted or ClickHouse-exchanged DataSketches byte format round-trips unchanged across the bump, in both directions. It holds for uniqTheta* states and for statistics.packed. The compressed read path is the one carrier that deliberately changes, from wrong to correct.

Also run: the uniqTheta and 02864_statistics_* stateless families and the Statistics
unit tests pass; 05046 passes 50/50 runs with randomization and 50/50 without. Two tests
in the local run fail identically on the pre-bump binary as well, so they are limits of the
single-node sandbox (remote('127.0.0.{2,3}', ...) and a ReplicatedMergeTree async
insert), not regressions.

Session id: cron:clickhouse-impl-slot-6:20260827-032300

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default submodule changed At least one submodule changed in this PR. labels Aug 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @thevar1able @rschu1ze, could you review this? It bumps contrib/datasketches-cpp for the upstream HyperLogLog union fix, and the same drift also fixes two mis-decodes in the compressed Theta sketch format, so uniqTheta stops returning a value that is too low when reading a state written by another Apache DataSketches implementation. The drift over the three compiled directories is 13 headers, and both persisted formats are byte-identical across the bump in each direction.

@clickhouse-gh

clickhouse-gh Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 0d97fa85f with master 3eb72756a (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 711.97 MiB 708.91 MiB -3.06 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

11 translation units recompiled, 43 s compile time in total, 11 of them have a recent master baseline.

Job report

@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 41 queries analysed

This PR only bumps the datasketches-cpp submodule (uniqTheta compressed-state deserialization) and adds a stateless test for it; no server query-execution code changes. None of the five flagged ClickBench queries (Q18, Q28, Q32, Q33, Q34) use uniqTheta, and all show flat CPU time against a uniform +6-7% wall-clock rise, which is environmental variance rather than a real regression. All five correctly stay not_sure. The envelope-suppression and test-disagreement outcomes are consistent with the data given the off-path diff.

clickbench

⚠️ 5 inconclusive

Flagged queries (5 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 18 not_sure 1058 1136 +7.4% <0.0001 CPU time is flat (15076→15194 ms) while wall-clock rose +7.4%. The PR only bumps the datasketches submodule for uniqTheta decoding, which ClickBench never exercises, so this is run-to-run variance.
⚠️ 28 not_sure 1054 1120 +6.3% <0.0001 The two tests disagree and the base run was noisy, with CPU time flat (+6.3% wall only). ClickBench doesn't use uniqTheta, the only thing this PR changes; treat as variance.
⚠️ 32 not_sure 1321 1412 +6.9% <0.0001 CPU time is flat (19055→19136 ms) against a +6.9% wall shift. The uniqTheta submodule bump in this PR is not on any ClickBench code path, so this is environmental variance.
⚠️ 33 not_sure 1205 1295 +7.5% <0.0001 CPU time is essentially unchanged (17575→17585 ms) despite the +7.5% wall delta. ClickBench does not invoke uniqTheta, the only function this PR touches; this is variance.
⚠️ 34 not_sure 1203 1288 +7.0% <0.0001 CPU time is flat (17560→17623 ms) while wall-clock moved +7.0%. The datasketches/uniqTheta change here is off every ClickBench path, so this reads as run-to-run variance.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 35bbc902-f7f2-4d09-bbd1-172f633c4597
  • MIRAI run: 307184c9-38d6-41d7-b7b7-fca08da53c3a
  • PR check IDs:
    • clickbench_547463_1788147971
    • clickbench_547565_1788147977
    • clickbench_547668_1788147985
    • tpch_adapted_1_official_547826_1788148038
    • tpch_adapted_1_official_547846_1788148039
    • tpch_adapted_1_official_548028_1788148066

@rschu1ze

Copy link
Copy Markdown
Member

Problem 1: This PR looks like it merges from upstream HEAD (bad practice from the old days) instead of making a ClickHouse/ branch (see here).

Problem 2: HEAD is a moving target + development version. It will be nicer to upgrade to the newest current stable version + backport the fix requested here.

@rschu1ze rschu1ze closed this Aug 31, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Both problems are real and this PR had both.

Three measurements for whoever picks it up, since they make the stable-tag route cheap:

  1. Tag 5.2.0 (de8553ba) is 75 commits ahead of the current pin 76edd74f and 0 behind, so it is a plain fast-forward.
  2. theta/include/bit_packing.hpp is byte-identical at 5.2.0 and at upstream HEAD c8e42183. Against the pin it differs in three functional lines: pack_bits_13 writes values[3] << 4 (pin: >> 4), unpack_bits_33 casts to uint64_t before << 24 (pin sign-extends after promotion to int), and unpack_bits_35 masks & 3 (pin: & 2). The last two are on the uniqTheta deserialize path for compressed (serialization version 4) states, so 5.2.0 on its own fixes an under-count when such a state is read into AggregateFunction(uniqTheta, ...). tests/queries/0_stateless/05046_uniq_theta_compressed_state_116587.sql in this diff covers that and fails on the current pin.
  3. hll/ is not on the include path: contrib/datasketches-cpp-cmake/CMakeLists.txt exposes only common/, count/ and theta/. So the requested upstream fix (Fix HLL union estimate/serialization regression from lazy KxQ rebuild apache/datasketches-cpp#512) changes nothing that is compiled today, and becomes live only once Apache DataSketches Support for Cross-Service Sketch Interoperability & Analytics #95045 adds hll/include. That is the open PR asked about on the issue.

One mechanical constraint: groeneai has no push access to ClickHouse/datasketches-cpp (push: false), and that fork has no ClickHouse/-prefixed branch, so I cannot create ClickHouse/5.2.0 or cherry-pick the fix onto it. Standing down in favour of @ thevar1able 's library bumping skill; if that branch gets created I can do the bump.

@alexey-milovidov

Copy link
Copy Markdown
Member

Redone as #117422, addressing both points.

The fork ClickHouse/datasketches-cpp was archived (hence push: false); it is unarchived now and carries branch ClickHouse/5.2.0 = tag 5.2.0 + a squashed cherry-pick of apache/datasketches-cpp#512. The submodule URL moves from apache/ to ClickHouse/ and the pin to that branch, so no upstream development commit is tracked any more.

The backport is not a no-op on 5.2.0: the lazy KxQ/curMin rebuild it repairs was already released there, and the four regression tests that come with the fix all fail on the plain tag and pass on the branch.

Your two measurements hold, and the release pin also shrinks the review surface a lot: over the three compiled directories the drift is 5 headers rather than 13.

rorylshanks pushed a commit to rorylshanks/ClickHouse that referenced this pull request Sep 2, 2026
A PR that is opened and then reopened seconds later delivers two pull_request
events at one head commit, so GitHub dispatches two complete PR workflow runs in
parallel. Both are run_attempt = 1, and TEMPLATE_PULL_REQUEST_0 emits no
concurrency block, unlike TEMPLATE_SCHEDULE and TEMPLATE_DISPATCH_WORKFLOW, so
neither run supersedes the other.

Everything the two runs share is keyed by (PR, sha) and never by RUN_ID: the S3
artifact objects from _Environment.get_s3_prefix_static, and the
result_<workflow>.json document merged by _ResultS3.update_workflow_results. Two
consequences measured at one commit of ClickHouse#116641 and of ClickHouse#116642:

  - Nine legs of one run died in the praktika pre-run artifact download with
    PreconditionFailed, because the other run re-uploaded the key while the
    ranged GET was in flight, so its ETag precondition no longer held. All nine
    are success in the sibling run at the identical tree, and two of them are
    flaky check legs. praktika had already closed this same race for the
    submodule cache object alone, with an If-None-Match write-once create in
    native_jobs.py.

  - The losing run's Finish Workflow read the shared result document while the
    other run's per-arch jobs were still RUNNING, and published "No per-arch
    Bugfix Validation job validated the bug". The sibling run contradicts it
    with three success jobs.

Emit a concurrency group of workflow, PR number and head sha, with
cancel-in-progress, for pull_request workflows. The head sha is in the group so
a push starts a new group and never cancels the run at the previous commit. When
the second run appears the first has created exactly one job, Config Workflow,
so a supersession cancels that job and nothing else.

The group is populated per event rather than written into the template, because
TEMPLATE_PULL_REQUEST_0 is shared with the push workflows, where
github.event.pull_request is null. A literal in the template would give MasterCI
a degenerate group and, with cancel-in-progress, cancel every in-flight run on
every master commit. master.yml and release_branches.yml stay byte-identical.

The close-and-reopen originates from an app outside this repository. This change
neither depends on it nor alters it, and a genuinely reopened PR still gets a
run.

retry_infra_failures.yml partially masks this today: a pre-run S3 failure is
classified as infrastructure by its rule for a Run step that failed in under two
minutes, and the run is retried.

Co-Authored-By: Claude Opus 5 <[email protected]>
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 groeneai-origin-request PR origin: a maintainer pinged or directed groeneai manual approve Manual approve required to run CI pr-bugfix Pull request with bugfix, not backported by default 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 version bump (bug with HLL)

3 participants