tisonkun commented on code in PR #293:
URL: https://github.com/apache/datasketches-rust/pull/293#discussion_r4626437771


##########
datasketches/src/kll/sketch.rs:
##########
@@ -164,6 +164,65 @@ impl<T: Clone + Ord> KllSketch<T> {
         self.internal_update(item);
     }
 
+    /// Updates the sketch with an item repeated `weight` times.
+    ///
+    /// Equivalent to calling [`update`](Self::update) `weight` times. Weights 
that fit in the
+    /// remaining capacity are appended directly to level zero; larger weights 
build an exact
+    /// binary-level representation and merge it in one pass.
+    ///
+    /// A weight of zero is a no-op, unlike DataSketches Java and DataSketches 
C++, which reject

Review Comment:
   Documented under a new `# Cross-language compatibility` section in 8def81e 
(along with codifying the convention in `CONTRIBUTING.md`), and clarified the 
C++ companion link in the PR description. We intentionally keep the `u64::MAX` 
stream-weight domain for consistency with `KllSketch::update` and 
`KllSketch::merge` (which already reach `u64::MAX` and up to 15 items at level 
60 via repeated merges, as in 
`kll_test::core::weight_overflow_preserves_state`). Note that 
`datasketches-cpp` reads `n` as `uint64_t` and accepts individual levels 
exceeding `level_capacity` whenever `num_retained < total_capacity`; the 
cross-language bound is `datasketches-java` reading `n` as signed `long`, so 
the doc now explicitly notes keeping `total_weight() <= i64::MAX as u64` when 
serializing sketches for Java.



##########
tests-integration/tests/kll_test/update.rs:
##########
@@ -0,0 +1,263 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::panic::AssertUnwindSafe;
+use std::panic::catch_unwind;
+
+use datasketches::common::SearchCriteria;
+use datasketches::kll::KllSketch;
+
+const DEFAULT_K: u16 = 200;
+const MIN_K: u16 = 8;
+const NUMERIC_NOISE_TOLERANCE: f64 = 1e-6;
+
+#[test]
+fn zero_weight_is_a_no_op() {
+    let mut sketch = KllSketch::<i64>::new(DEFAULT_K).unwrap();
+    sketch.update_with_weight(10, 0);
+    assert!(sketch.is_empty());
+    assert_eq!(sketch.total_weight(), 0);
+    assert_eq!(sketch.num_retained(), 0);
+    assert_eq!(sketch.min_item(), None);
+    assert_eq!(sketch.max_item(), None);
+
+    sketch.update_with_weight(10, 5);
+    let before = sketch.serialize();
+    sketch.update_with_weight(-100, 0);
+    sketch.update_with_weight(100, 0);
+    assert_eq!(sketch.min_item(), Some(&10));
+    assert_eq!(sketch.max_item(), Some(&10));
+    assert_eq!(sketch.serialize(), before);
+}
+
+#[test]
+fn exact_mode_and_capacity_boundary_match_repeated_updates() {
+    let mut weighted = KllSketch::<i64>::new(DEFAULT_K).unwrap();
+    let mut repeated = KllSketch::<i64>::new(DEFAULT_K).unwrap();
+
+    // Weights 1..=15 sum to 120; adding 80 reaches the exact k=200 capacity 
boundary.
+    for (item, weight) in (1..=15).map(|i| (i, i as u64)).chain([(16, 80)]) {
+        weighted.update_with_weight(item, weight);
+        for _ in 0..weight {
+            repeated.update(item);
+        }
+    }
+
+    assert_eq!(weighted.total_weight(), DEFAULT_K as u64);
+    assert_eq!(weighted.num_retained(), DEFAULT_K as usize);
+    assert!(!weighted.is_estimation_mode());
+    assert_eq!(weighted.serialize(), repeated.serialize());
+
+    // One additional unit crosses capacity and triggers compaction on the 
weight == 1 path.
+    weighted.update_with_weight(17, 1);
+    assert_eq!(weighted.total_weight(), DEFAULT_K as u64 + 1);
+    assert!(weighted.is_estimation_mode());
+    assert_eq!(weighted.max_item(), Some(&17));
+}
+
+#[test]
+fn binary_level_decomposition_and_top_level_folding() {
+    // Cover both an even weight (leaving level zero empty) and an odd 
multi-bit weight.
+    for weight in [1u64 << 40, (1u64 << 40) + 12_345] {
+        let mut sketch = KllSketch::<i64>::new(DEFAULT_K).unwrap();
+        sketch.update_with_weight(7, weight);
+
+        assert_eq!(sketch.total_weight(), weight);
+        assert!(sketch.is_estimation_mode());
+        assert_eq!(sketch.num_retained(), weight.count_ones() as usize);
+        assert_eq!(sketch.sorted_view().total_weight(), weight);
+        assert_eq!(sketch.min_item(), Some(&7));
+        assert_eq!(sketch.max_item(), Some(&7));
+        assert_eq!(sketch.rank(&7, SearchCriteria::Inclusive), Some(1.0));
+        assert_eq!(sketch.rank(&7, SearchCriteria::Exclusive), Some(0.0));
+        assert_eq!(
+            sketch.quantile(0.5, SearchCriteria::Inclusive).unwrap(),
+            Some(7)
+        );
+
+        let bytes = sketch.serialize();
+        let decoded = KllSketch::<i64>::deserialize(&bytes).unwrap();
+        assert_eq!(decoded.serialize(), bytes);
+    }
+
+    // At MIN_K = 8, folding u64::MAX - 8 places 15 copies at level 60 (above 
level_capacity = 8)

