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 81ec1cb feat: add tuple sketch implementation (#152)
81ec1cb is described below
commit 81ec1cb181c9ba043e4998c0bad44fd0d8a00899
Author: Yijun Zhao <[email protected]>
AuthorDate: Thu Jul 23 15:43:27 2026 +0800
feat: add tuple sketch implementation (#152)
Co-authored-by: tison <[email protected]>
---
datasketches/Cargo.toml | 1 +
datasketches/src/codec/decode.rs | 10 +
datasketches/src/codec/family.rs | 9 +
datasketches/src/codec/mod.rs | 6 +-
datasketches/src/error.rs | 3 +-
datasketches/src/hash/mod.rs | 19 +-
datasketches/src/lib.rs | 5 +-
datasketches/src/theta/serialization.rs | 5 -
datasketches/src/theta/sketch.rs | 57 +-
datasketches/src/theta/union.rs | 12 +-
datasketches/src/thetacommon/constants.rs | 10 +
datasketches/src/thetacommon/hash_table.rs | 53 ++
datasketches/src/thetacommon/union.rs | 30 +-
datasketches/src/tuple/hash_table.rs | 461 +++++++++++
datasketches/src/tuple/mod.rs | 49 ++
datasketches/src/tuple/policy.rs | 76 ++
datasketches/src/tuple/serialization.rs | 126 +++
datasketches/src/tuple/sketch.rs | 1004 ++++++++++++++++++++++++
datasketches/tests/tuple_serialization_test.rs | 110 +++
datasketches/tests/tuple_sketch_test.rs | 324 ++++++++
20 files changed, 2301 insertions(+), 69 deletions(-)
diff --git a/datasketches/Cargo.toml b/datasketches/Cargo.toml
index eb299e8..d4db61e 100644
--- a/datasketches/Cargo.toml
+++ b/datasketches/Cargo.toml
@@ -45,6 +45,7 @@ frequencies = []
hll = []
tdigest = []
theta = []
+tuple = []
[dev-dependencies]
googletest = { workspace = true }
diff --git a/datasketches/src/codec/decode.rs b/datasketches/src/codec/decode.rs
index 37c1523..d2f2364 100644
--- a/datasketches/src/codec/decode.rs
+++ b/datasketches/src/codec/decode.rs
@@ -38,6 +38,16 @@ impl SketchSlice<'_> {
self.slice.set_position(pos + n);
}
+ /// Returns the not-yet-read portion of the underlying slice.
+ ///
+ /// Useful for handing the remaining bytes to a variable-length decoder
that reports how many
+ /// bytes it consumed; pair it with [`advance`](Self::advance).
+ pub fn remaining(&self) -> &[u8] {
+ let buf = self.slice.get_ref();
+ let pos = (self.slice.position() as usize).min(buf.len());
+ &buf[pos..]
+ }
+
/// Reads exactly `buf.len()` bytes from the slice into `buf`.
pub fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
self.slice.read_exact(buf)
diff --git a/datasketches/src/codec/family.rs b/datasketches/src/codec/family.rs
index cc1ce45..c6ab908 100644
--- a/datasketches/src/codec/family.rs
+++ b/datasketches/src/codec/family.rs
@@ -53,6 +53,15 @@ impl Family {
max_pre_longs: 1,
};
+ /// Tuple Sketch for cardinality estimation with per-key summaries.
+ #[cfg(feature = "tuple")]
+ pub const TUPLE: Family = Family {
+ id: 9,
+ name: "TUPLE",
+ min_pre_longs: 1,
+ max_pre_longs: 3,
+ };
+
/// The Frequency family of sketches.
#[cfg(feature = "frequencies")]
pub const FREQUENCY: Family = Family {
diff --git a/datasketches/src/codec/mod.rs b/datasketches/src/codec/mod.rs
index 5b78f53..30d1075 100644
--- a/datasketches/src/codec/mod.rs
+++ b/datasketches/src/codec/mod.rs
@@ -29,7 +29,8 @@ pub use self::encode::SketchBytes;
feature = "frequencies",
feature = "hll",
feature = "tdigest",
- feature = "theta"
+ feature = "theta",
+ feature = "tuple",
))]
#[allow(dead_code)] // some utilities are only used for certain sketches
pub(crate) mod assert;
@@ -41,6 +42,7 @@ pub(crate) mod assert;
feature = "frequencies",
feature = "hll",
feature = "tdigest",
- feature = "theta"
+ feature = "theta",
+ feature = "tuple",
))]
pub(crate) mod family;
diff --git a/datasketches/src/error.rs b/datasketches/src/error.rs
index 8ec5c10..6e614ee 100644
--- a/datasketches/src/error.rs
+++ b/datasketches/src/error.rs
@@ -89,8 +89,7 @@ impl Error {
}
}
-// pub(crate) convenient constructors
-#[allow(dead_code)] // some constructors are only used for certain sketches
+#[allow(dead_code)] // some convenient constructors are only used for certain
sketches
impl Error {
pub(crate) fn invalid_argument(msg: impl Into<String>) -> Self {
Self::new(ErrorKind::InvalidArgument, msg)
diff --git a/datasketches/src/hash/mod.rs b/datasketches/src/hash/mod.rs
index 0a77759..ef4d745 100644
--- a/datasketches/src/hash/mod.rs
+++ b/datasketches/src/hash/mod.rs
@@ -20,7 +20,8 @@
feature = "cpc",
feature = "frequencies",
feature = "hll",
- feature = "theta"
+ feature = "theta",
+ feature = "tuple",
))]
mod murmurhash;
#[cfg(any(
@@ -28,7 +29,8 @@ mod murmurhash;
feature = "cpc",
feature = "frequencies",
feature = "hll",
- feature = "theta"
+ feature = "theta",
+ feature = "tuple",
))]
pub(crate) use self::murmurhash::MurmurHash3X64128;
@@ -56,7 +58,8 @@ pub(crate) use self::xxhash::XxHash64;
feature = "cpc",
feature = "frequencies",
feature = "hll",
- feature = "theta"
+ feature = "theta",
+ feature = "tuple",
))]
pub(crate) const DEFAULT_UPDATE_SEED: u64 = 9001;
@@ -68,7 +71,12 @@ pub(crate) const DEFAULT_UPDATE_SEED: u64 = 9001;
/// # Panics
///
/// Panics if the computed seed hash is zero.
-#[cfg(any(feature = "countmin", feature = "cpc", feature = "theta"))]
+#[cfg(any(
+ feature = "countmin",
+ feature = "cpc",
+ feature = "theta",
+ feature = "tuple",
+))]
pub(crate) fn compute_seed_hash(seed: u64) -> u16 {
use std::hash::Hasher;
@@ -91,7 +99,8 @@ pub(crate) fn compute_seed_hash(seed: u64) -> u16 {
feature = "cpc",
feature = "frequencies",
feature = "hll",
- feature = "theta"
+ feature = "theta",
+ feature = "tuple",
))]
fn read_u64_le(bytes: &[u8]) -> u64 {
let mut buf = [0u8; 8];
diff --git a/datasketches/src/lib.rs b/datasketches/src/lib.rs
index 90510d5..deeb271 100644
--- a/datasketches/src/lib.rs
+++ b/datasketches/src/lib.rs
@@ -45,8 +45,11 @@ pub mod hll;
pub mod tdigest;
#[cfg(feature = "theta")]
pub mod theta;
-#[cfg(feature = "theta")]
+#[cfg(any(feature = "theta", feature = "tuple"))]
+#[allow(dead_code)] // some utilities are only used for certain sketches
pub mod thetacommon;
+#[cfg(feature = "tuple")]
+pub mod tuple;
// common modules
pub mod codec;
diff --git a/datasketches/src/theta/serialization.rs
b/datasketches/src/theta/serialization.rs
index ad54307..54ba181 100644
--- a/datasketches/src/theta/serialization.rs
+++ b/datasketches/src/theta/serialization.rs
@@ -23,8 +23,3 @@ pub(super) const COMPRESSED_SERIAL_VERSION: u8 = 4;
pub(super) const V2_PREAMBLE_EMPTY: u8 = 1;
pub(super) const V2_PREAMBLE_PRECISE: u8 = 2;
pub(super) const V2_PREAMBLE_ESTIMATE: u8 = 3;
-
-pub(super) const FLAGS_IS_READ_ONLY: u8 = 1 << 1;
-pub(super) const FLAGS_IS_EMPTY: u8 = 1 << 2;
-pub(super) const FLAGS_IS_COMPACT: u8 = 1 << 3;
-pub(super) const FLAGS_IS_ORDERED: u8 = 1 << 4;
diff --git a/datasketches/src/theta/sketch.rs b/datasketches/src/theta/sketch.rs
index 5821415..1d26c8d 100644
--- a/datasketches/src/theta/sketch.rs
+++ b/datasketches/src/theta/sketch.rs
@@ -46,6 +46,10 @@ use crate::theta::serialization::V2_PREAMBLE_PRECISE;
use crate::thetacommon::RawThetaSketchView;
use crate::thetacommon::binomial_bounds;
use crate::thetacommon::constants::DEFAULT_LG_K;
+use crate::thetacommon::constants::FLAGS_IS_COMPACT;
+use crate::thetacommon::constants::FLAGS_IS_EMPTY;
+use crate::thetacommon::constants::FLAGS_IS_ORDERED;
+use crate::thetacommon::constants::FLAGS_IS_READ_ONLY;
use crate::thetacommon::constants::MAX_LG_K;
use crate::thetacommon::constants::MAX_THETA;
use crate::thetacommon::constants::MIN_LG_K;
@@ -220,25 +224,18 @@ impl ThetaSketch {
/// assert_eq!(compact.num_retained(), 1);
/// ```
pub fn compact(&self, ordered: bool) -> CompactThetaSketch {
- let mut entries: Vec<u64> = self.iter().map(|entry|
entry.hash()).collect();
-
- let empty = self.is_empty();
- let theta = if empty {
- // Match Java's correctThetaOnCompact() behavior for never-updated
sketches
- // initialized with p < 1.0.
- MAX_THETA
- } else {
- self.table.theta()
- };
- let is_single = entries.len() == 1 && theta == MAX_THETA;
- // Empty or Single-item sketches are always ordered (Java
compatibility)
- let ordered = ordered || empty || is_single;
-
- if ordered && entries.len() > 1 {
- entries.sort_unstable();
- }
-
- CompactThetaSketch::from_parts(entries, theta, self.table.seed_hash(),
ordered, empty)
+ let parts = self.table.to_compact_parts(ordered);
+ CompactThetaSketch::from_parts(
+ parts
+ .entries
+ .into_iter()
+ .map(|entry| entry.hash())
+ .collect(),
+ parts.theta,
+ parts.seed_hash,
+ parts.ordered,
+ parts.empty,
+ )
}
/// Returns the approximate lower error bound given the specified number
of Standard Deviations.
@@ -467,13 +464,13 @@ impl CompactThetaSketch {
bytes.write_u16_be(0); // unused for compact
let mut flags = 0u8;
- flags |= serialization::FLAGS_IS_READ_ONLY;
- flags |= serialization::FLAGS_IS_COMPACT;
+ flags |= FLAGS_IS_READ_ONLY;
+ flags |= FLAGS_IS_COMPACT;
if self.is_empty() {
- flags |= serialization::FLAGS_IS_EMPTY;
+ flags |= FLAGS_IS_EMPTY;
}
if self.is_ordered() {
- flags |= serialization::FLAGS_IS_ORDERED;
+ flags |= FLAGS_IS_ORDERED;
}
bytes.write_u8(flags);
@@ -510,9 +507,9 @@ impl CompactThetaSketch {
bytes.write_u8(num_entries_bytes);
let mut flags = 0u8;
- flags |= serialization::FLAGS_IS_READ_ONLY;
- flags |= serialization::FLAGS_IS_COMPACT;
- flags |= serialization::FLAGS_IS_ORDERED;
+ flags |= FLAGS_IS_READ_ONLY;
+ flags |= FLAGS_IS_COMPACT;
+ flags |= FLAGS_IS_ORDERED;
bytes.write_u8(flags);
bytes.write_u16_le(self.seed_hash);
@@ -748,7 +745,7 @@ impl CompactThetaSketch {
.read_u16_le()
.map_err(insufficient_data("seed_hash"))?;
- let empty = (flags & serialization::FLAGS_IS_EMPTY) != 0;
+ let empty = (flags & FLAGS_IS_EMPTY) != 0;
let mut theta = MAX_THETA;
let num_entries;
let mut entries = vec![];
@@ -776,7 +773,7 @@ impl CompactThetaSketch {
}
entries = Self::read_entries(&mut cursor, num_entries as usize,
theta)?;
}
- let ordered = (flags & serialization::FLAGS_IS_ORDERED) != 0;
+ let ordered = (flags & FLAGS_IS_ORDERED) != 0;
Ok(Self {
entries,
theta,
@@ -797,7 +794,7 @@ impl CompactThetaSketch {
let seed_hash = cursor
.read_u16_le()
.map_err(insufficient_data("seed_hash"))?;
- let empty = (flags & serialization::FLAGS_IS_EMPTY) != 0;
+ let empty = (flags & FLAGS_IS_EMPTY) != 0;
if !empty {
let expected_seed_hash = compute_seed_hash(expected_seed);
if seed_hash != expected_seed_hash {
@@ -861,7 +858,7 @@ impl CompactThetaSketch {
}
}
- let ordered = (flags & serialization::FLAGS_IS_ORDERED) != 0;
+ let ordered = (flags & FLAGS_IS_ORDERED) != 0;
Ok(Self {
entries,
diff --git a/datasketches/src/theta/union.rs b/datasketches/src/theta/union.rs
index 9f19513..06ec617 100644
--- a/datasketches/src/theta/union.rs
+++ b/datasketches/src/theta/union.rs
@@ -60,17 +60,17 @@ impl ThetaUnion {
/// Return this union as a compact sketch.
pub fn to_sketch(&self, ordered: bool) -> CompactThetaSketch {
- let result = self.raw.result(ordered);
+ let parts = self.raw.to_compact_parts(ordered);
CompactThetaSketch::from_parts(
- result
+ parts
.entries
.into_iter()
.map(|entry| entry.hash())
.collect(),
- result.theta,
- result.seed_hash,
- result.ordered,
- result.empty,
+ parts.theta,
+ parts.seed_hash,
+ parts.ordered,
+ parts.empty,
)
}
diff --git a/datasketches/src/thetacommon/constants.rs
b/datasketches/src/thetacommon/constants.rs
index c0c7bb2..da1480b 100644
--- a/datasketches/src/thetacommon/constants.rs
+++ b/datasketches/src/thetacommon/constants.rs
@@ -34,3 +34,13 @@ pub const HASH_TABLE_REBUILD_THRESHOLD: f64 = 15.0 / 16.0;
pub const STRIDE_HASH_BITS: u8 = 7;
pub const STRIDE_MASK: u64 = (1 << STRIDE_HASH_BITS) - 1;
+
+// Flag bits of the flags byte in the Theta-family wire format, shared by
Theta and Tuple sketches.
+/// Flags byte bit: the sketch is read-only.
+pub const FLAGS_IS_READ_ONLY: u8 = 1 << 1;
+/// Flags byte bit: the sketch is logically empty.
+pub const FLAGS_IS_EMPTY: u8 = 1 << 2;
+/// Flags byte bit: the sketch is in compact form.
+pub const FLAGS_IS_COMPACT: u8 = 1 << 3;
+/// Flags byte bit: retained entries are ordered by ascending hash.
+pub const FLAGS_IS_ORDERED: u8 = 1 << 4;
diff --git a/datasketches/src/thetacommon/hash_table.rs
b/datasketches/src/thetacommon/hash_table.rs
index 91c43fc..e17a453 100644
--- a/datasketches/src/thetacommon/hash_table.rs
+++ b/datasketches/src/thetacommon/hash_table.rs
@@ -27,10 +27,26 @@ use crate::thetacommon::constants::MAX_THETA;
use crate::thetacommon::constants::MIN_LG_K;
use crate::thetacommon::constants::STRIDE_MASK;
+/// Raw compact-sketch state from which a sketch family creates its compact
result type.
+#[derive(Debug)]
+pub struct RawCompactParts<E> {
+ pub entries: Vec<E>,
+ pub theta: u64,
+ pub seed_hash: u16,
+ pub ordered: bool,
+ pub empty: bool,
+}
+
/// Generic hash-table mechanics shared by Theta and Tuple sketches.
///
/// The entry type supplies the retained hash and any sketch-specific payload.
The table owns all
/// theta screening, probing, resizing, rebuilding, trimming, and
logical-empty state.
+///
+/// It maintains an array with capacity up to 2^lg_max_size:
+/// * Before it reaches the max capacity, it will extend the array based on
resize_factor.
+/// * After it reaches the capacity bigger than 2^lg_nom_size, every time the
number of entries
+/// exceeds the threshold, it will rebuild the table: only keep the min
2^lg_nom_size entries and
+/// update the theta to the k-th smallest entry.
#[derive(Debug)]
pub struct RawHashTable<E> {
lg_cur_size: u8,
@@ -125,6 +141,16 @@ where
/// Inserts or updates the entry slot for a pre-hashed key.
///
+ /// The callback `f` is invoked with the current entry for `hash`:
+ /// * `Some(existing)` if the key is already retained. The callback should
modify it in place;
+ /// its return value is ignored.
+ /// * `None` if the key is new. The callback returns `Some(entry)` to
insert it, or `None` to
+ /// decline insertion.
+ ///
+ /// Using a single callback ensures any captured update value is consumed
exactly once, so it
+ /// works for both the update sketch (folding an update value) and set
operations (merging an
+ /// incoming entry) without requiring the value to be `Copy` or `Clone`.
+ ///
/// Returns true if a new entry was created, false otherwise (existing
key, declined insertion,
/// or a hash screened out by theta).
pub fn upsert_entry<F>(&mut self, hash: u64, f: F) -> bool
@@ -234,6 +260,33 @@ where
self.entries.iter().filter_map(Option::as_ref)
}
+ /// Returns the retained entries and theta as raw compact-sketch parts.
+ ///
+ /// An empty table reports `MAX_THETA` rather than its current theta,
matching Java's
+ /// `correctThetaOnCompact()` behavior for never-updated sketches
initialized with p < 1.0.
+ /// Empty and single-entry exact-mode results are always marked ordered
(Java/C++
+ /// compatibility).
+ pub fn to_compact_parts(&self, ordered: bool) -> RawCompactParts<E>
+ where
+ E: Clone,
+ {
+ let mut entries: Vec<E> = self.iter_entries().cloned().collect();
+ let empty = self.is_empty();
+ let theta = if empty { MAX_THETA } else { self.theta() };
+ let is_single = entries.len() == 1 && theta == MAX_THETA;
+ let ordered = ordered || empty || is_single;
+ if ordered && entries.len() > 1 {
+ entries.sort_unstable_by_key(RawHashTableEntry::hash);
+ }
+ RawCompactParts {
+ entries,
+ theta,
+ seed_hash: self.seed_hash(),
+ ordered,
+ empty,
+ }
+ }
+
/// Return number of all entries.
#[cfg(test)]
pub fn num_entries(&self) -> usize {
diff --git a/datasketches/src/thetacommon/union.rs
b/datasketches/src/thetacommon/union.rs
index 4392d62..c9ea9fe 100644
--- a/datasketches/src/thetacommon/union.rs
+++ b/datasketches/src/thetacommon/union.rs
@@ -20,6 +20,7 @@ use crate::error::Error;
use crate::thetacommon::RawHashTableEntry;
use crate::thetacommon::RawThetaSketchView;
use crate::thetacommon::constants::MAX_THETA;
+use crate::thetacommon::hash_table::RawCompactParts;
use crate::thetacommon::hash_table::RawHashTable;
/// Merges an incoming entry into an existing entry with the same hash.
@@ -38,16 +39,6 @@ pub struct RawThetaUnion<E, P> {
union_theta: u64,
}
-/// Raw compact-union state from which a sketch family creates its compact
result type.
-#[derive(Debug)]
-pub struct RawThetaUnionResult<E> {
- pub entries: Vec<E>,
- pub theta: u64,
- pub seed_hash: u16,
- pub ordered: bool,
- pub empty: bool,
-}
-
impl<E, P> RawThetaUnion<E, P>
where
E: RawHashTableEntry,
@@ -107,16 +98,18 @@ where
Ok(())
}
- /// Return the current compact-union state.
- pub fn result(&self, ordered: bool) -> RawThetaUnionResult<E>
+ /// Return the current compact-union state as raw compact-sketch parts.
+ pub fn to_compact_parts(&self, ordered: bool) -> RawCompactParts<E>
where
E: Clone,
{
+ let seed_hash = self.table.seed_hash();
+
if self.table.is_empty() {
- return RawThetaUnionResult {
- entries: Vec::new(),
+ return RawCompactParts {
+ entries: vec![],
theta: self.union_theta,
- seed_hash: self.table.seed_hash(),
+ seed_hash,
ordered: true,
empty: true,
};
@@ -145,10 +138,10 @@ where
entries.sort_unstable_by_key(RawHashTableEntry::hash);
}
- RawThetaUnionResult {
+ RawCompactParts {
entries,
theta,
- seed_hash: self.table.seed_hash(),
+ seed_hash,
ordered,
empty: false,
}
@@ -237,8 +230,9 @@ mod tests {
})
.unwrap();
+ let parts = union.to_compact_parts(true);
assert_eq!(
- union.result(true).entries,
+ parts.entries,
vec![TestEntry {
hash: 1,
summary: 5,
diff --git a/datasketches/src/tuple/hash_table.rs
b/datasketches/src/tuple/hash_table.rs
new file mode 100644
index 0000000..9fed59f
--- /dev/null
+++ b/datasketches/src/tuple/hash_table.rs
@@ -0,0 +1,461 @@
+// 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::hash::Hash;
+use std::num::NonZeroU64;
+
+use crate::thetacommon::RawHashTableEntry;
+use crate::thetacommon::hash_table::RawHashTable;
+
+/// A retained entry in a Tuple sketch: a hash key together with its
associated summary.
+#[derive(Debug, Clone)]
+pub struct TupleEntry<S> {
+ // Note that this field is stored as `NonZeroU64` (hash 0 is screened out
before insertion),
+ // so `Option<TupleEntry<S>>` keeps the niche and takes no more space than
`TupleEntry<S>`
+ // itself.
+ hash: NonZeroU64,
+ summary: S,
+}
+
+impl<S> TupleEntry<S> {
+ /// Creates an entry from a hash known to be non-zero.
+ ///
+ /// # Panics
+ ///
+ /// Panics if `hash` is zero.
+ pub(crate) fn new(hash: u64, summary: S) -> Self {
+ let hash = NonZeroU64::new(hash).expect("hash must be non-zero");
+ Self { hash, summary }
+ }
+
+ /// Return the hash used as this entry's key.
+ pub fn hash(&self) -> u64 {
+ self.hash.get()
+ }
+
+ /// Returns the summary stored in this entry.
+ pub fn summary(&self) -> &S {
+ &self.summary
+ }
+}
+
+/// Specific hash table for tuple sketch.
+///
+/// This is the Theta sketch hash table extended so that each retained key
carries a user-defined
+/// summary. Unlike the Theta hash table, when a key is inserted that already
exists, the incoming
+/// update is merged into the existing summary rather than discarded.
+pub(super) type TupleHashTable<S> = RawHashTable<TupleEntry<S>>;
+
+impl<S> RawHashTableEntry for TupleEntry<S> {
+ fn hash(&self) -> u64 {
+ self.hash.get()
+ }
+}
+
+impl<S> TupleHashTable<S> {
+ /// Hashes a key and inserts or updates its summary via a single callback.
+ ///
+ /// See [`try_insert_hash`](Self::try_insert_hash) for the callback
contract. Returns true if a
+ /// new entry was created, false if the key already existed or the hash
was screened out by
+ /// theta.
+ pub fn try_insert<T, F>(&mut self, key: T, f: F) -> bool
+ where
+ T: Hash,
+ F: FnOnce(Option<&mut S>) -> Option<S>,
+ {
+ let hash = self.hash(key);
+ self.try_insert_hash(hash, f)
+ }
+
+ /// Inserts or updates the summary slot for a pre-hashed key.
+ ///
+ /// Returns true if a new entry was created, false otherwise (existing
key, declined insertion,
+ /// or a hash screened out by theta).
+ pub fn try_insert_hash<F>(&mut self, hash: u64, f: F) -> bool
+ where
+ F: FnOnce(Option<&mut S>) -> Option<S>,
+ {
+ self.upsert_entry(hash, |existing| match existing {
+ Some(entry) => {
+ f(Some(&mut entry.summary));
+ None
+ }
+ None => f(None).map(|summary| TupleEntry::new(hash, summary)),
+ })
+ }
+
+ /// Returns an iterator over retained entries as `(hash, &summary)` pairs.
+ pub fn iter(&self) -> impl Iterator<Item = (u64, &S)> + '_ {
+ self.iter_entries()
+ .map(|entry| (entry.hash.get(), &entry.summary))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::common::ResizeFactor;
+ use crate::hash::DEFAULT_UPDATE_SEED;
+ use crate::thetacommon::constants::MAX_THETA;
+ use crate::thetacommon::constants::MIN_LG_K;
+ use crate::thetacommon::hash_table::starting_sub_multiple;
+ use
crate::thetacommon::hash_table::starting_theta_from_sampling_probability;
+
+ impl TupleHashTable<u64> {
+ /// Inserts a key with count-style summary semantics: a new key starts
at 1, a repeated key
+ /// increments the retained count. Returns true if a new entry was
created.
+ fn insert(&mut self, value: impl Hash) -> bool {
+ self.try_insert(value, |existing| match existing {
+ Some(count) => {
+ *count += 1;
+ None
+ }
+ None => Some(1),
+ })
+ }
+
+ /// Returns the retained `(hash, count)` pairs.
+ fn pairs(&self) -> Vec<(u64, u64)> {
+ self.iter().map(|(hash, &count)| (hash, count)).collect()
+ }
+ }
+
+ #[test]
+ fn option_entry_keeps_nonzero_niche() {
+ // The NonZeroU64 hash gives Option<TupleEntry<S>> a niche, so table
slots carry no
+ // discriminant overhead on top of the entry itself.
+ assert_eq!(
+ size_of::<Option<TupleEntry<u64>>>(),
+ size_of::<TupleEntry<u64>>()
+ );
+ }
+
+ #[test]
+ fn test_new_hash_table() {
+ let table = TupleHashTable::<u64>::new(8, ResizeFactor::X8, 1.0,
DEFAULT_UPDATE_SEED);
+
+ assert_eq!(
+ table.lg_cur_size(),
+ starting_sub_multiple(8 + 1, MIN_LG_K, ResizeFactor::X8.lg_value())
+ );
+ assert_eq!(table.theta(),
starting_theta_from_sampling_probability(1.0));
+ assert_eq!(table.num_retained(), 0);
+ assert!(table.is_empty());
+ assert_eq!(table.iter().count(), 0);
+ }
+
+ #[test]
+ fn test_hash_and_theta_screen_behavior() {
+ let mut table = TupleHashTable::<u64>::new(8, ResizeFactor::X8, 1.0,
DEFAULT_UPDATE_SEED);
+
+ // With MAX_THETA, hashes are computed normally.
+ let hash1 = table.hash("test1");
+ let hash2 = table.hash("test2");
+ assert_ne!(hash1, 0);
+ assert_ne!(hash2, 0);
+ assert_ne!(hash1, hash2);
+
+ // With low theta, update should be screened out.
+ table.set_theta(1);
+ assert!(!table.insert("test3"));
+ }
+
+ #[test]
+ fn test_insert() {
+ let mut table = TupleHashTable::<u64>::new(5, ResizeFactor::X8, 1.0,
DEFAULT_UPDATE_SEED);
+
+ assert!(table.insert("test_value"));
+ assert_eq!(table.num_retained(), 1);
+ assert!(!table.is_empty());
+
+ // Insert the same value again: not a new entry, but the summary is
merged.
+ assert!(!table.insert("test_value"));
+ assert_eq!(table.num_retained(), 1);
+ assert_eq!(table.pairs(), vec![(table.hash("test_value"), 2)]);
+
+ // Force screening and verify insertion fails
+ table.set_theta(1);
+ assert!(!table.insert("screened"));
+ assert_eq!(table.num_retained(), 1);
+ assert!(!table.is_empty());
+ }
+
+ #[test]
+ fn test_insert_multiple_values() {
+ let mut table = TupleHashTable::<u64>::new(8, ResizeFactor::X8, 1.0,
DEFAULT_UPDATE_SEED);
+
+ let mut inserted_count = 0;
+ for i in 0..10 {
+ if table.insert(format!("value_{}", i)) {
+ inserted_count += 1;
+ }
+ }
+
+ assert_eq!(table.num_retained(), inserted_count);
+ assert!(!table.is_empty());
+ assert_eq!(table.iter().count(), inserted_count);
+ }
+
+ #[test]
+ fn test_summary_is_merged_on_collision() {
+ let mut table = TupleHashTable::<u64>::new(8, ResizeFactor::X8, 1.0,
DEFAULT_UPDATE_SEED);
+
+ for _ in 0..5 {
+ table.insert("same_key");
+ }
+
+ assert_eq!(table.num_retained(), 1);
+ assert_eq!(table.pairs(), vec![(table.hash("same_key"), 5)]);
+ }
+
+ #[test]
+ fn test_resize() {
+ fn populate_values(table: &mut TupleHashTable<u64>, count: usize) ->
usize {
+ let mut inserted = 0;
+ for i in 0..count {
+ if table.insert(format!("value_{i}")) {
+ inserted += 1;
+ }
+ }
+ inserted
+ }
+
+ {
+ let mut table =
+ TupleHashTable::<u64>::new(8, ResizeFactor::X2, 1.0,
DEFAULT_UPDATE_SEED);
+
+ assert_eq!(table.num_entries(), 32);
+
+ // Insert enough values to trigger resize (50% threshold)
+ // Capacity = 32 * 0.5 = 16
+ let inserted = populate_values(&mut table, 20);
+
+ assert!(table.num_retained() > 0);
+ assert_eq!(table.num_retained(), inserted);
+ assert_eq!(table.num_entries(), 64);
+ }
+
+ {
+ let mut table =
+ TupleHashTable::<u64>::new(8, ResizeFactor::X4, 1.0,
DEFAULT_UPDATE_SEED);
+
+ assert_eq!(table.num_entries(), 32);
+
+ let inserted = populate_values(&mut table, 20);
+
+ assert!(table.num_retained() > 0);
+ assert_eq!(table.num_retained(), inserted);
+ assert_eq!(table.num_entries(), 128);
+ }
+ }
+
+ #[test]
+ fn test_rebuild() {
+ let mut table = TupleHashTable::<u64>::new(5, ResizeFactor::X8, 1.0,
DEFAULT_UPDATE_SEED);
+
+ assert_eq!(table.lg_cur_size(), 6);
+ assert_eq!(table.num_entries(), 64);
+ assert_eq!(table.theta(), MAX_THETA);
+
+ // Insert many values to trigger rebuild
+ for i in 0..100 {
+ table.insert(format!("value_{i}"));
+ }
+
+ let new_theta = table.theta();
+ assert!(
+ new_theta < MAX_THETA,
+ "Theta should be reduced after rebuild"
+ );
+
+ // Continue to insert values to trigger rebuild again
+ for i in 100..200 {
+ table.insert(format!("value_{i}"));
+ }
+
+ assert_eq!(table.lg_cur_size(), 6);
+ assert!(table.num_entries() >= 64);
+ assert!(table.theta() < new_theta);
+ }
+
+ #[test]
+ fn test_trim() {
+ let mut table = TupleHashTable::<u64>::new(5, ResizeFactor::X8, 1.0,
DEFAULT_UPDATE_SEED);
+
+ for i in 0..100 {
+ table.insert(format!("value_{i}"));
+ }
+
+ let before_trim = table.num_retained();
+ assert!(before_trim > 32);
+
+ table.trim();
+ let after_trim = table.num_retained();
+ assert!(after_trim <= 32);
+ assert!(table.theta() < MAX_THETA);
+ }
+
+ #[test]
+ fn test_trim_when_not_needed() {
+ let mut table = TupleHashTable::<u64>::new(8, ResizeFactor::X8, 1.0,
DEFAULT_UPDATE_SEED);
+
+ for i in 0..10 {
+ table.insert(format!("value_{i}"));
+ }
+
+ let before_trim = table.num_retained();
+ let before_theta = table.theta();
+ table.trim();
+ let after_trim = table.num_retained();
+
+ assert_eq!(before_trim, after_trim);
+ assert_eq!(before_theta, table.theta());
+ }
+
+ #[test]
+ fn test_reset() {
+ let mut table = TupleHashTable::<u64>::new(8, ResizeFactor::X8, 1.0,
DEFAULT_UPDATE_SEED);
+ let init_theta = table.theta();
+ let init_lg_cur = table.lg_cur_size();
+ let init_entries = table.num_entries();
+
+ for i in 0..10 {
+ table.insert(format!("value_{i}"));
+ }
+
+ assert!(!table.is_empty());
+ assert!(table.num_retained() > 0);
+
+ table.reset();
+
+ assert!(table.is_empty());
+ assert_eq!(table.num_retained(), 0);
+ assert_eq!(table.theta(), init_theta);
+ assert_eq!(table.lg_cur_size(), init_lg_cur);
+ assert_eq!(table.num_entries(), init_entries);
+ assert_eq!(table.iter().count(), 0);
+ }
+
+ #[test]
+ fn test_table_with_sampling() {
+ let mut table = TupleHashTable::<u64>::new(
+ 8,
+ ResizeFactor::X8,
+ 0.5, // sampling_probability = 0.5
+ DEFAULT_UPDATE_SEED,
+ );
+ assert_eq!(table.theta(), (MAX_THETA as f64 * 0.5) as u64);
+
+ for i in 0..10 {
+ table.insert(format!("value_{i}"));
+ }
+
+ table.reset();
+
+ assert_eq!(table.theta(), (MAX_THETA as f64 * 0.5) as u64);
+ assert!(table.is_empty());
+ }
+
+ #[test]
+ fn test_iterator() {
+ let mut table = TupleHashTable::<u64>::new(8, ResizeFactor::X8, 1.0,
DEFAULT_UPDATE_SEED);
+
+ let mut inserted_hashes = vec![];
+ for i in 0..10 {
+ let hash = table.hash(i);
+ if table.insert(i) {
+ inserted_hashes.push(hash);
+ }
+ }
+
+ let iter_hashes: Vec<u64> = table.iter().map(|(hash, _)|
hash).collect();
+ assert_eq!(iter_hashes.len(), table.num_retained());
+ assert_eq!(iter_hashes.len(), inserted_hashes.len());
+
+ for hash in &inserted_hashes {
+ assert!(iter_hashes.contains(hash));
+ }
+
+ assert!(!iter_hashes.contains(&0));
+ }
+
+ #[test]
+ fn test_empty_table_operations() {
+ let mut table = TupleHashTable::<u64>::new(8, ResizeFactor::X8, 1.0,
DEFAULT_UPDATE_SEED);
+
+ assert!(table.is_empty());
+ assert_eq!(table.num_retained(), 0);
+ assert_eq!(table.iter().count(), 0);
+
+ // Trim on empty table should not panic
+ table.trim();
+ assert!(table.is_empty());
+
+ // Reset on empty table should not panic
+ table.reset();
+ assert!(table.is_empty());
+ }
+
+ #[test]
+ fn test_rebuild_preserves_entries_less_than_kth() {
+ let mut table = TupleHashTable::<u64>::new(5, ResizeFactor::X8, 1.0,
DEFAULT_UPDATE_SEED);
+ let k = 1u64 << 5; // k = 32
+
+ // Insert many values to trigger rebuild
+ let mut i = 0;
+ let mut inserted_hashes = vec![];
+ loop {
+ let hash = table.hash(i);
+ i += 1;
+ if table.insert(i - 1) {
+ inserted_hashes.push(hash);
+ }
+ if table.num_retained() >= k as usize {
+ break;
+ }
+ }
+
+ let rebuild_threshold = table.get_capacity();
+
+ loop {
+ let hash = table.hash(i);
+ i += 1;
+ if table.insert(i - 1) {
+ inserted_hashes.push(hash);
+ }
+ if table.num_retained() >= rebuild_threshold {
+ break;
+ }
+ }
+
+ // trigger rebuild
+ loop {
+ let hash = table.hash(i);
+ i += 1;
+ if table.insert(i - 1) {
+ inserted_hashes.push(hash);
+ break;
+ }
+ }
+
+ // assert all entries are less than kth
+ inserted_hashes.sort();
+ let kth = inserted_hashes[k as usize];
+ assert!(table.iter().all(|(hash, _)| hash < kth));
+ assert_eq!(table.theta(), kth);
+ }
+}
diff --git a/datasketches/src/tuple/mod.rs b/datasketches/src/tuple/mod.rs
new file mode 100644
index 0000000..f76af9e
--- /dev/null
+++ b/datasketches/src/tuple/mod.rs
@@ -0,0 +1,49 @@
+// 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.
+
+//! Tuple sketch implementation.
+//!
+//! A Tuple sketch is an extension of the Theta sketch: in addition to the
retained
+//! hash values it keeps a user-defined summary associated with every retained
key. The hash table
+//! mechanics (theta screening, resize, rebuild to nominal size k) mirror the
Theta sketch, with the
+//! added requirement that colliding keys merge their summaries.
+//!
+//! The behavior of a summary (how to create and update it) is supplied
externally through
+//! policy objects ([`SummaryUpdatePolicy`]) rather than being baked into the
summary type.
+//!
+//! # Usage
+//!
+//! ```
+//! # use datasketches::tuple::TupleSketch;
+//! let mut sketch = TupleSketch::<u64>::builder().build();
+//! sketch.update("apple", 1);
+//! assert!(sketch.estimate() >= 1.0);
+//! ```
+
+mod hash_table;
+mod policy;
+mod serialization;
+mod sketch;
+
+pub use self::hash_table::TupleEntry;
+pub use self::policy::DefaultUpdatePolicy;
+pub use self::policy::SummaryUpdatePolicy;
+pub use self::serialization::TupleSummaryValue;
+pub use self::sketch::CompactTupleSketch;
+pub use self::sketch::TupleSketch;
+pub use self::sketch::TupleSketchBuilder;
+pub use self::sketch::TupleSketchView;
diff --git a/datasketches/src/tuple/policy.rs b/datasketches/src/tuple/policy.rs
new file mode 100644
index 0000000..468ffd4
--- /dev/null
+++ b/datasketches/src/tuple/policy.rs
@@ -0,0 +1,76 @@
+// 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.
+
+//! Policies describing how summaries are created, updated, and combined.
+//!
+//! A Tuple sketch keeps a user-defined summary `S` next to every retained
key. The behavior of a
+//! summary is supplied externally through policy objects rather than baked
into the summary type
+//! itself, so the same summary type (for example a plain `u64` or a
`Vec<f64>`) can be driven by
+//! different behaviors and can carry per-instance configuration (such as the
number of values in an
+//! array-of-doubles summary).
+
+use std::ops::AddAssign;
+
+/// Defines how a summary is created and how update values are folded into it.
+///
+/// This is used by the update tuple sketch. `S` is the stored summary type
and `U` is the type of
+/// the update value, which may be a borrowed type such as `&[f64]`.
+pub trait SummaryUpdatePolicy<S, U> {
+ /// Creates a new summary for a key seen for the first time.
+ ///
+ /// The summary should be in its identity state; the first update value is
folded in separately
+ /// via [`update`](Self::update).
+ fn create(&self) -> S;
+
+ /// Folds an update value into an existing summary.
+ fn update(&self, summary: &mut S, value: U);
+}
+
+/// Default update policy for summaries that are default-constructible and
additive.
+///
+/// This is the convenience policy used when no custom policy is supplied,
equivalent to C++
+/// `default_tuple_update_policy` (which folds updates with `summary +=
update`). It is available
+/// for any summary type `S` and update type `U` where `S: Default +
AddAssign<U>`.
+#[derive(Debug, Default, Clone, Copy)]
+pub struct DefaultUpdatePolicy(());
+
+impl<S, U> SummaryUpdatePolicy<S, U> for DefaultUpdatePolicy
+where
+ S: Default + AddAssign<U>,
+{
+ fn create(&self) -> S {
+ S::default()
+ }
+
+ fn update(&self, summary: &mut S, value: U) {
+ *summary += value;
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn default_update_policy_update_accumulates() {
+ let policy = DefaultUpdatePolicy::default();
+ let mut summary = 0u64;
+ policy.update(&mut summary, 3);
+ policy.update(&mut summary, 4);
+ assert_eq!(summary, 7);
+ }
+}
diff --git a/datasketches/src/tuple/serialization.rs
b/datasketches/src/tuple/serialization.rs
new file mode 100644
index 0000000..09763ca
--- /dev/null
+++ b/datasketches/src/tuple/serialization.rs
@@ -0,0 +1,126 @@
+// 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.
+
+//! Binary serialization of Tuple sketches.
+//!
+//! The Tuple compact format reuses the uncompressed Theta layout (preamble,
flags, theta) but uses
+//! the Tuple family id, carries a sketch-type byte, and stores the user
summary bytes after each
+//! retained hash. See the C++/Java reference implementations for the on-disk
format.
+//!
+//! A Tuple sketch keeps a user-defined summary next to every retained key.
Because the summary
+//! type is opaque to the sketch, (de)serialization of summaries is delegated
to the summary type
+//! itself via the [`TupleSummaryValue`] trait, mirroring `FrequentItemValue`.
+
+use crate::codec::SketchBytes;
+use crate::codec::SketchSlice;
+use crate::error::Error;
+
+/// Current serial version written by this implementation.
+pub(super) const SERIAL_VERSION: u8 = 3;
+/// Legacy serial version still accepted on read.
+pub(super) const SERIAL_VERSION_LEGACY: u8 = 1;
+
+/// Current sketch-type byte written by this implementation.
+pub(super) const SKETCH_TYPE: u8 = 1;
+/// Legacy sketch-type byte still accepted on read.
+pub(super) const SKETCH_TYPE_LEGACY: u8 = 5;
+
+/// Trait for values that can be stored as Tuple sketch summaries.
+///
+/// Implement this trait for a summary type to make it (de)serializable by
+/// [`CompactTupleSketch`](crate::tuple::CompactTupleSketch). The encoding is
entirely up to the
+/// implementation; both fixed-width summaries (such as a `u64` counter) and
variable-width
+/// summaries (such as an array of doubles whose length is encoded in the
bytes) are supported by
+/// advancing the cursor past exactly the bytes read.
+pub trait TupleSummaryValue: Sized {
+ /// Returns the size in bytes required to serialize this summary.
+ fn serialize_size(&self) -> usize;
+
+ /// Serializes the summary into the byte buffer.
+ fn serialize_value(&self, bytes: &mut SketchBytes);
+
+ /// Deserializes a summary from the byte cursor, advancing it past the
bytes consumed.
+ ///
+ /// # Errors
+ ///
+ /// Returns an error if the cursor holds too few bytes or the encoding is
otherwise malformed.
+ fn deserialize_value(cursor: &mut SketchSlice<'_>) -> Result<Self, Error>;
+}
+
+macro_rules! impl_primitive_summary {
+ ($name:ty, $read:ident, $write:ident) => {
+ impl TupleSummaryValue for $name {
+ fn serialize_size(&self) -> usize {
+ size_of::<$name>()
+ }
+
+ fn serialize_value(&self, bytes: &mut SketchBytes) {
+ bytes.$write(*self);
+ }
+
+ fn deserialize_value(cursor: &mut SketchSlice<'_>) -> Result<Self,
Error> {
+ cursor.$read().map_err(|_| {
+ Error::insufficient_data(
+ concat!("failed to read ", stringify!($name), "
summary bytes").to_string(),
+ )
+ })
+ }
+ }
+ };
+}
+
+impl_primitive_summary!(u32, read_u32_le, write_u32_le);
+impl_primitive_summary!(u64, read_u64_le, write_u64_le);
+impl_primitive_summary!(i32, read_i32_le, write_i32_le);
+impl_primitive_summary!(i64, read_i64_le, write_i64_le);
+impl_primitive_summary!(f32, read_f32_le, write_f32_le);
+impl_primitive_summary!(f64, read_f64_le, write_f64_le);
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::error::ErrorKind;
+
+ #[test]
+ fn primitive_values_round_trip() {
+ let mut bytes = SketchBytes::with_capacity(8);
+ 123456789u64.serialize_value(&mut bytes);
+ let bytes = bytes.into_bytes();
+ assert_eq!(bytes.len(), 8);
+ let mut cursor = SketchSlice::new(&bytes);
+ assert_eq!(u64::deserialize_value(&mut cursor).unwrap(), 123456789);
+ }
+
+ #[test]
+ fn primitive_values_consume_only_their_width() {
+ let mut bytes = SketchBytes::with_capacity(6);
+ 9u32.serialize_value(&mut bytes);
+ bytes.write(&[0xAA, 0xBB]); // trailing bytes belonging to the next
entry
+ let bytes = bytes.into_bytes();
+ let mut cursor = SketchSlice::new(&bytes);
+ assert_eq!(u32::deserialize_value(&mut cursor).unwrap(), 9);
+ assert_eq!(cursor.remaining(), &[0xAA, 0xBB]);
+ }
+
+ #[test]
+ fn primitive_values_reject_short_input() {
+ let bytes = [0u8; 3];
+ let mut cursor = SketchSlice::new(&bytes);
+ let err = u64::deserialize_value(&mut cursor).unwrap_err();
+ assert_eq!(err.kind(), ErrorKind::InvalidData);
+ }
+}
diff --git a/datasketches/src/tuple/sketch.rs b/datasketches/src/tuple/sketch.rs
new file mode 100644
index 0000000..78cc6ae
--- /dev/null
+++ b/datasketches/src/tuple/sketch.rs
@@ -0,0 +1,1004 @@
+// 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.
+
+//! Tuple sketch types.
+//!
+//! This module provides [`TupleSketch`] (mutable) and [`CompactTupleSketch`]
(immutable),
+//! the Tuple sketch analogues of the Theta sketch. Each retained key carries
a user-defined summary
+//! whose behavior is supplied by a [`SummaryUpdatePolicy`].
+
+use std::hash::Hash;
+use std::marker::PhantomData;
+
+use crate::codec::SketchBytes;
+use crate::codec::SketchSlice;
+use crate::codec::assert::ensure_preamble_longs_in_range;
+use crate::codec::assert::insufficient_data;
+use crate::codec::family::Family;
+use crate::common::NumStdDev;
+use crate::common::ResizeFactor;
+use crate::error::Error;
+use crate::hash::DEFAULT_UPDATE_SEED;
+use crate::hash::compute_seed_hash;
+use crate::thetacommon::RawThetaSketchView;
+use crate::thetacommon::binomial_bounds;
+use crate::thetacommon::constants::DEFAULT_LG_K;
+use crate::thetacommon::constants::FLAGS_IS_COMPACT;
+use crate::thetacommon::constants::FLAGS_IS_EMPTY;
+use crate::thetacommon::constants::FLAGS_IS_ORDERED;
+use crate::thetacommon::constants::FLAGS_IS_READ_ONLY;
+use crate::thetacommon::constants::MAX_LG_K;
+use crate::thetacommon::constants::MAX_THETA;
+use crate::thetacommon::constants::MIN_LG_K;
+use crate::tuple::hash_table::TupleEntry;
+use crate::tuple::hash_table::TupleHashTable;
+use crate::tuple::policy::DefaultUpdatePolicy;
+use crate::tuple::policy::SummaryUpdatePolicy;
+use crate::tuple::serialization;
+use crate::tuple::serialization::TupleSummaryValue;
+
+/// Read-only view for Tuple sketches.
+///
+/// This trait is the input abstraction for APIs (such as union and
intersection) that accept
+/// either a mutable [`TupleSketch`] or an immutable [`CompactTupleSketch`].
`S` is the
+/// summary type retained by the sketch.
+///
+/// It is blanket-implemented for every [`RawThetaSketchView`] over
[`TupleEntry`], so custom
+/// sketch-like inputs can be supplied by implementing that trait.
+pub trait TupleSketchView<S>: RawThetaSketchView<TupleEntry<S>> {}
+
+impl<S, T> TupleSketchView<S> for T where T: RawThetaSketchView<TupleEntry<S>>
{}
+
+/// Mutable Tuple sketch for building from input data.
+///
+/// `S` is the summary type retained alongside each key, and `P` is the
[`SummaryUpdatePolicy`] that
+/// defines how summaries are created and updated. For additive summaries the
default
+/// [`DefaultUpdatePolicy`] is used.
+///
+/// # Examples
+///
+/// ```
+/// # use datasketches::tuple::TupleSketch;
+/// let mut sketch = TupleSketch::<u64>::builder().build();
+/// sketch.update("apple", 1);
+/// sketch.update("apple", 1);
+/// assert!(sketch.estimate() >= 1.0);
+/// assert_eq!(sketch.num_retained(), 1);
+/// ```
+#[derive(Debug)]
+pub struct TupleSketch<S, P = DefaultUpdatePolicy> {
+ table: TupleHashTable<S>,
+ policy: P,
+}
+
+impl<S> TupleSketch<S, DefaultUpdatePolicy> {
+ /// Creates a new builder using the default update policy.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// # use datasketches::tuple::TupleSketch;
+ /// let sketch = TupleSketch::<u64>::builder().lg_k(12).build();
+ /// assert_eq!(sketch.lg_k(), 12);
+ /// ```
+ pub fn builder() -> TupleSketchBuilder<S, DefaultUpdatePolicy> {
+ TupleSketchBuilder::default()
+ }
+}
+
+impl<S, P> TupleSketch<S, P> {
+ /// Updates the sketch with a key and an update value.
+ ///
+ /// If the key is new, the policy creates a summary and folds in `value`;
if the key already
+ /// exists, `value` is folded into the retained summary. Updates screened
out by theta do not
+ /// change any summary.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// # use datasketches::tuple::TupleSketch;
+ /// let mut sketch = TupleSketch::<u64>::builder().build();
+ /// sketch.update(42, 5);
+ /// ```
+ pub fn update<U>(&mut self, key: impl Hash, value: U)
+ where
+ P: SummaryUpdatePolicy<S, U>,
+ {
+ let policy = &self.policy;
+ self.table.try_insert(key, |existing| match existing {
+ Some(summary) => {
+ policy.update(summary, value);
+ None
+ }
+ None => {
+ let mut summary = policy.create();
+ policy.update(&mut summary, value);
+ Some(summary)
+ }
+ });
+ }
+
+ /// Returns the cardinality (distinct key count) estimate.
+ pub fn estimate(&self) -> f64 {
+ if self.is_empty() {
+ return 0.0;
+ }
+ let num_retained = self.table.num_retained() as f64;
+ let theta = self.table.theta() as f64 / MAX_THETA as f64;
+ num_retained / theta
+ }
+
+ /// Returns theta as a fraction (0.0 to 1.0).
+ pub fn theta(&self) -> f64 {
+ self.table.theta() as f64 / MAX_THETA as f64
+ }
+
+ /// Returns theta as `u64`.
+ pub fn theta64(&self) -> u64 {
+ self.table.theta()
+ }
+
+ /// Returns the 16-bit seed hash.
+ pub fn seed_hash(&self) -> u16 {
+ self.table.seed_hash()
+ }
+
+ /// Returns true if the sketch is empty.
+ pub fn is_empty(&self) -> bool {
+ self.table.is_empty()
+ }
+
+ /// Returns true if the sketch is in estimation mode.
+ pub fn is_estimation_mode(&self) -> bool {
+ self.table.theta() < MAX_THETA
+ }
+
+ /// Returns the number of retained entries.
+ pub fn num_retained(&self) -> usize {
+ self.table.num_retained()
+ }
+
+ /// Returns lg_k (log2 of the nominal size k).
+ pub fn lg_k(&self) -> u8 {
+ self.table.lg_nom_size()
+ }
+
+ /// Trims the sketch to the nominal size k.
+ pub fn trim(&mut self) {
+ self.table.trim();
+ }
+
+ /// Resets the sketch to the empty state.
+ pub fn reset(&mut self) {
+ self.table.reset();
+ }
+
+ /// Returns an iterator over retained entries as `(hash, &summary)` pairs.
+ pub fn iter(&self) -> impl Iterator<Item = (u64, &S)> + '_ {
+ self.table.iter()
+ }
+
+ /// Returns the approximate lower error bound given the number of standard
deviations.
+ pub fn lower_bound(&self, num_std_dev: NumStdDev) -> f64 {
+ if !self.is_estimation_mode() {
+ return self.num_retained() as f64;
+ }
+ binomial_bounds::lower_bound(self.num_retained() as u64, self.theta(),
num_std_dev)
+ .expect("theta should always be valid")
+ }
+
+ /// Returns the approximate upper error bound given the number of standard
deviations.
+ pub fn upper_bound(&self, num_std_dev: NumStdDev) -> f64 {
+ if !self.is_estimation_mode() {
+ return self.num_retained() as f64;
+ }
+ binomial_bounds::upper_bound(
+ self.num_retained() as u64,
+ self.theta(),
+ num_std_dev,
+ self.is_empty(),
+ )
+ .expect("theta should always be valid")
+ }
+
+ /// Returns the estimated size of the sketch in bytes.
+ pub fn estimated_size(&self) -> usize {
+ size_of::<Self>() + self.table.estimated_size()
+ }
+}
+
+impl<S: Clone, P> TupleSketch<S, P> {
+ /// Returns this sketch in compact (immutable) form.
+ ///
+ /// If `ordered` is true, retained entries are sorted by hash in ascending
order.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// # use datasketches::tuple::TupleSketch;
+ /// let mut sketch = TupleSketch::<u64>::builder().build();
+ /// sketch.update("apple", 1);
+ /// let compact = sketch.compact(true);
+ /// assert_eq!(compact.num_retained(), 1);
+ /// ```
+ pub fn compact(&self, ordered: bool) -> CompactTupleSketch<S> {
+ let parts = self.table.to_compact_parts(ordered);
+ CompactTupleSketch::from_parts(
+ parts.entries,
+ parts.theta,
+ parts.seed_hash,
+ parts.ordered,
+ parts.empty,
+ )
+ }
+}
+
+impl<S: Clone, P> RawThetaSketchView<TupleEntry<S>> for TupleSketch<S, P> {
+ fn seed_hash(&self) -> u16 {
+ self.table.seed_hash()
+ }
+
+ fn theta(&self) -> u64 {
+ self.table.theta()
+ }
+
+ fn is_empty(&self) -> bool {
+ self.table.is_empty()
+ }
+
+ fn is_ordered(&self) -> bool {
+ false
+ }
+
+ fn iter(&self) -> impl Iterator<Item = TupleEntry<S>> + '_ {
+ self.table
+ .iter()
+ .map(|(hash, summary)| TupleEntry::new(hash, summary.clone()))
+ }
+
+ fn num_retained(&self) -> usize {
+ self.table.num_retained()
+ }
+}
+
+/// Compact (immutable) Tuple sketch.
+///
+/// This is the serialization-friendly form: a compact array of retained
[`TupleEntry`] values
+/// (hash plus summary) plus theta and a 16-bit seed hash. It can be ordered
(sorted ascending by
+/// hash) or unordered.
+#[derive(Clone, Debug)]
+pub struct CompactTupleSketch<S> {
+ entries: Vec<TupleEntry<S>>,
+ theta: u64,
+ seed_hash: u16,
+ ordered: bool,
+ empty: bool,
+}
+
+impl<S> CompactTupleSketch<S> {
+ pub(super) fn from_parts(
+ entries: Vec<TupleEntry<S>>,
+ theta: u64,
+ seed_hash: u16,
+ ordered: bool,
+ empty: bool,
+ ) -> Self {
+ Self {
+ entries,
+ theta,
+ seed_hash,
+ ordered,
+ empty,
+ }
+ }
+
+ /// Returns the cardinality (distinct key count) estimate.
+ pub fn estimate(&self) -> f64 {
+ if self.is_empty() {
+ return 0.0;
+ }
+ let num_retained = self.num_retained() as f64;
+ if self.theta == MAX_THETA {
+ return num_retained;
+ }
+ let theta = self.theta as f64 / MAX_THETA as f64;
+ num_retained / theta
+ }
+
+ /// Returns theta as a fraction (0.0 to 1.0).
+ pub fn theta(&self) -> f64 {
+ self.theta as f64 / MAX_THETA as f64
+ }
+
+ /// Returns theta as `u64`.
+ pub fn theta64(&self) -> u64 {
+ self.theta
+ }
+
+ /// Returns true if the sketch is empty.
+ pub fn is_empty(&self) -> bool {
+ self.empty
+ }
+
+ /// Returns true if the sketch is in estimation mode.
+ pub fn is_estimation_mode(&self) -> bool {
+ self.theta < MAX_THETA
+ }
+
+ /// Returns the number of retained entries.
+ pub fn num_retained(&self) -> usize {
+ self.entries.len()
+ }
+
+ /// Returns true if retained entries are ordered (sorted ascending by
hash).
+ pub fn is_ordered(&self) -> bool {
+ self.ordered
+ }
+
+ /// Returns the 16-bit seed hash.
+ pub fn seed_hash(&self) -> u16 {
+ self.seed_hash
+ }
+
+ /// Returns an iterator over retained entries as `(hash, &summary)` pairs.
+ pub fn iter(&self) -> impl Iterator<Item = (u64, &S)> + '_ {
+ self.entries
+ .iter()
+ .map(|entry| (entry.hash(), entry.summary()))
+ }
+
+ /// Returns the approximate lower error bound given the number of standard
deviations.
+ pub fn lower_bound(&self, num_std_dev: NumStdDev) -> f64 {
+ if !self.is_estimation_mode() {
+ return self.num_retained() as f64;
+ }
+ binomial_bounds::lower_bound(self.num_retained() as u64, self.theta(),
num_std_dev)
+ .expect("compact theta should always be valid")
+ }
+
+ /// Returns the approximate upper error bound given the number of standard
deviations.
+ pub fn upper_bound(&self, num_std_dev: NumStdDev) -> f64 {
+ if !self.is_estimation_mode() {
+ return self.num_retained() as f64;
+ }
+ binomial_bounds::upper_bound(
+ self.num_retained() as u64,
+ self.theta(),
+ num_std_dev,
+ self.is_empty(),
+ )
+ .expect("compact theta should always be valid")
+ }
+
+ /// Returns the estimated size of the sketch in bytes.
+ pub fn estimated_size(&self) -> usize {
+ size_of::<Self>() + self.entries.capacity() *
size_of::<TupleEntry<S>>()
+ }
+
+ fn preamble_longs(&self) -> u8 {
+ if self.is_estimation_mode() {
+ 3
+ } else if self.is_empty() || self.entries.len() == 1 {
+ 1
+ } else {
+ 2
+ }
+ }
+
+ /// Serializes this sketch into the compact Tuple binary format.
+ ///
+ /// Each summary is encoded by its [`TupleSummaryValue`] implementation.
The layout matches the
+ /// Java/C++ Tuple sketches, so the output can be read by those
implementations given a
+ /// compatible summary encoding.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// # use datasketches::tuple::TupleSketch;
+ /// let mut sketch = TupleSketch::<u64>::builder().build();
+ /// sketch.update("apple", 1);
+ /// let bytes = sketch.compact(true).serialize();
+ /// assert!(!bytes.is_empty());
+ /// ```
+ pub fn serialize(&self) -> Vec<u8>
+ where
+ S: TupleSummaryValue,
+ {
+ let pre_longs = self.preamble_longs();
+ let entries_size: usize = self
+ .entries
+ .iter()
+ .map(|entry| 8 + entry.summary().serialize_size())
+ .sum();
+ let mut bytes = SketchBytes::with_capacity(8 * pre_longs as usize +
entries_size);
+
+ bytes.write_u8(pre_longs);
+ bytes.write_u8(serialization::SERIAL_VERSION);
+ bytes.write_u8(Family::TUPLE.id);
+ bytes.write_u8(serialization::SKETCH_TYPE);
+ bytes.write_u8(0); // unused
+
+ let mut flags = FLAGS_IS_READ_ONLY | FLAGS_IS_COMPACT;
+ if self.is_empty() {
+ flags |= FLAGS_IS_EMPTY;
+ }
+ if self.is_ordered() {
+ flags |= FLAGS_IS_ORDERED;
+ }
+ bytes.write_u8(flags);
+ bytes.write_u16_le(self.seed_hash);
+
+ if pre_longs > 1 {
+ bytes.write_u32_le(self.entries.len() as u32);
+ bytes.write_u32_le(0); // unused
+ }
+ if self.is_estimation_mode() {
+ bytes.write_u64_le(self.theta);
+ }
+
+ for entry in &self.entries {
+ bytes.write_u64_le(entry.hash());
+ entry.summary().serialize_value(&mut bytes);
+ }
+ bytes.into_bytes()
+ }
+
+ /// Deserializes a compact Tuple sketch using the default seed.
+ pub fn deserialize(bytes: &[u8]) -> Result<Self, Error>
+ where
+ S: TupleSummaryValue,
+ {
+ Self::deserialize_with_seed(bytes, DEFAULT_UPDATE_SEED)
+ }
+
+ /// Deserializes a compact Tuple sketch using the provided expected `seed`.
+ ///
+ /// # Errors
+ ///
+ /// Returns an error if the bytes are truncated, the family/serial
version/sketch type are
+ /// unexpected, the seed hash does not match (for non-empty sketches), or
an entry is corrupted.
+ pub fn deserialize_with_seed(bytes: &[u8], seed: u64) -> Result<Self,
Error>
+ where
+ S: TupleSummaryValue,
+ {
+ let mut cursor = SketchSlice::new(bytes);
+ let pre_longs = cursor
+ .read_u8()
+ .map_err(insufficient_data("preamble_longs"))?;
+ let ser_ver = cursor
+ .read_u8()
+ .map_err(insufficient_data("serial_version"))?;
+ let family_id =
cursor.read_u8().map_err(insufficient_data("family_id"))?;
+ let sketch_type =
cursor.read_u8().map_err(insufficient_data("sketch_type"))?;
+ cursor.read_u8().map_err(insufficient_data("<unused>"))?;
+ let flags = cursor.read_u8().map_err(insufficient_data("flags"))?;
+ let seed_hash = cursor
+ .read_u16_le()
+ .map_err(insufficient_data("seed_hash"))?;
+
+ Family::TUPLE.validate_id(family_id)?;
+ ensure_preamble_longs_in_range(
+ Family::TUPLE.min_pre_longs..=Family::TUPLE.max_pre_longs,
+ pre_longs,
+ )?;
+ if ser_ver != serialization::SERIAL_VERSION
+ && ser_ver != serialization::SERIAL_VERSION_LEGACY
+ {
+ return Err(Error::deserial(format!(
+ "unsupported serial version: expected {} or {}, got {ser_ver}",
+ serialization::SERIAL_VERSION,
+ serialization::SERIAL_VERSION_LEGACY,
+ )));
+ }
+ if sketch_type != serialization::SKETCH_TYPE
+ && sketch_type != serialization::SKETCH_TYPE_LEGACY
+ {
+ return Err(Error::deserial(format!(
+ "unsupported sketch type: expected {} or {}, got
{sketch_type}",
+ serialization::SKETCH_TYPE,
+ serialization::SKETCH_TYPE_LEGACY,
+ )));
+ }
+
+ let empty = (flags & FLAGS_IS_EMPTY) != 0;
+ let ordered = (flags & FLAGS_IS_ORDERED) != 0;
+
+ if empty {
+ return Ok(Self::from_parts(
+ vec![],
+ MAX_THETA,
+ seed_hash,
+ ordered,
+ true,
+ ));
+ }
+
+ let expected_seed_hash = compute_seed_hash(seed);
+ if seed_hash != expected_seed_hash {
+ return Err(Error::deserial(format!(
+ "incompatible seed hash: expected {expected_seed_hash}, got
{seed_hash}",
+ )));
+ }
+
+ let mut theta = MAX_THETA;
+ let num_entries = if pre_longs == 1 {
+ 1usize
+ } else {
+ let n = cursor
+ .read_u32_le()
+ .map_err(insufficient_data("num_entries"))? as usize;
+ cursor
+ .read_u32_le()
+ .map_err(insufficient_data("<unused_u32>"))?;
+ if pre_longs > 2 {
+ theta =
cursor.read_u64_le().map_err(insufficient_data("theta"))?;
+ }
+ n
+ };
+
+ let mut entries = Vec::with_capacity(num_entries);
+ for _ in 0..num_entries {
+ let hash = cursor
+ .read_u64_le()
+ .map_err(insufficient_data("entry_hash"))?;
+ if hash == 0 || hash >= theta {
+ return Err(Error::deserial("corrupted: invalid retained hash
value"));
+ }
+ let summary = S::deserialize_value(&mut cursor)?;
+ entries.push(TupleEntry::new(hash, summary));
+ }
+
+ Ok(Self::from_parts(entries, theta, seed_hash, ordered, false))
+ }
+}
+
+impl<S: Clone> RawThetaSketchView<TupleEntry<S>> for CompactTupleSketch<S> {
+ fn seed_hash(&self) -> u16 {
+ self.seed_hash
+ }
+
+ fn theta(&self) -> u64 {
+ self.theta
+ }
+
+ fn is_empty(&self) -> bool {
+ self.empty
+ }
+
+ fn is_ordered(&self) -> bool {
+ self.ordered
+ }
+
+ fn iter(&self) -> impl Iterator<Item = TupleEntry<S>> + '_ {
+ self.entries.iter().cloned()
+ }
+
+ fn num_retained(&self) -> usize {
+ self.entries.len()
+ }
+}
+
+/// Builder for [`TupleSketch`].
+///
+/// The summary type `S` is fixed when the builder is created (for example via
+/// `TupleSketch::<u64>::builder()`), and the policy type `P` defaults to
+/// [`DefaultUpdatePolicy`]. Use [`policy`](Self::policy) to supply a custom
policy.
+#[derive(Debug)]
+pub struct TupleSketchBuilder<S, P = DefaultUpdatePolicy> {
+ lg_k: u8,
+ resize_factor: ResizeFactor,
+ sampling_probability: f32,
+ seed: u64,
+ policy: P,
+ _marker: PhantomData<fn() -> S>,
+}
+
+impl<S> Default for TupleSketchBuilder<S, DefaultUpdatePolicy> {
+ fn default() -> Self {
+ Self {
+ lg_k: DEFAULT_LG_K,
+ resize_factor: ResizeFactor::X8,
+ sampling_probability: 1.0,
+ seed: DEFAULT_UPDATE_SEED,
+ policy: DefaultUpdatePolicy::default(),
+ _marker: PhantomData,
+ }
+ }
+}
+
+impl<S, P> TupleSketchBuilder<S, P> {
+ /// Sets lg_k (log2 of the nominal size k).
+ ///
+ /// # Panics
+ ///
+ /// Panics if lg_k is not in range [5, 26].
+ pub fn lg_k(mut self, lg_k: u8) -> Self {
+ assert!(
+ (MIN_LG_K..=MAX_LG_K).contains(&lg_k),
+ "lg_k must be in [{MIN_LG_K}, {MAX_LG_K}], got {lg_k}"
+ );
+ self.lg_k = lg_k;
+ self
+ }
+
+ /// Sets the resize factor.
+ pub fn resize_factor(mut self, factor: ResizeFactor) -> Self {
+ self.resize_factor = factor;
+ self
+ }
+
+ /// Sets the sampling probability p.
+ ///
+ /// # Panics
+ ///
+ /// Panics if p is not in range `(0.0, 1.0]`.
+ pub fn sampling_probability(mut self, probability: f32) -> Self {
+ assert!(
+ (0.0..=1.0).contains(&probability) && probability > 0.0,
+ "sampling_probability must be in (0.0, 1.0], got {probability}"
+ );
+ self.sampling_probability = probability;
+ self
+ }
+
+ /// Sets the hash seed.
+ pub fn seed(mut self, seed: u64) -> Self {
+ self.seed = seed;
+ self
+ }
+
+ /// Sets a custom update policy, changing the builder's policy type.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use datasketches::tuple::SummaryUpdatePolicy;
+ /// use datasketches::tuple::TupleSketch;
+ ///
+ /// struct MaxPolicy;
+ ///
+ /// impl SummaryUpdatePolicy<u64, u64> for MaxPolicy {
+ /// fn create(&self) -> u64 {
+ /// 0
+ /// }
+ ///
+ /// fn update(&self, summary: &mut u64, value: u64) {
+ /// *summary = (*summary).max(value);
+ /// }
+ /// }
+ ///
+ /// let mut sketch =
TupleSketch::<u64>::builder().policy(MaxPolicy).build();
+ /// sketch.update("k", 3);
+ /// sketch.update("k", 7);
+ /// ```
+ pub fn policy<P2>(self, policy: P2) -> TupleSketchBuilder<S, P2> {
+ TupleSketchBuilder {
+ lg_k: self.lg_k,
+ resize_factor: self.resize_factor,
+ sampling_probability: self.sampling_probability,
+ seed: self.seed,
+ policy,
+ _marker: PhantomData,
+ }
+ }
+
+ /// Builds the [`TupleSketch`].
+ pub fn build(self) -> TupleSketch<S, P> {
+ let table = TupleHashTable::new(
+ self.lg_k,
+ self.resize_factor,
+ self.sampling_probability,
+ self.seed,
+ );
+ TupleSketch {
+ table,
+ policy: self.policy,
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::error::ErrorKind;
+ use crate::tuple::policy::SummaryUpdatePolicy;
+
+ fn sorted_updatable_entries(sketch: &TupleSketch<u64>) -> Vec<(u64, u64)> {
+ let mut entries: Vec<(u64, u64)> = sketch.iter().map(|(h, &s)| (h,
s)).collect();
+ entries.sort_unstable();
+ entries
+ }
+
+ fn sorted_compact_entries(sketch: &CompactTupleSketch<u64>) -> Vec<(u64,
u64)> {
+ let mut entries: Vec<(u64, u64)> = sketch.iter().map(|(h, &s)| (h,
s)).collect();
+ entries.sort_unstable();
+ entries
+ }
+
+ fn assert_updatable_and_compact_equivalent(
+ updatable: &TupleSketch<u64>,
+ compact: &CompactTupleSketch<u64>,
+ ) {
+ assert_eq!(updatable.is_empty(), compact.is_empty());
+ assert_eq!(updatable.is_estimation_mode(),
compact.is_estimation_mode());
+ assert_eq!(updatable.num_retained(), compact.num_retained());
+ assert_eq!(updatable.theta64(), compact.theta64());
+ assert_eq!(updatable.seed_hash(), compact.seed_hash());
+ assert_eq!(
+ sorted_updatable_entries(updatable),
+ sorted_compact_entries(compact)
+ );
+ assert!((updatable.estimate() - compact.estimate()).abs() <= 1e-9);
+ }
+
+ #[test]
+ fn exact_mode_updatable_and_compact_equivalent() {
+ let mut sketch = TupleSketch::<u64>::builder().lg_k(12).build();
+ for i in 0..2000 {
+ sketch.update(i, 1u64);
+ }
+ assert!(!sketch.is_estimation_mode());
+
+ for ordered in [false, true] {
+ let compact = sketch.compact(ordered);
+ assert_updatable_and_compact_equivalent(&sketch, &compact);
+ if compact.num_retained() > 1 {
+ assert_eq!(compact.is_ordered(), ordered);
+ }
+ }
+ }
+
+ #[test]
+ fn estimation_mode_updatable_and_compact_equivalent() {
+ let mut sketch = TupleSketch::<u64>::builder().lg_k(5).build();
+ for i in 0..5000 {
+ sketch.update(i, 1u64);
+ }
+ assert!(sketch.is_estimation_mode());
+
+ for ordered in [false, true] {
+ let compact = sketch.compact(ordered);
+ assert_updatable_and_compact_equivalent(&sketch, &compact);
+ }
+ }
+
+ #[test]
+ fn summaries_accumulate_with_default_policy() {
+ let mut sketch = TupleSketch::<u64>::builder().build();
+ for _ in 0..5 {
+ sketch.update("same_key", 2u64);
+ }
+ assert_eq!(sketch.num_retained(), 1);
+ let entries = sorted_updatable_entries(&sketch);
+ assert_eq!(entries.len(), 1);
+ assert_eq!(entries[0].1, 10); // 5 updates of 2
+
+ // Summaries survive the compaction.
+ let compact = sketch.compact(true);
+ assert_eq!(sorted_compact_entries(&compact)[0].1, 10);
+ }
+
+ #[test]
+ fn empty_sketch_is_ordered_and_zero_estimate() {
+ let sketch = TupleSketch::<u64>::builder().build();
+ assert!(sketch.is_empty());
+ assert_eq!(sketch.estimate(), 0.0);
+
+ let compact = sketch.compact(false);
+ assert!(compact.is_empty());
+ assert!(compact.is_ordered());
+ assert_eq!(compact.estimate(), 0.0);
+ assert_eq!(compact.theta64(), MAX_THETA);
+ }
+
+ #[test]
+ fn bounds_bracket_estimate_in_estimation_mode() {
+ let mut sketch = TupleSketch::<u64>::builder().lg_k(12).build();
+ for i in 0..10000 {
+ sketch.update(i, 1u64);
+ }
+ let estimate = sketch.estimate();
+ let lower = sketch.lower_bound(NumStdDev::Two);
+ let upper = sketch.upper_bound(NumStdDev::Two);
+ assert!(lower <= estimate);
+ assert!(estimate <= upper);
+ }
+
+ #[derive(Default)]
+ struct MaxPolicy;
+
+ impl SummaryUpdatePolicy<u64, u64> for MaxPolicy {
+ fn create(&self) -> u64 {
+ 0
+ }
+
+ fn update(&self, summary: &mut u64, value: u64) {
+ *summary = (*summary).max(value);
+ }
+ }
+
+ #[test]
+ fn custom_policy_drives_summary_behavior() {
+ let mut sketch =
TupleSketch::<u64>::builder().policy(MaxPolicy).build();
+ sketch.update("k", 3u64);
+ sketch.update("k", 7u64);
+ sketch.update("k", 2u64);
+
+ assert_eq!(sketch.num_retained(), 1);
+ let entries = sorted_updatable_entries_generic(&sketch);
+ assert_eq!(entries[0].1, 7);
+ }
+
+ fn sorted_updatable_entries_generic<P>(sketch: &TupleSketch<u64, P>) ->
Vec<(u64, u64)> {
+ let mut entries: Vec<(u64, u64)> = sketch.iter().map(|(h, &s)| (h,
s)).collect();
+ entries.sort_unstable();
+ entries
+ }
+
+ fn view_num_retained<V: TupleSketchView<u64>>(view: &V) -> usize {
+ view.num_retained()
+ }
+
+ fn view_summary_sum<V: TupleSketchView<u64>>(view: &V) -> u64 {
+ view.iter().map(|entry| *entry.summary()).sum()
+ }
+
+ fn view_is_ordered<V: TupleSketchView<u64>>(view: &V) -> bool {
+ view.is_ordered()
+ }
+
+ #[test]
+ fn view_trait_accepts_both_sketch_types() {
+ let mut sketch = TupleSketch::<u64>::builder().build();
+ for i in 0..100 {
+ sketch.update(i, 2u64);
+ }
+ let compact = sketch.compact(true);
+
+ // Both sketch types are accepted through the shared view trait.
+ assert_eq!(view_num_retained(&sketch), 100);
+ assert_eq!(view_num_retained(&compact), 100);
+ assert_eq!(view_summary_sum(&sketch), view_summary_sum(&compact));
+ assert_eq!(view_summary_sum(&compact), 200); // 100 keys * 2
+
+ // Updatable is unordered by default; compact(true) reports ordered.
+ assert!(!view_is_ordered(&sketch));
+ assert!(view_is_ordered(&compact));
+ }
+
+ fn assert_compact_round_trip(original: &CompactTupleSketch<u64>) {
+ let bytes = original.serialize();
+ let restored = CompactTupleSketch::<u64>::deserialize(&bytes).unwrap();
+ assert_eq!(original.is_empty(), restored.is_empty());
+ assert_eq!(original.is_ordered(), restored.is_ordered());
+ assert_eq!(original.theta64(), restored.theta64());
+ assert_eq!(original.seed_hash(), restored.seed_hash());
+ assert_eq!(original.num_retained(), restored.num_retained());
+ assert_eq!(
+ sorted_compact_entries(original),
+ sorted_compact_entries(&restored)
+ );
+ }
+
+ #[test]
+ fn serialize_round_trip_exact_mode() {
+ let mut sketch = TupleSketch::<u64>::builder().lg_k(12).build();
+ for i in 0..2000 {
+ sketch.update(i, 1u64);
+ }
+ assert!(!sketch.is_estimation_mode());
+ assert_compact_round_trip(&sketch.compact(true));
+ assert_compact_round_trip(&sketch.compact(false));
+ }
+
+ #[test]
+ fn serialize_round_trip_estimation_mode() {
+ let mut sketch = TupleSketch::<u64>::builder().lg_k(5).build();
+ for i in 0..5000 {
+ sketch.update(i, 3u64);
+ }
+ let compact = sketch.compact(true);
+ assert!(compact.is_estimation_mode());
+ assert_compact_round_trip(&compact);
+ assert_compact_round_trip(&sketch.compact(false));
+ }
+
+ #[test]
+ fn serialize_round_trip_empty() {
+ let sketch = TupleSketch::<u64>::builder().build();
+ let compact = sketch.compact(true);
+ assert!(compact.is_empty());
+ assert_compact_round_trip(&compact);
+ }
+
+ #[test]
+ fn serialize_round_trip_single_entry() {
+ let mut sketch = TupleSketch::<u64>::builder().build();
+ sketch.update("only", 42u64);
+ let compact = sketch.compact(true);
+ assert_eq!(compact.num_retained(), 1);
+
+ let bytes = compact.serialize();
+ // A single-entry exact sketch uses a 1-long preamble.
+ assert_eq!(bytes[0], 1);
+
+ let restored = CompactTupleSketch::<u64>::deserialize(&bytes).unwrap();
+ assert_eq!(restored.num_retained(), 1);
+ assert_eq!(restored.iter().next().unwrap().1, &42);
+ }
+
+ #[test]
+ fn serialize_header_fields_match_tuple_format() {
+ let mut sketch = TupleSketch::<u64>::builder().build();
+ for i in 0..100 {
+ sketch.update(i, 1u64);
+ }
+ let bytes = sketch.compact(true).serialize();
+ assert_eq!(bytes[0], 2); // preamble longs (exact, multi-entry)
+ assert_eq!(bytes[1], 3); // serial version
+ assert_eq!(bytes[2], 9); // TUPLE family id
+ assert_eq!(bytes[3], 1); // sketch type
+ }
+
+ #[test]
+ fn serialize_preserves_summaries() {
+ let mut sketch = TupleSketch::<u64>::builder().build();
+ for i in 0..50 {
+ sketch.update(i, 1u64);
+ sketch.update(i, 1u64); // each summary accumulates to 2
+ }
+ let bytes = sketch.compact(true).serialize();
+ let restored = CompactTupleSketch::<u64>::deserialize(&bytes).unwrap();
+ assert_eq!(restored.num_retained(), 50);
+ assert!(restored.iter().all(|(_, &s)| s == 2));
+ }
+
+ #[test]
+ fn deserialize_rejects_wrong_family() {
+ let mut sketch = TupleSketch::<u64>::builder().build();
+ for i in 0..10 {
+ sketch.update(i, 1u64);
+ }
+ let mut bytes = sketch.compact(true).serialize();
+ bytes[2] = 3; // pretend it is a THETA sketch
+ let err = CompactTupleSketch::<u64>::deserialize(&bytes).unwrap_err();
+ assert_eq!(err.kind(), ErrorKind::InvalidData);
+ }
+
+ #[test]
+ fn deserialize_rejects_seed_mismatch() {
+ let mut sketch = TupleSketch::<u64>::builder().build();
+ for i in 0..10 {
+ sketch.update(i, 1u64);
+ }
+ let bytes = sketch.compact(true).serialize();
+ let err = CompactTupleSketch::<u64>::deserialize_with_seed(&bytes,
999).unwrap_err();
+ assert_eq!(err.kind(), ErrorKind::InvalidData);
+ }
+
+ #[test]
+ fn deserialize_rejects_truncated_summary() {
+ let mut sketch = TupleSketch::<u64>::builder().build();
+ for i in 0..100 {
+ sketch.update(i, 1u64);
+ }
+ let bytes = sketch.compact(true).serialize();
+ let truncated = &bytes[..bytes.len() - 4]; // cut the last summary in
half
+ let err =
CompactTupleSketch::<u64>::deserialize(truncated).unwrap_err();
+ assert_eq!(err.kind(), ErrorKind::InvalidData);
+ }
+}
diff --git a/datasketches/tests/tuple_serialization_test.rs
b/datasketches/tests/tuple_serialization_test.rs
new file mode 100644
index 0000000..ae692ee
--- /dev/null
+++ b/datasketches/tests/tuple_serialization_test.rs
@@ -0,0 +1,110 @@
+// 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.
+
+//! Cross-language compatibility tests for Tuple sketch serialization.
+//!
+//! The fixtures are produced by the upstream Java and C++ generators (see
+//! `tools/generate_serialization_test_data.py`):
+//!
+//! * Java: `TupleCrossLanguageTest.generateForCppIntegerSummary` writes
`tuple_int_n{n}_java.sk`
+//! using its `IntegerSummary`.
+//! * C++: `tuple_sketch_serialize_for_java.cpp` writes
`tuple_int_n{n}_cpp.sk` using an `int`
+//! summary.
+//!
+//! Both build a tuple sketch with `update(i, i)` for `i` in `0..n`, so the
summary is a 4-byte
+//! little-endian signed integer — exactly what the `i32`
[`TupleSummaryValue`] implementation
+//! reads. The `aod_*`/`aos_*` fixtures use Array-of-Doubles /
Array-of-Strings summaries, which
+//! this crate does not implement, so they are intentionally not covered here.
+
+#![cfg(feature = "tuple")]
+
+mod common;
+
+use std::fs;
+use std::path::PathBuf;
+
+use common::serialization_test_data;
+use datasketches::tuple::CompactTupleSketch;
+use googletest::assert_that;
+use googletest::prelude::near;
+
+fn test_sketch_file(path: PathBuf, expected_cardinality: usize) {
+ let expected = expected_cardinality as f64;
+
+ let bytes = fs::read(&path).unwrap();
+ let sketch1 = CompactTupleSketch::<i32>::deserialize(&bytes)
+ .unwrap_or_else(|err| panic!("Deserialization failed for {}: {}",
path.display(), err));
+
+ assert_eq!(
+ sketch1.is_empty(),
+ expected_cardinality == 0,
+ "Unexpected is_empty for {}",
+ path.display()
+ );
+
+ let estimate1 = sketch1.estimate();
+ assert_that!(estimate1, near(expected, expected * 0.03));
+
+ // Snapshots from Java/C++ are not required to match byte-for-byte output
from this
+ // implementation. Verify our own serialization is stable across a
round-trip instead.
+ let serialized_bytes = sketch1.serialize();
+ let sketch2 =
CompactTupleSketch::<i32>::deserialize(&serialized_bytes).unwrap_or_else(|err| {
+ panic!(
+ "Deserialization failed after round-trip for {}: {}",
+ path.display(),
+ err
+ )
+ });
+
+ let serialized_bytes2 = sketch2.serialize();
+ assert_eq!(
+ serialized_bytes,
+ serialized_bytes2,
+ "Serialized bytes are unstable after round-trip for {}",
+ path.display()
+ );
+
+ let estimate2 = sketch2.estimate();
+ assert_eq!(
+ estimate1,
+ estimate2,
+ "Estimates differ after round-trip for {}",
+ path.display()
+ );
+}
+
+#[test]
+fn test_java_compatibility() {
+ let test_cases = [0, 1, 10, 100, 1000, 10_000, 100_000, 1_000_000];
+
+ for n in test_cases {
+ let filename = format!("tuple_int_n{}_java.sk", n);
+ let path = serialization_test_data("java_generated_files", &filename);
+ test_sketch_file(path, n);
+ }
+}
+
+#[test]
+fn test_cpp_compatibility() {
+ let test_cases = [0, 1, 10, 100, 1000, 10_000, 100_000, 1_000_000];
+
+ for n in test_cases {
+ let filename = format!("tuple_int_n{}_cpp.sk", n);
+ let path = serialization_test_data("cpp_generated_files", &filename);
+ test_sketch_file(path, n);
+ }
+}
diff --git a/datasketches/tests/tuple_sketch_test.rs
b/datasketches/tests/tuple_sketch_test.rs
new file mode 100644
index 0000000..276ed0d
--- /dev/null
+++ b/datasketches/tests/tuple_sketch_test.rs
@@ -0,0 +1,324 @@
+// 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.
+
+//! Behavioral tests for the Tuple sketch, mirroring `theta_sketch_test.rs`.
+//!
+//! Updates carry a `u64` summary combined with the default (additive) policy,
so the distinct-count
+//! behavior matches the Theta sketch while the summaries accumulate alongside
each key.
+
+#![cfg(feature = "tuple")]
+
+use datasketches::common::NumStdDev;
+use datasketches::hash_value;
+use datasketches::tuple::TupleSketch;
+
+#[test]
+fn test_basic_update() {
+ let mut sketch = TupleSketch::<u64>::builder().lg_k(12).build();
+ assert!(sketch.is_empty());
+ assert_eq!(sketch.estimate(), 0.0);
+
+ sketch.update("value1", 1u64);
+ assert!(!sketch.is_empty());
+ assert_eq!(sketch.estimate(), 1.0);
+
+ sketch.update("value2", 1u64);
+ assert_eq!(sketch.estimate(), 2.0);
+}
+
+#[test]
+fn test_summary_accumulates_per_key() {
+ let mut sketch = TupleSketch::<u64>::builder().lg_k(12).build();
+ for _ in 0..5 {
+ sketch.update("same_key", 2u64);
+ }
+ assert_eq!(sketch.estimate(), 1.0);
+ assert_eq!(sketch.num_retained(), 1);
+ // The default policy folds each update into the retained summary: 5 * 2
== 10.
+ assert_eq!(sketch.iter().next().unwrap().1, &10);
+}
+
+#[test]
+fn test_update_various_types() {
+ let mut sketch = TupleSketch::<u64>::builder().lg_k(12).build();
+
+ sketch.update("string", 1u64);
+ sketch.update(42i64, 1u64);
+ sketch.update(42u64, 1u64);
+ // where floating-point numbers have different representations
+ sketch.update(hash_value::canonical_float::from_f64(3.15), 1u64);
+ sketch.update(hash_value::canonical_float::from_f64(3.15), 1u64);
+ sketch.update(hash_value::canonical_float::from_f32(3.15), 1u64);
+ sketch.update(hash_value::canonical_float::from_f32(3.15), 1u64);
+ sketch.update([1u8, 2, 3], 1u64);
+
+ assert!(!sketch.is_empty());
+ assert_eq!(sketch.estimate(), 5.0);
+
+ let mut sketch = TupleSketch::<u64>::builder().lg_k(12).build();
+
+ sketch.update("string", 1u64);
+ sketch.update(42i64, 1u64);
+ sketch.update(42u64, 1u64);
+ // where floating-point numbers have the same representation
+ sketch.update(hash_value::canonical_float::from_f64(5.0), 1u64);
+ sketch.update(hash_value::canonical_float::from_f64(5.0), 1u64);
+ sketch.update(hash_value::canonical_float::from_f32(5.0), 1u64);
+ sketch.update(hash_value::canonical_float::from_f32(5.0), 1u64);
+ sketch.update([1u8, 2, 3], 1u64);
+
+ assert!(!sketch.is_empty());
+ assert_eq!(sketch.estimate(), 4.0);
+}
+
+#[test]
+fn test_duplicate_updates() {
+ let mut sketch = TupleSketch::<u64>::builder().lg_k(12).build();
+
+ for _ in 0..100 {
+ sketch.update("same_value", 1u64);
+ }
+
+ assert_eq!(sketch.estimate(), 1.0);
+}
+
+#[test]
+fn test_theta_reduction() {
+ let mut sketch = TupleSketch::<u64>::builder().lg_k(5).build(); // Small k
to trigger theta reduction
+ assert!(!sketch.is_estimation_mode());
+
+ // Insert many values to trigger theta reduction
+ for i in 0..1000 {
+ sketch.update(format!("value_{}", i), 1u64);
+ }
+
+ assert!(sketch.is_estimation_mode());
+ assert!(sketch.theta() < 1.0);
+}
+
+#[test]
+fn test_trim() {
+ let mut sketch = TupleSketch::<u64>::builder().lg_k(5).build();
+
+ // Insert many values
+ for i in 0..1000 {
+ sketch.update(format!("value_{}", i), 1u64);
+ }
+
+ let before_trim = sketch.num_retained();
+ sketch.trim();
+ let after_trim = sketch.num_retained();
+
+ // After trim, should have approximately k entries
+ assert!(after_trim <= before_trim);
+ assert_eq!(sketch.num_retained(), 32);
+}
+
+#[test]
+fn test_reset() {
+ let mut sketch = TupleSketch::<u64>::builder().lg_k(5).build();
+
+ // Insert many values
+ for i in 0..1000 {
+ sketch.update(format!("value_{}", i), 1u64);
+ }
+ assert!(!sketch.is_empty());
+ assert!(sketch.is_estimation_mode());
+ assert!(sketch.num_retained() > 32);
+ assert!(sketch.theta() < 1.0);
+
+ sketch.reset();
+ assert!(sketch.is_empty());
+ assert_eq!(sketch.estimate(), 0.0);
+ assert_eq!(sketch.theta(), 1.0);
+ assert_eq!(sketch.num_retained(), 0);
+ assert!(!sketch.is_estimation_mode());
+ assert_eq!(sketch.lower_bound(NumStdDev::One), 0.0);
+ assert_eq!(sketch.upper_bound(NumStdDev::One), 0.0);
+}
+
+#[test]
+fn test_iterator() {
+ let mut sketch = TupleSketch::<u64>::builder().lg_k(12).build();
+
+ sketch.update("value1", 1u64);
+ sketch.update("value2", 1u64);
+ sketch.update("value3", 1u64);
+
+ let count: usize = sketch.iter().count();
+ assert_eq!(count, sketch.num_retained());
+}
+
+#[test]
+fn test_bounds_empty_sketch() {
+ let sketch = TupleSketch::<u64>::builder().lg_k(12).build();
+ assert!(sketch.is_empty());
+ assert!(!sketch.is_estimation_mode());
+ assert_eq!(sketch.theta(), 1.0);
+ assert_eq!(sketch.estimate(), 0.0);
+ assert_eq!(sketch.lower_bound(NumStdDev::One), 0.0);
+ assert_eq!(sketch.upper_bound(NumStdDev::One), 0.0);
+ assert_eq!(sketch.lower_bound(NumStdDev::Two), 0.0);
+ assert_eq!(sketch.upper_bound(NumStdDev::Two), 0.0);
+ assert_eq!(sketch.lower_bound(NumStdDev::Three), 0.0);
+ assert_eq!(sketch.upper_bound(NumStdDev::Three), 0.0);
+}
+
+#[test]
+fn test_bounds_exact_mode() {
+ let mut sketch = TupleSketch::<u64>::builder().lg_k(12).build();
+ for i in 0..2000 {
+ sketch.update(i, 1u64);
+ }
+ assert!(!sketch.is_empty());
+ assert!(!sketch.is_estimation_mode());
+ assert_eq!(sketch.theta(), 1.0);
+ assert_eq!(sketch.estimate(), 2000.0);
+ assert_eq!(sketch.lower_bound(NumStdDev::One), 2000.0);
+ assert_eq!(sketch.upper_bound(NumStdDev::One), 2000.0);
+}
+
+#[test]
+fn test_bounds_estimation_mode() {
+ let mut sketch = TupleSketch::<u64>::builder().lg_k(12).build();
+ let n = 10000;
+ for i in 0..n {
+ sketch.update(i, 1u64);
+ }
+ assert!(!sketch.is_empty());
+ assert!(sketch.is_estimation_mode());
+ assert!(sketch.theta() < 1.0);
+
+ let estimate = sketch.estimate();
+ let lower_bound_1 = sketch.lower_bound(NumStdDev::One);
+ let upper_bound_1 = sketch.upper_bound(NumStdDev::One);
+ let lower_bound_2 = sketch.lower_bound(NumStdDev::Two);
+ let upper_bound_2 = sketch.upper_bound(NumStdDev::Two);
+ let lower_bound_3 = sketch.lower_bound(NumStdDev::Three);
+ let upper_bound_3 = sketch.upper_bound(NumStdDev::Three);
+
+ // Check estimate is within reasonable margin (2% to be safe)
+ assert!(
+ (estimate - n as f64).abs() < n as f64 * 0.02,
+ "estimate {} is not within 2% of {}",
+ estimate,
+ n
+ );
+
+ // Check bounds are in correct order
+ assert!(lower_bound_1 < estimate);
+ assert!(estimate < upper_bound_1);
+ assert!(lower_bound_2 < estimate);
+ assert!(estimate < upper_bound_2);
+ assert!(lower_bound_3 < estimate);
+ assert!(estimate < upper_bound_3);
+
+ // Check that wider confidence intervals are indeed wider
+ assert!(lower_bound_3 < lower_bound_2);
+ assert!(lower_bound_2 < lower_bound_1);
+ assert!(upper_bound_1 < upper_bound_2);
+ assert!(upper_bound_2 < upper_bound_3);
+}
+
+#[test]
+fn test_bounds_with_sampling() {
+ let mut sketch = TupleSketch::<u64>::builder()
+ .lg_k(12)
+ .sampling_probability(0.5)
+ .build();
+
+ for i in 0..1000 {
+ sketch.update(i, 1u64);
+ }
+
+ assert!(!sketch.is_empty());
+ assert!(sketch.is_estimation_mode());
+ assert!(sketch.theta() < 1.0);
+
+ let estimate = sketch.estimate();
+ let lower_bound = sketch.lower_bound(NumStdDev::Two);
+ let upper_bound = sketch.upper_bound(NumStdDev::Two);
+
+ assert!(lower_bound <= estimate);
+ assert!(estimate <= upper_bound);
+}
+
+#[test]
+fn test_bounds_all_num_std_devs() {
+ let mut sketch = TupleSketch::<u64>::builder().lg_k(12).build();
+ for i in 0..10000 {
+ sketch.update(i, 1u64);
+ }
+
+ let lb1 = sketch.lower_bound(NumStdDev::One);
+ let lb2 = sketch.lower_bound(NumStdDev::Two);
+ let lb3 = sketch.lower_bound(NumStdDev::Three);
+ let ub1 = sketch.upper_bound(NumStdDev::One);
+ let ub2 = sketch.upper_bound(NumStdDev::Two);
+ let ub3 = sketch.upper_bound(NumStdDev::Three);
+
+ // Verify the bounds are properly ordered
+ assert!(lb3 <= lb2);
+ assert!(lb2 <= lb1);
+ assert!(ub1 <= ub2);
+ assert!(ub2 <= ub3);
+}
+
+#[test]
+fn test_bounds_empty_estimation_mode() {
+ // Create a sketch with sampling probability < 1.0 to force estimation mode
+ let sketch = TupleSketch::<u64>::builder()
+ .lg_k(12)
+ .sampling_probability(0.1)
+ .build();
+
+ // The sketch is empty but theta < 1.0, so it's in estimation mode.
+ // When empty, both bounds should return 0.0 (matching the Java/Theta
behavior).
+ assert!(sketch.is_empty());
+ assert!(sketch.is_estimation_mode());
+ assert_eq!(sketch.estimate(), 0.0);
+ assert_eq!(sketch.lower_bound(NumStdDev::One), 0.0);
+ assert_eq!(sketch.upper_bound(NumStdDev::One), 0.0);
+}
+
+#[test]
+fn test_compact_preserves_logical_non_empty_after_screened_update() {
+ let screened_value = (0u64..)
+ .find(|candidate| {
+ let mut sketch = TupleSketch::<u64>::builder()
+ .lg_k(12)
+ .sampling_probability(0.5)
+ .build();
+ sketch.update(*candidate, 1u64);
+ !sketch.is_empty() && sketch.num_retained() == 0
+ })
+ .expect("failed to find a value screened out by the sampling theta");
+
+ let mut sketch = TupleSketch::<u64>::builder()
+ .lg_k(12)
+ .sampling_probability(0.5)
+ .build();
+ sketch.update(screened_value, 1u64);
+
+ assert!(!sketch.is_empty());
+ assert_eq!(sketch.num_retained(), 0);
+
+ let compact = sketch.compact(false);
+ assert!(!compact.is_empty());
+ assert_eq!(compact.num_retained(), 0);
+ assert_eq!(compact.theta64(), sketch.theta64());
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]