Skip to content

Estimate range conditions from all parts of tdigest statistics - #126385

Merged
hanfei1991 merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/tdigest-statistics-merge-compress
Oct 20, 2026
Merged

hanfei1991 merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/tdigest-statistics-merge-compress

Conversation

@groeneai

@groeneai groeneai commented Oct 17, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Improvement

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

Range conditions such as x < 100 on a column with tdigest statistics are now estimated correctly on tables with several parts. Previously the estimate depended on the order of the parts and could be zero, so the planner could pick a worse join order, PREWHERE order or distributed plan.

Description

04950_distributed_plan_runtime_filter_delivery_from_join_stage failed on master in Stateless tests (amd_debug, distributed plan, s3 storage, parallel), and 37 of 69 reruns with the same randomized settings failed too. Those settings include auto_statistics_types with tdigest. In every failing run the planner estimated v < 90000 on big (90000 matching rows) as 0 rows and refused to transport the runtime filter. Every passing run estimated 89999.

The estimator merges the tdigest statistics of all parts with QuantileTDigest::merge, which appends the other digest's centroids and sorts them only once more than 2048 are pending. getCountLessThan reads the centroids in order and returns 0 when the first one is already above the bound. So the estimate depended on which part came first, and that varies with the commit order of a parallel insert.

StatisticsTDigest::merge now compresses the digest after merging, so it is sorted whatever the part order. Digests loaded from parts are already compressed, and the other statistics merges do not depend on order.

Validation: the new test 05406_statistics_tdigest_range_estimate_part_order fails on master (high first 0) and passes with the fix (50/50 with randomized settings). A copy of 04950 that writes the lowest key range as the last part fails 20/20 on master and passes 20/20 with the fix. Planning on a table with 500 parts (debug build): EXPLAIN median 6 ms before, 10 ms after; merge time unchanged.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.271-master (included in 26.11 and later)
  • Backported to: 26.10.5.59

The selectivity estimator accumulates the `tdigest` statistics of all parts
with `StatisticsTDigest::merge`. `QuantileTDigest::merge` only appends the
other digest's centroids and sorts them once more than `max_unmerged` (2048)
are pending, while `getCountLessThan` is const and walks the centroids in
array order, returning 0 when the first centroid is already above the bound.
So a range condition was estimated from whichever part came first, and the
estimate was often 0 when a part with high values was added first (or after
the last internal compress).

This made `04950_distributed_plan_runtime_filter_delivery_from_join_stage`
flaky on master: with `auto_statistics_types` containing `tdigest`, the 4
parallel-insert parts of `big` were committed in varying order, the planner
estimated `v < 90000` as 0 rows in the failing runs and refused to transport
the runtime filter (`100 estimated build keys vs 0 estimated site rows`).

Compress after merging, so the merged digest is sorted whatever the part
order. Digests loaded from parts are already compressed in `deserialize`,
and `compress` mutates only the object `merge` is already mutating (the
estimator's own `cloneEmpty` copy, or the gathered statistics of a merge).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@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 review (2 nits).

# Sev Finding Verdict Evidence / action
1 💡 compress() now runs on every merged part, not every 2048 appended centroids AGREE, not blocking Measured on 500 parts (debug): EXPLAIN median 6 ms to 10 ms, part merges unchanged. Only columns with tdigest statistics pay it. Stated in the description.
2 💡 Equality estimates now read a compressed merged digest DISAGREE That is the digest a merge of the same parts produces; the statistics tests give identical results before and after.

Severity: ❌ blocker / ⚠️ major / 💡 nit.

Session id: cron:clickhouse-review-slot-9:20261016-235500

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 05406_statistics_tdigest_range_estimate_part_order prints high first 0 on master on every run (estimate 0 for a true 2500).
b Root cause explained? QuantileTDigest::merge appends centroids and sorts only past 2048 pending ones; getCountLessThan reads them in order and returns 0 when the first centroid is above the bound. The merged estimate therefore depended on part order.
c Fix matches root cause? Yes. StatisticsTDigest::merge compresses after merging, the only path that left an estimated digest unsorted (deserialize already compresses).
d Test intent preserved / new tests added? New SQL test with both part orders; 04950 is unchanged.
e Both directions demonstrated? 05406: master FAIL on every run, fix 50/50 OK (randomized). A copy of 04950 with the lowest key range in the last part: master 20/20 FAIL with the CI signature (estimate statistics big: 0 rows, transport refused), fix 20/20 OK.
f Fix is general across code paths? The other statistics merges (Basic, MinMax, CountMin, Uniq, UniqV2) are order-independent; both merge callers (estimator, MergeTask) use StatisticsTDigest::merge.
g Fix generalizes across inputs (params/datatypes/wrappers)? Nullable/LowCardinality are stripped before the same merge; tested with 2 parts both ways and 4 parts with an internal compress.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; serialized digests were already compressed.
i Invariants and contracts preserved? compress() keeps count and total weight and only touches the object merge() already mutates (the estimator's own copy, or MergeTask's gathered statistics). Cost: +4 ms EXPLAIN median on 500 parts (debug), merge time unchanged.

Session id: cron:clickhouse-impl-slot-5:20261016-213900

@clickhouse-gh

clickhouse-gh Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c4e7739]

