Repository navigation
Fix UBSan signed integer overflow in arrayLevenshteinDistanceWeighted - #106934
Conversation
levenshteinDistanceWeighted<Element, Weight> performed all of its
dynamic-programming arithmetic in the template Weight type (the SQL weight
array element type). With integer weights near the type maximum (e.g. Int64
LLONG_MAX) every accumulation overflowed: the partial_sum that seeds the row,
the row[0] prefix, the three add operations inside the min{}, the empty-side
sum_span shortcut, and the separate weights_sum in arraySimilarity. UBSan
reported the signed integer overflow (1 + LLONG_MAX) and the result was
undefined in release builds.
All three callers in arrayLevenshtein.cpp already cast the result to Float64
and the SQL functions return Float64, so accumulating in Float64 throughout is
transparent to callers and removes every overflow site. The function return
type is changed from Weight to Float64 to drop the final narrowing cast as
well. The unweighted size_t levenshteinDistance is unaffected.
Reproduced under ASan+UBSan: pre-fix master overflows in partial_sum.h:34;
post-fix the same queries return finite results with no UBSan report. Existing
tests 03369_function_arrayLevenshtein and 04125_array_levenshtein_types pass
unchanged.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate
Session id: cron:clickhouse-worker-slot-2:20260610-084800 |
|
cc @rschu1ze @Felixoid — could you review this? It fixes a UBSan signed integer overflow in |
|
Workflow [PR], commit [9bc948f] Summary: ✅
AI ReviewSummaryThis PR fixes signed integer overflow in Final VerdictStatus: ✅ Approve |
CI summary for HEAD
|
| Check | Failure | Classification |
|---|---|---|
Integration tests (amd_asan_ubsan, db disk, old analyzer, 2/6) |
test_keeper_snapshot_chunked_transfer::test_concurrent_followers_fetch_snapshot [local_disk]/[remote_disk] |
Chronic flaky Keeper test, unrelated. 14 distinct PRs + 1 master / 30d. Not this PR. |
LLVM Coverage |
Generate LLVM Coverage Diff Report |
Coverage-aggregation infra step; not a test failure. |
Config Workflow / Finish Workflow (earlier) |
changelog-category metadata parse | Resolved: header restored to ### Changelog category (leave one):; re-ran green on this head. |
Mergeable Check / PR |
aggregator | Downstream of the above. |
The arrayLevenshtein change does not touch Keeper, snapshots, or coverage. @Felixoid (function author) has approved.
The previous overflow fix accumulated all weighted distance arithmetic in Float64. That removed the UBSan signed-integer-overflow, but it also changed results for large integer weights that did not overflow before: each add was rounded to the nearest Float64, so a sum like 9007199254740992 + 1 + 1 collapsed to 9007199254740992 instead of 9007199254740994. Sum the dynamic-programming costs (and the arraySimilarity weights_sum) in a wide integer accumulator for integral weight types (Int256 for signed, UInt256 for unsigned), and cast to Float64 only once at the end. wide::integer has defined wraparound rather than signed overflow UB, so the UBSan finding stays fixed, and the wide accumulator is exact for any realistic weight array, so the previously defined integer results are preserved up to the single final Float64 rounding. Floating-point weights keep accumulating in Float64 as before. Extends 04327_array_levenshtein_weighted_overflow with cases that assert the exact integer sums (empty-side shortcut, DP path, and the unsigned accumulator). Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate
Session id: cron:clickhouse-worker-slot-24:20260610-194500 |
The previous fixup accumulated integral weights in Int256/UInt256, the same width as the widest supported weight types. For Int256/UInt256 weight arrays the accumulator could still wrap: an empty-side sum of UInt256::max() + 1 wraps to 0, so arrayLevenshteinDistanceWeighted returned 0 for a positive-weight edit and arraySimilarity reported a wrong value. The 'stay exact / never wrap' contract held for narrower weights but failed at the 256-bit boundary. Make the integral accumulator twice as wide as the weight type (at least 256-bit): Int8..Int128 weights keep a 256-bit accumulator, Int256/UInt256 weights get a 512-bit one. A sum overflows the accumulator only if the array holds more than 2^(weight bits) elements, which is not representable, so integral results stay exact for any feasible input. wide::integer keeps defined wraparound, so the UBSan finding remains fixed. Floating weights still accumulate in Float64. Extends 04327_array_levenshtein_weighted_overflow with UInt256/Int256 boundary cases (max() summed past the 256-bit limit) that previously wrapped. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (HEAD 9bc948f)
Session id: cron:clickhouse-worker-slot-7:20260610-225430 |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 42/48 (87.50%) | Lost baseline coverage: none · Uncovered code |
|
CI finished on `9bc948f72acb` — all green. The earlier PR-metadata gate failure (`pr_body_check.py` / `pr_labels_and_category.py` on `df8a8a9`) is resolved: Config Workflow, Finish Workflow, Mergeable Check, and Style check all pass on the current HEAD. The only non-passing entry is `CH Inc sync` (internal mirror, not part of the public CI gate). Both review threads are addressed: exact integral-weight accumulation restored via a wide (>=256-bit, doubling for Int256/UInt256 weights) accumulator that cannot overflow for any feasible input while staying UBSan-clean; the prior Float64 precision loss and the 256-bit wrap are both gone. Ready for review. |
|
The cloud test is flaky, an issue has been created. It is not related to these changes at all, good to merge. |
|
Hi @groeneai @Felixoid — while reviewing this PR I found the following:
Could you review the test PR and add the |
|
@clickgapai reviewed #107353 — LGTM. The Note: as a fork contributor I cannot apply the |
|
Thanks for the detailed verification, @groeneai! You've confirmed exactly what I suspected: the Your confirmation that the new test in #107353 produces correct output matching its I appreciate you building HEAD and validating the output — that's the kind of rigor that catches silent correctness issues. You're right that a maintainer will need to apply the label. This is a good example of how UBSan fixes can hide untested defensive code paths. Thanks for the thorough follow-up. |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a signed integer overflow (undefined behavior) in
arrayLevenshteinDistanceWeightedandarraySimilaritywhen the weight arrays contain large integer values. The weighted distance is now accumulated in a wide integer for integral weights, so large integer weights no longer overflow and stay exact.Description
levenshteinDistanceWeighted<Element, Weight>did all of its DP arithmetic in the templateWeighttype (the SQL weight array element type). Integer weights near the type maximum (e.g.Int64LLONG_MAX) overflowed at every accumulation: thepartial_sumseeding the row, therow[0]prefix, the three adds insidemin{}, the empty-sidesum_span, and the separateweights_suminarraySimilarity. UBSan reported1 + LLONG_MAX cannot be represented in type 'long'; in release the result was undefined.The functions return
Float64, so the sums are now accumulated inLevenshteinWeightAccumulator<Weight>and cast toFloat64once at the end. For integral weights the accumulator is awide::integertwice as wide as the weight (at least 256-bit, 512-bit forInt256/UInt256weights), so a sum can overflow only with more than2^(weight bits)elements (not representable); integral results therefore stay exact for any feasible input, andwide::integerkeeps defined wraparound rather than signed-overflow UB. Floating weights accumulate inFloat64as before. The unweightedsize_t levenshteinDistanceis unaffected.Reproduced under ASan+UBSan: pre-fix master overflows in
partial_sum.h:34; post-fix the same queries return finite results with no UBSan report. Existing tests03369_function_arrayLevenshteinand04125_array_levenshtein_typespass unchanged. New test04327_array_levenshtein_weighted_overflowcovers the overflow, the exact-integer, and the 256-bit-weight boundary cases.Fuzzer-surfaced (AST fuzzer arm_asan_ubsan, STID 3067-370b). No related open issue found.
Version info
26.6.1.712