Skip to content

Fix undefined behavior converting huge join row estimates to distinct counts - #124008

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-ubsan-join-statistics-huge-row-estimates
Oct 7, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-ubsan-join-statistics-huge-row-estimates

Conversation

@groeneai

@groeneai groeneai commented Oct 5, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #118875

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Join planning no longer has undefined behavior when a row estimate exceeds the UInt64 range, for example for a cross product of large tables in the experimental Cascades optimizer or under LIMIT 18446744073709551615.

Description

The AST fuzzer aborted a sanitizer build in Cascades statistics derivation (report):

StatisticsDerivation.cpp:304:20: runtime error: 1.35009e+24 is outside the range of representable values of type 'unsigned long'

The query was a TPC-H Q18 from 05024_tpch_join_order_plans_aggregation_pushdown with its ANDs turned into ORs, so customer, orders, lineitem became a cross product of 1.35e24 rows under the SF100 statistics hints. Cascades keeps row estimates as Float64 because they can exceed the UInt64 range, but several places turned an estimate into a UInt64 distinct-value count with a plain cast, which is undefined behavior for values of 2^64 and above. Since #122305 the join-key bound casts each input's row count separately, so one huge input of an equality join is enough.

The fix adds toUInt64Saturating next to the other shared helpers in RelationStatistics and uses it at all ten conversions in StatisticsDerivation.cpp (join keys, the final join clamp, filter, aggregation keys, LIMIT, DISTINCT, INTERSECT). The join order optimizer had the same conversion for an aggregation over an input estimated at 2^64 - 1, for example under LIMIT 18446744073709551615; it uses the helper too. The result is unchanged for every estimate below 2^64; a unit test pins the saturation. Not for changelog: the per-input join-key casts exist only on master, and at the other sites a release build only got an arbitrary estimate.

The new test reaches five of these sites with statistics hints and the join order one with LIMIT. On a master ASan build it kills the server (StatisticsDerivation.cpp:304:20); with the fix it passes 50/50 with randomized settings, and no existing Cascades or join order test changes its outcome.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.1733-master (included in 26.10 and later)

groeneai and others added 2 commits October 5, 2026 09:21
… counts

Cascades keeps row estimates as Float64 because a cross product of large
inputs can exceed the UInt64 range, and the cost model compares such
values. Distinct-value counts are UInt64, and ten places in
StatisticsDerivation.cpp turned an estimate into one with a plain cast,
which is undefined behavior for values of 2^64 and above. Since ClickHouse#122305
the join-key bound casts each input's row count separately, so one huge
input of an equality join is enough.

The AST fuzzer hit it with TPC-H Q18 from
05024_tpch_join_order_plans_aggregation_pushdown with its ANDs turned
into ORs: customer x orders x lineitem is a 1.35e24-row cross product
under the SF100 hints, and it is the left input of the semi join made by
rewrite_in_to_join (STID 4584-4b08, StatisticsDerivation.cpp:304).

Add toUInt64Saturating to RelationStatistics, next to the statistics
helpers shared with join ordering, and use it at every conversion. It is
identical to the plain cast below 2^64. Clamping the estimate itself
would flatten the cost model, and std::min with Float64(UINT64_MAX) is
2^64, still out of range, hence the >= check.

The test reaches the left and right join keys, an aggregation key,
DISTINCT and INTERSECT. Its INTERSECT query projects columns of both
cross product inputs: with only one input's columns the cross product
returns no rows under the distributed Cascades plan, on master too.

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

The join order optimizer computes an aggregation's row estimate as a
Float64 and stored it into the UInt64 estimate with an implicit
conversion. When the aggregation's input estimate is UINT64_MAX (a
LIMIT 18446744073709551615 or ORDER BY ... LIMIT over a source without
an estimate, or a cardinality hint of that size) and a key has no
distinct-value statistics, the Float64 value is exactly 2^64, which is
outside the UInt64 range: undefined behavior, reported by UBSan in
estimateAggregatingStepStats. It is reachable with default settings,
without Cascades. Use toUInt64Saturating there as well.

The SQL test can only observe that the sanitizer does not abort, not
which value a huge estimate becomes, so add a unit test that pins
toUInt64Saturating: NaN and non-positive values give 0, values of 2^64
and above give UINT64_MAX, the largest in-range double converts
exactly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Oct 5, 2026
@groeneai

groeneai commented Oct 5, 2026

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