Review Comment:
   Added `merging_sparse_and_top_folded_weighted_sketches` in f3e8a23, covering 
`KllSketch::merge` in both directions on a `1 << 40` sparse weighted sketch 
(empty level zero and 39 empty intermediate levels) with unit updates as well 
as merging 61-level top-folded sketches at `MIN_K = 8`, asserting 
`total_weight`, `sorted_view().total_weight()`, `num_retained`, extrema, exact 
ranks, and byte-identical serialization round-trips.



##########
datasketches/src/kll/sketch.rs:
##########
@@ -826,29 +885,58 @@ impl<T: Clone + Ord> KllSketch<T> {
 
     fn merge_higher_levels(&mut self, other: &KllSketch<T>) {
         let provisional_levels = self.levels.len().max(other.levels.len());
-        let mut self_levels = std::mem::take(&mut self.levels);
-        let mut work_levels = vec![Vec::new(); provisional_levels];
-        work_levels[0] = std::mem::take(&mut self_levels[0]);
+        let mut work_levels = std::mem::take(&mut self.levels);
+        work_levels.resize_with(provisional_levels, Vec::new);
 
-        for level in 1..provisional_levels {
-            let left = if level < self_levels.len() {
-                std::mem::take(&mut self_levels[level])
-            } else {
-                Vec::new()
-            };
-            let right = other.levels.get(level).cloned().unwrap_or_default();
+        for (work_level, other_level) in 
work_levels.iter_mut().zip(&other.levels).skip(1) {
+            if !other_level.is_empty() {
+                merge_into_level(work_level, other_level.clone());
+            }
+        }
 
-            work_levels[level] = if left.is_empty() {
-                right
-            } else if right.is_empty() {
-                left
-            } else {
-                merge_sorted_vec(left, right)
-            };
+        self.levels = general_compress(work_levels, self.k, 
self.is_level_zero_sorted);
+        self.refresh_capacity_state();
+    }
+
+    fn merge_weighted(&mut self, item: T, weight: u64, final_n: u64) {
+        debug_assert!(weight >= 2);
+        self.update_min_max(&item);
+        if weight & 1 != 0 {
+            self.internal_update(item.clone());
         }
 
+        // An item at level `h` carries weight `2^h`, so `(weight >> h) & 1` 
copies at each level
+        // form an exact representation of `weight` copies. Bits above 
`MAX_NUM_LEVELS - 1` fold
+        // into `weight >> 60` (at most 15) copies at the top level.

Review Comment:
   Updated to `weight >> (MAX_NUM_LEVELS - 1)` in 8def81e.



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

Reply via email to