This is an automated email from the ASF dual-hosted git repository.

tisonkun pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/datasketches-rust.git


The following commit(s) were added to refs/heads/main by this push:
     new ee261aa  fix(tdigest): handle extreme values and invalid state (#173)
ee261aa is described below

commit ee261aadce0921a62684587db795cbd65d80d718
Author: tison <[email protected]>
AuthorDate: Thu Jul 30 14:08:19 2026 +0800

    fix(tdigest): handle extreme values and invalid state (#173)
    
    Signed-off-by: tison <[email protected]>
---
 datasketches/src/tdigest/sketch.rs        | 57 ++++++++++++++++++++++++++-----
 datasketches/tests/hll_test/union.rs      | 20 ++++++-----
 datasketches/tests/serde_tests/tdigest.rs | 21 ++++++++++++
 datasketches/tests/tdigest_test/sketch.rs | 19 +++++++++++
 4 files changed, 99 insertions(+), 18 deletions(-)

diff --git a/datasketches/src/tdigest/sketch.rs 
b/datasketches/src/tdigest/sketch.rs
index 765ac13..45c9222 100644
--- a/datasketches/src/tdigest/sketch.rs
+++ b/datasketches/src/tdigest/sketch.rs
@@ -577,6 +577,8 @@ impl TDigestMut {
         };
         check_non_nan(min, "min")?;
         check_non_nan(max, "max")?;
+        check_finite(min, "min")?;
+        check_finite(max, "max")?;
         let mut centroids = Vec::with_capacity(num_centroids);
         let mut centroids_weight = 0u64;
         for _ in 0..num_centroids {
@@ -594,9 +596,10 @@ impl TDigestMut {
             check_non_nan(mean, "centroid mean")?;
             check_finite(mean, "centroid")?;
             let weight = check_nonzero(weight, "centroid weight")?;
-            centroids_weight += weight.get();
+            centroids_weight = checked_weight_sum(centroids_weight, 
weight.get())?;
             centroids.push(Centroid { mean, weight });
         }
+        checked_weight_sum(centroids_weight, num_buffered as u64)?;
         let mut buffer = Vec::with_capacity(num_buffered);
         for _ in 0..num_buffered {
             let value = if is_f32 {
@@ -643,6 +646,8 @@ impl TDigestMut {
                 let max = cursor.read_f64_be().map_err(make_error("max"))?;
                 check_non_nan(min, "min in compat double format")?;
                 check_non_nan(max, "max in compat double format")?;
+                check_finite(min, "min in compat double format")?;
+                check_finite(max, "max in compat double format")?;
                 let k = cursor.read_f64_be().map_err(make_error("k"))? as u16;
                 if k < 10 {
                     return Err(Error::deserial(format!(
@@ -654,12 +659,13 @@ impl TDigestMut {
                 let mut total_weight = 0u64;
                 let mut centroids = Vec::with_capacity(num_centroids);
                 for _ in 0..num_centroids {
-                    let weight = 
cursor.read_f64_be().map_err(make_error("weight"))? as u64;
+                    let weight = 
cursor.read_f64_be().map_err(make_error("weight"))?;
                     let mean = 
cursor.read_f64_be().map_err(make_error("mean"))?;
-                    let weight = check_nonzero(weight, "centroid weight in 
compat double format")?;
+                    let weight =
+                        check_compat_weight(weight, "centroid weight in compat 
double format")?;
                     check_non_nan(mean, "centroid mean in compat double 
format")?;
                     check_finite(mean, "centroid mean in compat double 
format")?;
-                    total_weight += weight.get();
+                    total_weight = checked_weight_sum(total_weight, 
weight.get())?;
                     centroids.push(Centroid { mean, weight });
                 }
                 Ok(TDigestMut::make(
@@ -682,6 +688,8 @@ impl TDigestMut {
                 let max = cursor.read_f64_be().map_err(make_error("max"))?;
                 check_non_nan(min, "min in compat float format")?;
                 check_non_nan(max, "max in compat float format")?;
+                check_finite(min, "min in compat float format")?;
+                check_finite(max, "max in compat float format")?;
                 let k = cursor.read_f32_be().map_err(make_error("k"))? as u16;
                 if k < 10 {
                     return Err(Error::deserial(format!(
@@ -696,12 +704,13 @@ impl TDigestMut {
                 let mut total_weight = 0u64;
                 let mut centroids = Vec::with_capacity(num_centroids);
                 for _ in 0..num_centroids {
-                    let weight = 
cursor.read_f32_be().map_err(make_error("weight"))? as u64;
+                    let weight = 
cursor.read_f32_be().map_err(make_error("weight"))? as f64;
                     let mean = 
cursor.read_f32_be().map_err(make_error("mean"))? as f64;
-                    let weight = check_nonzero(weight, "centroid weight in 
compat float format")?;
+                    let weight =
+                        check_compat_weight(weight, "centroid weight in compat 
float format")?;
                     check_non_nan(mean, "centroid mean in compat float 
format")?;
                     check_finite(mean, "centroid mean in compat float 
format")?;
-                    total_weight += weight.get();
+                    total_weight = checked_weight_sum(total_weight, 
weight.get())?;
                     centroids.push(Centroid { mean, weight });
                 }
                 Ok(TDigestMut::make(
@@ -1327,6 +1336,28 @@ fn check_nonzero(value: u64, tag: &'static str) -> 
Result<NonZeroU64, Error> {
         .ok_or_else(|| Error::deserial(format!("malformed data: {tag} cannot 
be zero")))
 }
 
+fn check_compat_weight(value: f64, tag: &'static str) -> Result<NonZeroU64, 
Error> {
+    check_non_nan(value, tag)?;
+    check_finite(value, tag)?;
+    if !(1.0..u64::MAX as f64).contains(&value) {
+        return Err(Error::deserial(format!(
+            "malformed data: {tag} must be representable as a positive u64"
+        )));
+    }
+    if value.trunc() != value {
+        return Err(Error::deserial(format!(
+            "malformed data: {tag} must not have a fractional part"
+        )));
+    }
+    check_nonzero(value as u64, tag)
+}
+
+fn checked_weight_sum(total_weight: u64, weight: u64) -> Result<u64, Error> {
+    total_weight
+        .checked_add(weight)
+        .ok_or_else(|| Error::deserial("malformed data: total weight 
overflow"))
+}
+
 /// Generates cluster sizes proportional to `q*(1-q)`.
 ///
 /// The use of a normalizing function results in a strictly bounded number of 
clusters no matter
@@ -1347,6 +1378,14 @@ mod scale_function {
     }
 }
 
-const fn weighted_average(x1: f64, w1: f64, x2: f64, w2: f64) -> f64 {
-    (x1 * w1 + x2 * w2) / (w1 + w2)
+fn weighted_average(x1: f64, w1: f64, x2: f64, w2: f64) -> f64 {
+    let total_weight = w1 + w2;
+    let ratio = w2 / total_weight;
+    if x1.is_sign_positive() != x2.is_sign_positive() {
+        // Subtracting opposite-signed finite extremes can overflow.
+        x1 * (1. - ratio) + x2 * ratio
+    } else {
+        // Same-sign subtraction is finite and avoids summing two near-maximum 
terms.
+        (x2 - x1).mul_add(ratio, x1)
+    }
 }
diff --git a/datasketches/tests/hll_test/union.rs 
b/datasketches/tests/hll_test/union.rs
index 017f06e..6d6d5d3 100644
--- a/datasketches/tests/hll_test/union.rs
+++ b/datasketches/tests/hll_test/union.rs
@@ -406,24 +406,26 @@ fn test_union_reset() {
 fn test_union_commutativity() {
     // Verify A∪B = B∪A
     let mut sketch_a = HllSketch::new(12, HllType::Hll8);
-    let mut sketch_b = HllSketch::new(12, HllType::Hll8);
-
     for i in 0..1000 {
         sketch_a.update(i);
     }
+
+    let mut sketch_b = HllSketch::new(12, HllType::Hll8);
     for i in 500..1500 {
         sketch_b.update(i);
     }
 
-    let mut union_1 = HllUnion::new(12); // A∪B
-    union_1.update(&sketch_a);
-    union_1.update(&sketch_b);
+    // A∪B
+    let mut union1 = HllUnion::new(12);
+    union1.update(&sketch_a);
+    union1.update(&sketch_b);
 
-    let mut union_2 = HllUnion::new(12); // B∪A
-    union_2.update(&sketch_b);
-    union_2.update(&sketch_a);
+    // B∪A
+    let mut union2 = HllUnion::new(12);
+    union2.update(&sketch_b);
+    union2.update(&sketch_a);
 
-    assert_eq!(union_1.estimate(), union_2.estimate());
+    assert_eq!(union1.estimate(), union2.estimate());
 }
 
 #[test]
diff --git a/datasketches/tests/serde_tests/tdigest.rs 
b/datasketches/tests/serde_tests/tdigest.rs
index bfe4d40..a6251ab 100644
--- a/datasketches/tests/serde_tests/tdigest.rs
+++ b/datasketches/tests/serde_tests/tdigest.rs
@@ -186,3 +186,24 @@ fn test_many_values() {
     assert_eq!(td.rank(500.0), deserialized_td.rank(500.0));
     assert_eq!(td.quantile(0.5), deserialized_td.quantile(0.5));
 }
+
+#[test]
+fn test_large_weights_produce_finite_extreme_quantile() {
+    let lower = f64::from_bits(f64::MAX.to_bits() - 1);
+    let mut tdigest = TDigestMut::default();
+    tdigest.update(lower);
+    tdigest.update(f64::MAX);
+    let mut bytes = tdigest.serialize();
+
+    // These valid weights retain a positive lower contribution even though 
its normalized ratio
+    // rounds away when interpolating between the two extreme values.
+    bytes[40..48].copy_from_slice(&((1_u64 << 52) - 1).to_le_bytes());
+    bytes[56..64].copy_from_slice(&(1_u64 << 52).to_le_bytes());
+
+    let mut tdigest = TDigestMut::deserialize(&bytes, false).unwrap();
+    let quantile = tdigest.quantile(0.25).unwrap();
+    assert!(
+        quantile.is_finite() && (lower..=f64::MAX).contains(&quantile),
+        "quantile must remain within its finite interpolation bounds, got 
{quantile}"
+    );
+}
diff --git a/datasketches/tests/tdigest_test/sketch.rs 
b/datasketches/tests/tdigest_test/sketch.rs
index b61d779..13ca646 100644
--- a/datasketches/tests/tdigest_test/sketch.rs
+++ b/datasketches/tests/tdigest_test/sketch.rs
@@ -229,6 +229,25 @@ fn test_invalid_inputs() {
     assert!(td.is_empty());
 }
 
+#[test]
+fn test_extreme_values_produce_finite_quantiles() {
+    let mut tdigest = TDigestMut::default();
+    for i in 0..10_000 {
+        tdigest.update(if i % 2 == 0 { f64::MAX } else { -f64::MAX });
+    }
+
+    assert_eq!(tdigest.total_weight(), 10_000);
+    assert_eq!(tdigest.min_value(), Some(-f64::MAX));
+    assert_eq!(tdigest.max_value(), Some(f64::MAX));
+    for rank in [0.25, 0.5, 0.75] {
+        let quantile = tdigest.quantile(rank).unwrap();
+        assert!(
+            quantile.is_finite(),
+            "quantile at rank {rank} must be finite, got {quantile}"
+        );
+    }
+}
+
 #[test]
 fn test_estimate_repeat_values() {
     let mut tdigest = TDigestMut::default();


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to