Pre-publication review by an independent model (engine: codex; 2 rounds, 2 findings) plus my own cold review (1 finding, 2 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ The join order sibling (RelationStatisticsEstimator.cpp:98) was ruled out by a probe that returns early at :253 and never reaches :98 AGREE, fixed LIMIT 18446744073709551615, ORDER BY ... LIMIT and a 2^64 - 1 cardinality hint all reach it on master; it uses the helper now and the test covers it
2 ⚠️ The SQL test cannot see whether huge estimates saturate or map to 0 AGREE, fixed unit test CascadesJoinStats.ToUInt64Saturating; a >= 2^64 -> 0 mutant fails it
3 ⚠️ The join order query checks only count(); add an EXPLAIN check of the saturated estimate DISAGREE the query alone aborts a master UBSan build at RelationStatisticsEstimator.cpp:98:38, and the saturation is pinned by the unit test; no extra EXPLAIN oracle
4 💡 joinOrderCommon.h saturates inline in two places noted correct and untouched; not changed to keep the diff minimal

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261005-102400

@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The CI statement on the setup of 05024_tpch_join_order_plans_aggregation_pushdown aborts a master ASan build 4/4 with 1.35009e+24 is outside the range of representable values; the new test kills a master ASan server at StatisticsDerivation.cpp:304:20.
b Root cause explained? Row estimates are Float64 and a cross product can exceed 2^64; ten places converted an estimate to a UInt64 distinct count with a plain cast, which is undefined behavior at and above 2^64. Since #122305 one huge join input is enough.
c Fix matches root cause? Yes. The conversion is where the out-of-range value is created, so it saturates there; the estimate itself is left as is (clamping it would flatten the cost model).
d Test intent preserved / new tests added? New test 05325_join_statistics_huge_row_estimates, one query per reachable site (left and right join keys, aggregation key, DISTINCT, INTERSECT, the join order optimizer's aggregation estimate). The unit test CascadesJoinStats.ToUInt64Saturating pins the saturation itself, which SQL cannot see; it fails if values of 2^64 and above map to 0.
e Both directions demonstrated? Master ASan server: FAIL (UBSan at StatisticsDerivation.cpp:304; the join order query alone at RelationStatisticsEstimator.cpp:98). Fixed ASan server: OK, 50/50 randomized and 200/200 more; debug build OK.
f Fix is general across code paths? All ten float-to-integer conversions in StatisticsDerivation.cpp use the helper (a grep finds no other cast in the file). The join order estimator had the same conversion for an aggregation over an input estimated at 2^64 - 1 (LIMIT, ORDER BY ... LIMIT, a cardinality hint all reach it), and uses the helper too; joinOrderCommon.h and ConditionSelectivityEstimator.cpp already saturate.
g Fix generalizes across inputs (params/datatypes/wrappers)? Planner arithmetic only, independent of column types and engines. The helper maps NaN and non-positive values to 0, values of 2^64 and above to UINT64_MAX, everything else unchanged; one test query hits exactly 2^64.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or serialized state; results for estimates below 2^64 are identical, and no existing Cascades or join order test changes its outcome.
i Invariants and contracts preserved? A distinct count stays a valid UInt64 that is monotone in the estimate; consumers of a saturated count already guard overflow (remapColumnStats) or take a minimum (updateJoinKeyDistinctCounts). No locking or allocation changes.

Session id: cron:clickhouse-impl-slot-41:20261005-094400

@clickhouse-gh

clickhouse-gh Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e6f22c8]

Summary: ✅


AI Review

Summary

This PR replaces the unsafe Float64 → UInt64 conversions in join-statistics estimation with toUInt64Saturating, applies the same fix to the join-order aggregation estimator, and adds focused coverage for both the sanitizer repro and the exact 2^64 boundary. I did not find a remaining correctness or safety gap in the patched code paths.

Missing context / blind spots
  • ⚠️ The full PR report and the pending Build (amd_asan_ubsan) / Build (arm_asan_ubsan) jobs were not finished when I reviewed, so I could not independently confirm the end-to-end sanitizer repro on completed CI artifacts.
Final Verdict
  • Status: ✅ Approve
  • The touched Float64 → UInt64 sites now saturate consistently, the join-order sibling path is covered as well, and the added tests are appropriately targeted.

LLVM Coverage Report

Measured on commit e6f22c8.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 92.10% 92.20% +0.10%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 54/54 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Oct 5, 2026
@groeneai
groeneai requested review from cv4g and davenger October 5, 2026 11:04
@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Oct 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing e6f22c88f with master 98f3cad68 (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×1.08 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +11.2 s (+10%) in total before that adjustment.

Job report

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Perfect.

@alexey-milovidov alexey-milovidov self-assigned this Oct 7, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 7, 2026
Merged via the queue into ClickHouse:master with commit 9b9866a Oct 7, 2026
149 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 7, 2026
vdimir pushed a commit that referenced this pull request Nov 2, 2026
`estimateReadRowsCount` is in `optimizeJoin.cpp` on 26.8: it moved to
`RelationStatisticsEstimator.cpp` only with #120232, which is master-only.
So the change of #126491 is applied there, with two adaptations:
- the third argument (`for_runtime_filter_transport`) of the recursive call
  does not exist on 26.8 and is dropped;
- `toUInt64Saturating` (added by #124008, master-only) does not exist on 26.8,
  so the file gets a static copy of it with the same body.

The setting `query_plan_lower_array_join_function` does not exist on 26.8
(`arrayJoin` is never lowered to an `ArrayJoinStep` there), so the test
`05406_join_swap_array_join_estimate` drops it from four queries. Those
queries then run the `arrayJoin` expression path, with the same result,
and the reference is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
vdimir pushed a commit that referenced this pull request Nov 2, 2026
`estimateReadRowsCount` is in `optimizeJoin.cpp` on 26.9: it moved to
`RelationStatisticsEstimator.cpp` only with #120232, which is master-only.
So the change of #126491 is applied there, with two adaptations:
- the third argument (`for_runtime_filter_transport`) of the recursive call
  does not exist on 26.9 and is dropped;
- `toUInt64Saturating` (added by #124008, master-only) does not exist on 26.9,
  so the file gets a static copy of it with the same body.

The test `05406_join_swap_array_join_estimate` is unchanged.

Co-Authored-By: Claude Opus 5.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 comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-not-for-changelog This PR should not be mentioned in the changelog pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants