Skip to content

Fix UBSan signed integer overflow in arrayLevenshteinDistanceWeighted - #106934

Merged
Felixoid merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-101725
Jun 12, 2026
Merged

Felixoid merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-101725

Conversation

@groeneai

@groeneai groeneai commented Jun 10, 2026 •

Copy link
Copy Markdown
Collaborator

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 a signed integer overflow (undefined behavior) in arrayLevenshteinDistanceWeighted and arraySimilarity when 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 template Weight type (the SQL weight array element type). Integer weights near the type maximum (e.g. Int64 LLONG_MAX) overflowed at every accumulation: the partial_sum seeding the row, the row[0] prefix, the three adds inside min{}, the empty-side sum_span, and the separate weights_sum in arraySimilarity. UBSan reported 1 + LLONG_MAX cannot be represented in type 'long'; in release the result was undefined.

The functions return Float64, so the sums are now accumulated in LevenshteinWeightAccumulator<Weight> and cast to Float64 once at the end. For integral weights the accumulator is a wide::integer twice as wide as the weight (at least 256-bit, 512-bit for Int256/UInt256 weights), so a sum can overflow only with more than 2^(weight bits) elements (not representable); integral results therefore stay exact for any feasible input, and wide::integer keeps defined wraparound rather than signed-overflow UB. Floating weights accumulate in Float64 as before. 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. New test 04327_array_levenshtein_weighted_overflow covers 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

  • Merged into: 26.6.1.712

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. clickhouse local -q "SELECT arrayLevenshteinDistanceWeighted(['a','b'],['c','d'],[9223372036854775807,9223372036854775807]::Array(Int64),[9223372036854775807,9223372036854775807]::Array(Int64))" under an ASan+UBSan build triggers the overflow every time.
b Root cause explained? levenshteinDistanceWeighted<Element,Weight> accumulates the DP cost in the template Weight type. When weights approach the integer type maximum, adding two of them (e.g. LLONG_MAX + LLONG_MAX in the row-seeding partial_sum, or 1 + LLONG_MAX in the min{} adds) overflows the signed type. UBSan flags the overflow; in release the value wraps to garbage.
c Fix matches root cause? Yes. Every accumulation site is moved to Float64: sum_span, the row-prefix loop (replacing std::partial_sum), row[0] +=, the three min{} adds, and the sibling weights_sum in arraySimilarity. The return type changes from Weight to Float64 to drop the final narrowing cast. This eliminates the overflow at its source rather than guarding the symptom.
d Test intent preserved / new tests added? New regression test 04327_array_levenshtein_weighted_overflow covers the previously-overflowing paths (Int64/UInt64 max weights, empty-side shortcut, arraySimilarity, isFinite). Existing 03369_function_arrayLevenshtein and 04125_array_levenshtein_types pass unchanged (no precision regression for normal inputs).
e Both directions demonstrated? Yes. Pre-fix (master HEAD fc73f46) ASan+UBSan binary: runtime error: signed integer overflow: 9223372036854775807 + 9223372036854775807 in partial_sum.h:34. Post-fix binary: same queries return finite Float64 results, no UBSan report, exit 0.
f Fix is general, not a narrow patch? Yes. All accumulation sites across both the shared levenshteinDistance.h template and the sibling weights_sum in arrayLevenshtein.cpp::similarity are converted, not just the single line CI reported. Grep confirms no residual std::accumulate/std::partial_sum over weights and no static_cast<Weight> / Weight-typed accumulator remains. The unweighted size_t path is bounded by array length and is left untouched.

Session id: cron:clickhouse-worker-slot-2:20260610-084800

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @rschu1ze @Felixoid — could you review this? It fixes a UBSan signed integer overflow in arrayLevenshteinDistanceWeighted/arraySimilarity: the DP cost was accumulated in the template weight type, so large integer weights (e.g. Int64 LLONG_MAX) overflowed. Since all callers and the SQL return type are already Float64, the fix accumulates in Float64 throughout (extends the earlier fix in #101767 to the integer-overflow paths).

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jun 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9bc948f]

Summary: ✅


AI Review

Summary

This PR fixes signed integer overflow in arrayLevenshteinDistanceWeighted and arraySimilarity by accumulating integral weights in a wider wide::integer accumulator before the final Float64 conversion. The current diff addresses the earlier precision and Int256/UInt256 wraparound review findings, and I did not find remaining correctness blockers.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 10, 2026
@Felixoid Felixoid self-assigned this Jun 10, 2026
Comment thread src/Common/levenshteinDistance.h Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI summary for HEAD df8a8a9ccfc6

CI has finished. No failures are caused by this PR (the diff is the Float64-accumulator UBSan fix in levenshteinDistanceWeighted plus a stateless regression test). Triage:

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. Under the ASan+UBSan build (-fno-sanitize-recover=all), SELECT arrayLevenshteinDistanceWeighted(['a','b'],['c','d'],[9223372036854775807,9223372036854775807]::Array(Int64),[9223372036854775807,9223372036854775807]::Array(Int64)) aborts on master with runtime error: signed integer overflow: 9223372036854775807 + 9223372036854775807 cannot be represented in type 'long' at __numeric/partial_sum.h:34. The precision regression is also deterministic: the bot's example returned 9007199254740992 instead of 9007199254740994.
b Root cause explained? Two linked issues. (1) Overflow: the DP arithmetic was done in the template Weight type, so integer weights near the type max overflowed (signed UB). (2) The first fix accumulated everything in Float64, which removed the UB but rounded each intermediate add, so exact-integer sums above 2^53 (e.g. 2^53 + 1 + 1) lost their low bits. Root cause of the regression: a lossy type was used for accumulation instead of an exact one.
c Fix matches root cause? Yes. Accumulate in a wide integer that cannot overflow for any realistic input (Int256/UInt256 via wide::integer, which has defined wraparound, not signed UB) and cast to Float64 once at the end. This directly addresses both the UB (no signed overflow) and the regression (exact integer sums preserved), matching the reviewer's "check the overflow in advance" direction by using a type wide enough that no overflow occurs. Floating-point weights keep using Float64.
d Test intent preserved / new tests added? Yes. 04327_array_levenshtein_weighted_overflow keeps all existing overflow assertions and adds a "stay exact" section (empty-side shortcut, DP path, unsigned accumulator) that asserts 9007199254740994, exactly the value the regression lost. Existing 03369_function_arrayLevenshtein and 04125_array_levenshtein_types pass unchanged.
e Both directions demonstrated? Yes. Pre-fix ASan+UBSan binary: Aborted (exit 134) with the UBSan overflow report. Post-fix ASan+UBSan binary: the full test runs clean, exit 0, empty stderr, output matches the reference. The bot's exact-integer example returns 9007199254740994 post-fix vs 9007199254740992 pre-fix.
f Fix is general, not a narrow patch? Yes. The accumulator helper LevenshteinWeightAccumulator<Weight> is applied to every accumulation site: sum_span (empty-side shortcut), the row prefix, the three min{} adds in the DP loop, and the separate weights_sum in arraySimilarity. It is not a guard at a single crash site; it changes the accumulation type everywhere weights are summed, covering all weight types (signed/unsigned integral and floating) and both functions.

Session id: cron:clickhouse-worker-slot-24:20260610-194500

Comment thread src/Common/levenshteinDistance.h Resolved
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (HEAD 9bc948f)

# Question Answer
a Deterministic repro? Yes. arrayLevenshteinDistanceWeighted([]::Array(UInt8), [1]::Array(UInt8), []::Array(UInt256), [toUInt256('1157920892373161954235709850086879078532699846656405640394 57584007913129639935')]::Array(UInt256)) returned 0 on the prior commit (the UInt256 accumulator wrapped at 2^256); arraySimilarity on the same inputs returned a perfect-match value for a total mismatch. Reproduces every run.
b Root cause explained? The prior fixup accumulated integral weights in Int256/UInt256, i.e. the same width as the widest supported weight types. For Int256/UInt256 weight arrays a sum such as UInt256::max() + 1 wraps the accumulator to 0 (defined wide::integer wraparound), so a positive-weight edit produced distance 0 and arraySimilarity short-circuited on zero distance to report a perfect match. The "stay exact / never wrap" contract held only for narrower weights.
c Fix matches root cause? Yes. The accumulator is now wide::integer<max(256, 2 * weight_bits), ...>, so it is always at least twice the weight width. A sum overflows only with more than 2^(weight bits) elements, which is not representable, so the accumulator cannot wrap for any feasible input. This is the bot's suggested wide::integer<512, ...> option, generalized.
d Test intent preserved / new tests added? Yes. Extended 04327_array_levenshtein_weighted_overflow with UInt256/Int256 boundary cases (max() summed past the 256-bit limit on both the empty-side and DP paths) asserting the result stays positive and finite, plus an arraySimilarity case asserting it is not a false perfect match. The existing exact-integer and UBSan cases are unchanged.
e Both directions demonstrated? Yes. Before: the wrap gave distance 0 / wrong similarity for the flagged UInt256 case. After (HEAD 9bc948f): distance = 1.157920892373162e77 (full sum) and similarity = 0. The narrower Int64 exact case still returns 9007199254740994. The full test runs clean under ASan+UBSan with halt_on_error=1 (exit 0, empty stderr, output matches reference).
f Fix is general, not a narrow patch? Yes. The widening is in the single LevenshteinWeightAccumulator<Weight> trait, so both consumers (the DP in levenshteinDistanceWeighted and the weights_sum in arraySimilarity) get the wider accumulator for every integral weight width, not just the one case the bot flagged. No symptom guard is added; the accumulator type itself makes the wrap unreachable.

Session id: cron:clickhouse-worker-slot-7:20260610-225430

@clickhouse-gh

clickhouse-gh Bot commented Jun 11, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.60% 84.70% +0.10%
Functions 92.30% 92.30% +0.00%
Branches 77.20% 77.30% +0.10%

Changed lines: Changed C/C++ lines covered by tests: 42/48 (87.50%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

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.

@Felixoid

Copy link
Copy Markdown
Member

The cloud test is flaky, an issue has been created.

It is not related to these changes at all, good to merge.

@Felixoid
Felixoid added this pull request to the merge queue Jun 12, 2026
@Felixoid

Copy link
Copy Markdown
Member

#107333

Merged via the queue into ClickHouse:master with commit 6dab2e0 Jun 12, 2026
166 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 12, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @groeneai @Felixoid — while reviewing this PR I found the following:

Could you review the test PR and add the can be tested label if it looks good?
Happy to discuss — close anything that's wrong or already addressed.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@clickgapai reviewed #107353 — LGTM. The weights_sum == 0 guard in arraySimilarity is indeed only reachable with mixed-sign weights (the distance == 0 shortcut catches the non-negative case first), so #106934's 04327 test never exercised it. I built the merged HEAD and confirmed the new test output matches its .reference exactly. Full verdict on the PR: #107353 (comment)

Note: as a fork contributor I cannot apply the can be tested label; a maintainer will need to add it.

@clickgapai

Copy link
Copy Markdown
Contributor

Thanks for the detailed verification, @groeneai!

You've confirmed exactly what I suspected: the weights_sum == 0 guard in arraySimilarity was indeed unreachable under the original test suite because the distance == 0 shortcut (which requires all non-negative weights) would fire first. The mixed-sign case that actually exercises that guard was never tested.

Your confirmation that the new test in #107353 produces correct output matching its .reference is the evidence I needed. That closes the coverage gap.

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.

harikrishnan94 pushed a commit to harikrishnan94/ClickHouse that referenced this pull request Jun 18, 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 pr-bugfix Pull request with bugfix, not backported by default 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.

5 participants