Repository navigation
Fix undefined behavior converting huge join row estimates to distinct counts - #124008
Conversation
… 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]>
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).
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-8:20261005-102400 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-41:20261005-094400 |
|
Workflow [PR], commit [e6f22c8] Summary: ✅
AI ReviewSummaryThis PR replaces the unsafe Missing context / blind spots
Final Verdict
LLVM Coverage ReportMeasured on commit e6f22c8.
Changed lines: Changed C/C++ lines covered: 54/54 (100.00%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units21 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. |
`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]>
`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]>
Related: #118875
Changelog category (leave one):
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
UInt64range, for example for a cross product of large tables in the experimental Cascades optimizer or underLIMIT 18446744073709551615.Description
The AST fuzzer aborted a sanitizer build in Cascades statistics derivation (report):
The query was a TPC-H
Q18from05024_tpch_join_order_plans_aggregation_pushdownwith itsANDs turned intoORs, socustomer, orders, lineitembecame a cross product of 1.35e24 rows under the SF100 statistics hints. Cascades keeps row estimates asFloat64because they can exceed theUInt64range, but several places turned an estimate into aUInt64distinct-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
toUInt64Saturatingnext to the other shared helpers inRelationStatisticsand uses it at all ten conversions inStatisticsDerivation.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 underLIMIT 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
26.10.1.1733-master(included in26.10and later)