Summary: ✅


AI Review

Summary

The PR compresses merged tdigest statistics so range estimates include all parts regardless of insertion order, and adds a regression test for both orders. Reviewed head: c4e7739ac706fa1f5cd23aea2f32fd69481d167e. No actionable findings.

Missing context / blind spots
  • ⚠️ Stateless CI for the latest merge commit is still pending. The new regression passed all five runs on the preceding PR head in the debug stateless report. Completing the current-head stateless jobs would confirm validation after the merge from master; no local ClickHouse binary was available for an independent rerun.
Final Verdict

Status: ✅ Approve. No code changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Oct 17, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @hanfei1991 @CurtizJ, could you review this and add can be tested (I cannot add labels right now, so CI has not started)? StatisticsTDigest::merge left the merged digest unsorted, so range estimates from tdigest statistics on multi-part tables depended on part order and could be 0; it now compresses after merging.

@hanfei1991 hanfei1991 self-assigned this Oct 17, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Oct 17, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 17, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 79a7362

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_debug, parallel) / 05339_string_filters_during_scan_parquet_short_dictionary_values master regression from my merged #124131 (semantic conflict with the test added by #124507), not from this PR (it changes only StatisticsTDigest::merge and adds its own test): line 4 prints 0 instead of 1; the tested merge tree d55671f3c938 does not contain the revert (merged 03:14Z) #126396 (external, merged)
Stateless tests (amd_debug, distributed plan, s3 storage, parallel), (arm_asan_ubsan, azure, parallel), (arm_binary, parallel), (arm_binary, AsyncInsert, s3 storage, parallel), (arm_binary, ParallelReplicas, s3 storage, parallel), (arm_binary, s3 storage, DBReplicated, parallel, 2/2) / 05339_string_filters_during_scan_parquet_short_dictionary_values same master failure, the only failed test in each of these jobs #126396 (the owner of the first row)
Upgrade check (amd_release) / Segmentation fault (STID: 5726-4458) crash, not from this PR: segfault in the TemporaryBlockStreamHolder constructor under GraceHashJoin::initialize while a JoinStep is built; the same stack is in the Upgrade check of 9 other unrelated PRs since 2026-10-16 17:35Z #126204 (mine, open)
Upgrade check (amd_release) / the 4 Cannot list/count/submit/run ... mutation rows fallout of the crash above: the server was down (Connection refused on port 9000) #126204 (the owner of the row above)
Mergeable Check, PR praktika rollups of the rows above #126396 and #126204 (the owners of the rows above)

#126396 reverts #124131 on master, and #126397 re-lands it with the test adjusted. The only other FAIL rows on this head are the Config Workflow / Pre Hooks rows of the two earlier attempts, which stopped on the missing can be tested label; the final attempt passed it.

Session id: cron:our-pr-ci-monitor:20261017-090009

@hanfei1991

Copy link
Copy Markdown
Member

@groeneai check the CI failure

@groeneai

Copy link
Copy Markdown
Collaborator Author

The reds are not from this PR (it changes only StatisticsTDigest::merge and adds its own test):

@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 17, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 17, 2026
Backport #126385 to 26.10: Estimate range conditions from all parts of `tdigest` statistics
@clickhouse-gh clickhouse-gh Bot added comp-statistics Column statistics: statistics kept per part on a column (tdigest, uniq, count-min sketch, minmax)... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 22, 2026
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-statistics Column statistics: statistics kept per part on a column (tdigest, uniq, count-min sketch, minmax)... pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-improvement Pull request with some product improvements pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants