kazantsev-maksim commented on code in PR #5042:
URL: https://github.com/apache/datafusion-comet/pull/5042#discussion_r4130055665
##########
native/spark-expr/src/string_funcs/levenshtein.rs:
##########
@@ -87,399 +179,405 @@ fn levenshtein_distance_with_threshold(s: &str, t: &str,
threshold: i32) -> i32
return -1;
}
+ if s.is_ascii() && t.is_ascii() {
+ let s_bytes = s.as_bytes();
+ let t_bytes = t.as_bytes();
+ let m = s_bytes.len();
+ let n = t_bytes.len();
+
+ if (m as i32 - n as i32).abs() > threshold {
+ return -1;
+ }
+ if m == 0 {
+ return if n as i32 <= threshold { n as i32 } else { -1 };
+ }
+ if n == 0 {
+ return if m as i32 <= threshold { m as i32 } else { -1 };
+ }
+
+ let (s_bytes, t_bytes, m, n) = if m > n {
+ (t_bytes, s_bytes, n, m)
+ } else {
+ (s_bytes, t_bytes, m, n)
+ };
+
+ if (n as i32 - m as i32) > threshold {
+ return -1;
+ }
+
+ let out_of_band = threshold + 1;
Review Comment:
Thanks for identifying the debug overflow finding!
I have resolved the `[P2]` threshold arithmetic overflow issue:
1. **Capped effective threshold:** Since the Levenshtein distance between
strings of length $m$ and $n$ ($m \le n$) can never exceed $n$, we clamp `let
effective_threshold = threshold.min(n as i32);`. This guarantees that
`out_of_band = effective_threshold + 1` never overflows when `threshold ==
i32::MAX`.
2. **Saturating band calculations:** Replaced direct addition with `(j_1 as
usize).saturating_add(effective_threshold as usize).min(m)` and guarded
`min_i`, matching Spark's explicit overflow guard on band endpoints.
3. **Applied to both kernels:** Both ASCII fast-path and Unicode kernels use
this safe arithmetic.
4. **Regression tests:** Added
`test_levenshtein_distance_with_threshold_max_int` testing both `i32::MAX` and
`i32::MAX - 1` on `"frog"` / `"fog"` (ASCII) and `"café"` / `"cafe"` (Unicode).
All tests pass cleanly in debug mode with `-C overflow-checks=yes`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]