diff --git a/Cargo.lock b/Cargo.lock index bcd7ad7..934545f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -698,9 +698,9 @@ checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" [[package]] name = "cc" -version = "1.2.57" +version = "1.2.58" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a0dd1ca384932ff3641c8718a02769f1698e7563dc6974ffd03346116310423" +checksum = "e1e928d4b69e3077709075a938a05ffbedfa53a84c8f766efbf8220bb1ff60e1" dependencies = [ "find-msvc-tools", "jobserver", @@ -2499,10 +2499,12 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.91" +version = "0.3.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b49715b7073f385ba4bc528e5747d02e66cb39c6146efb66b781f131f0fb399c" +checksum = "cc4c90f45aa2e6eacbe8645f77fdea542ac97a494bcd117a67df9ff4d611f995" dependencies = [ + "cfg-if", + "futures-util", "once_cell", "wasm-bindgen", ] @@ -2792,9 +2794,9 @@ dependencies = [ [[package]] name = "mio" -version = "1.1.1" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a69bcab0ad47271a0234d9422b131806bf3968021e5dc9328caf2d4cd58557fc" +checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1" dependencies = [ "libc", "wasi", @@ -4098,9 +4100,9 @@ dependencies = [ [[package]] name = "simd-adler32" -version = "0.3.8" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e320a6c5ad31d271ad523dcf3ad13e2767ad8b1cb8f047f75a8aeaf8da139da2" +checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214" [[package]] name = "siphasher" @@ -4117,6 +4119,7 @@ dependencies = [ "dsrs", "rmp-serde", "serde", + "sketchlib-rust", "xxhash-rust", ] @@ -4871,9 +4874,9 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" [[package]] name = "unicode-segmentation" -version = "1.13.1" +version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da36089a805484bcccfffe0739803392c8298778a2d2f09febf76fac5ad9025b" +checksum = "9629274872b2bfaf8d66f5f15725007f635594914870f65218920345aa11aa8c" [[package]] name = "unicode-width" @@ -4931,9 +4934,9 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "uuid" -version = "1.22.0" +version = "1.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a68d3c8f01c0cfa54a75291d83601161799e4a89a39e0929f4b0354d88757a37" +checksum = "5ac8b6f42ead25368cf5b098aeb3dc8a1a2c05a3eee8a9a1a68c640edbfc79d9" dependencies = [ "getrandom 0.4.2", "js-sys", @@ -5030,9 +5033,9 @@ dependencies = [ [[package]] name = "wasm-bindgen" -version = "0.2.114" +version = "0.2.115" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6532f9a5c1ece3798cb1c2cfdba640b9b3ba884f5db45973a6f442510a87d38e" +checksum = "6523d69017b7633e396a89c5efab138161ed5aafcbc8d3e5c5a42ae38f50495a" dependencies = [ "cfg-if", "once_cell", @@ -5043,23 +5046,19 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.64" +version = "0.4.65" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9c5522b3a28661442748e09d40924dfb9ca614b21c00d3fd135720e48b67db8" +checksum = "2d1faf851e778dfa54db7cd438b70758eba9755cb47403f3496edd7c8fc212f0" dependencies = [ - "cfg-if", - "futures-util", "js-sys", - "once_cell", "wasm-bindgen", - "web-sys", ] [[package]] name = "wasm-bindgen-macro" -version = "0.2.114" +version = "0.2.115" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "18a2d50fcf105fb33bb15f00e7a77b772945a2ee45dcf454961fd843e74c18e6" +checksum = "4e3a6c758eb2f701ed3d052ff5737f5bfe6614326ea7f3bbac7156192dc32e67" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -5067,9 +5066,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.114" +version = "0.2.115" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03ce4caeaac547cdf713d280eda22a730824dd11e6b8c3ca9e42247b25c631e3" +checksum = "921de2737904886b52bcbb237301552d05969a6f9c40d261eb0533c8b055fedf" dependencies = [ "bumpalo", "proc-macro2", @@ -5080,9 +5079,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-shared" -version = "0.2.114" +version = "0.2.115" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75a326b8c223ee17883a4251907455a2431acc2791c98c26279376490c378c16" +checksum = "a93e946af942b58934c604527337bad9ae33ba1d5c6900bbb41c2c07c2364a93" dependencies = [ "unicode-ident", ] @@ -5123,9 +5122,9 @@ dependencies = [ [[package]] name = "web-sys" -version = "0.3.91" +version = "0.3.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "854ba17bb104abfb26ba36da9729addc7ce7f06f5c0f90f3c391f8461cca21f9" +checksum = "84cde8507f4d7cfcb1185b8cb5890c494ffea65edbe1ba82cfd63661c805ed94" dependencies = [ "js-sys", "wasm-bindgen", diff --git a/asap-common/sketch-core/Cargo.toml b/asap-common/sketch-core/Cargo.toml index eb7eea2..f4f93c9 100644 --- a/asap-common/sketch-core/Cargo.toml +++ b/asap-common/sketch-core/Cargo.toml @@ -9,6 +9,7 @@ serde.workspace = true rmp-serde = "1.1" xxhash-rust = { version = "0.8", features = ["xxh32"] } dsrs = { git = "https://github.com/ProjectASAP/datasketches-rs", rev = "d748ec75c80fff21f7b24897244dd1c895df2e9a" } +sketchlib-rust = { git = "https://github.com/ProjectASAP/sketchlib-rust", rev = "440427438fdaf3ac2298b53ee148f9e12a64ffcc" } clap = { version = "4.0", features = ["derive"] } [dev-dependencies] diff --git a/asap-common/sketch-core/report.md b/asap-common/sketch-core/report.md index a8c31c6..1230f10 100644 --- a/asap-common/sketch-core/report.md +++ b/asap-common/sketch-core/report.md @@ -1,23 +1,17 @@ # Sketchlib Fidelity Report -Compares the **legacy** sketch implementations in `sketch-core` vs the new **sketchlib-rust** backends for: +Compares the **legacy** Count-Min Sketch implementation in `sketch-core` vs the new **sketchlib-rust** backend. -- `CountMinSketch` -- `CountMinSketchWithHeap` (Count-Min portion) -- `KllSketch` -- `HydraKllSketch` (via `KllSketch`) +## Fidelity harness -## Running Fidelity Tests +The fidelity binary selects backends via CLI flags. -The fidelity binary selects backends via CLI flags instead of environment variables. +| Goal | Command | +|-------------|---------------------------------------------------------------| +| CMS sketchlib | `cargo run -p sketch-core --bin sketchlib_fidelity -- --cms-impl sketchlib` | +| CMS legacy | `cargo run -p sketch-core --bin sketchlib_fidelity -- --cms-impl legacy` | -| Goal | Command | -|--------------------------|--------------------------------------------------------------------------------------------------------------| -| Default (all sketchlib) | `cargo run -p sketch-core --bin sketchlib_fidelity` | -| All legacy | `cargo run -p sketch-core --bin sketchlib_fidelity -- --cms-impl legacy --kll-impl legacy --cmwh-impl legacy` | -| Legacy KLL only | `cargo run -p sketch-core --bin sketchlib_fidelity -- --cms-impl sketchlib --kll-impl legacy --cmwh-impl sketchlib` | - -## Unit Tests +## Unit tests Unit tests always run with **legacy** backends enabled (the test ctor calls `force_legacy_mode_for_tests()`), so you only need: @@ -28,4 +22,27 @@ cargo test -p sketch-core ## Results -Fidelity results will be added as sketch implementations are integrated in subsequent PRs. +### CountMinSketch (accuracy vs exact counts) + +#### depth=3 + +| width | n | domain | Mode | Pearson corr | MAPE (%) | RMSE (%) | +|-------|--------|--------|----------------|----------------|----------|----------| +| 1024 | 100000 | 1000 | Legacy | 0.9998451189 | 24.48 | 52.76 | +| 1024 | 100000 | 1000 | sketchlib-rust | 0.9998387103 | 24.36 | 54.11 | + +#### depth=5 + +| width | n | domain | Mode | Pearson corr | MAPE (%) | RMSE (%) | +|-------|--------|--------|----------------|----------------|----------|----------| +| 2048 | 200000 | 2000 | Legacy | 0.9999733814 | 8.75 | 29.94 | +| 2048 | 200000 | 2000 | sketchlib-rust | 0.9999744627 | 8.37 | 28.84 | +| 2048 | 50000 | 500 | Legacy | 1.0000000000 | 0.00 | 0.00 | +| 2048 | 50000 | 500 | sketchlib-rust | 1.0000000000 | 0.00 | 0.00 | + +#### depth=7 + +| width | n | domain | Mode | Pearson corr | MAPE (%) | RMSE (%) | +|-------|--------|--------|----------------|----------------|----------|----------| +| 4096 | 200000 | 2000 | Legacy | 0.9999993694 | 0.20 | 3.69 | +| 4096 | 200000 | 2000 | sketchlib-rust | 0.9999993499 | 0.21 | 4.27 | diff --git a/asap-common/sketch-core/src/bin/sketchlib_fidelity.rs b/asap-common/sketch-core/src/bin/sketchlib_fidelity.rs index cff9ac1..8fd08e3 100644 --- a/asap-common/sketch-core/src/bin/sketchlib_fidelity.rs +++ b/asap-common/sketch-core/src/bin/sketchlib_fidelity.rs @@ -1,8 +1,9 @@ -// Scaffold for fidelity benchmarks; helpers used in later PRs when sketch types are integrated. +// Fidelity benchmarks comparing legacy vs sketchlib implementations across sketch types. #![allow(dead_code)] use clap::Parser; use sketch_core::config::{self, ImplMode}; +use sketch_core::count_min::CountMinSketch; #[derive(Clone)] struct Lcg64 { @@ -97,13 +98,58 @@ fn rank_fraction(sorted: &[f64], x: f64) -> f64 { (idx as f64) / (sorted.len() as f64) } +// --- CountMinSketch parameter sets and runner --- + +struct CmsParams { + depth: usize, + width: usize, + n: usize, + domain: usize, +} + +struct CmsResult { + pearson: f64, + mape: f64, + rmse: f64, +} + +fn run_countmin_once(seed: u64, p: &CmsParams) -> CmsResult { + let mut rng = Lcg64::new(seed); + let mut exact: Vec = vec![0.0; p.domain]; + let mut cms = CountMinSketch::new(p.depth, p.width); + + for _ in 0..p.n { + let r = rng.next_u64(); + let key_id = if (r & 0xFF) < 200 { + (r as usize) % 20 + } else { + (r as usize) % p.domain + }; + let key = format!("k{key_id}"); + cms.update(&key, 1.0); + exact[key_id] += 1.0; + } + + let mut est: Vec = Vec::with_capacity(p.domain); + for key_id in 0..p.domain { + let key = format!("k{key_id}"); + est.push(cms.query_key(&key)); + } + + CmsResult { + pearson: pearson_corr(&exact, &est), + mape: mape(&exact, &est), + rmse: rmse_percentage(&exact, &est), + } +} + #[derive(Parser)] struct Args { - #[arg(long, value_enum, default_value_t = sketch_core::config::DEFAULT_IMPL_MODE)] + #[arg(long, value_enum, default_value_t = sketch_core::config::DEFAULT_CMS_IMPL)] cms_impl: ImplMode, - #[arg(long, value_enum, default_value_t = sketch_core::config::DEFAULT_IMPL_MODE)] + #[arg(long, value_enum, default_value_t = sketch_core::config::DEFAULT_KLL_IMPL)] kll_impl: ImplMode, - #[arg(long, value_enum, default_value_t = sketch_core::config::DEFAULT_IMPL_MODE)] + #[arg(long, value_enum, default_value_t = sketch_core::config::DEFAULT_CMWH_IMPL)] cmwh_impl: ImplMode, } @@ -112,6 +158,7 @@ fn main() { config::configure(args.cms_impl, args.kll_impl, args.cmwh_impl) .expect("sketch backend already initialised"); + let seed = 0xC0FFEE_u64; let mode = if matches!(args.cms_impl, ImplMode::Legacy) || matches!(args.kll_impl, ImplMode::Legacy) || matches!(args.cmwh_impl, ImplMode::Legacy) @@ -121,7 +168,42 @@ fn main() { "sketchlib-rust" }; - println!("# Sketchlib Fidelity Report ({})", mode); - println!(); - println!("Fidelity tests will be added as sketch implementations are integrated."); + // CountMinSketch: multiple (depth, width, n, domain) + let cms_param_sets: Vec = vec![ + CmsParams { + depth: 3, + width: 1024, + n: 100_000, + domain: 1000, + }, + CmsParams { + depth: 5, + width: 2048, + n: 200_000, + domain: 2000, + }, + CmsParams { + depth: 7, + width: 4096, + n: 200_000, + domain: 2000, + }, + CmsParams { + depth: 5, + width: 2048, + n: 50_000, + domain: 500, + }, + ]; + + println!("## CountMinSketch ({mode})"); + println!("| depth | width | n_updates | domain | Pearson corr | MAPE (%) | RMSE (%) |"); + println!("|-------|-------|------------|--------|--------------|----------|----------|"); + for p in &cms_param_sets { + let r = run_countmin_once(seed, p); + println!( + "| {} | {} | {} | {} | {:.10} | {:.6} | {:.6} |", + p.depth, p.width, p.n, p.domain, r.pearson, r.mape, r.rmse + ); + } } diff --git a/asap-common/sketch-core/src/config.rs b/asap-common/sketch-core/src/config.rs index 0812b3e..9f49ad7 100644 --- a/asap-common/sketch-core/src/config.rs +++ b/asap-common/sketch-core/src/config.rs @@ -9,22 +9,26 @@ pub enum ImplMode { Sketchlib, } -/// Default backend when not explicitly configured (e.g. for binaries that don't pass CLI args). -/// Single source of truth for sketch backend defaults. +/// Global default when impl mode is not explicitly configured (e.g. env var parsing). pub const DEFAULT_IMPL_MODE: ImplMode = ImplMode::Legacy; +/// Per-backend defaults. Used when configure() has not been called. +pub const DEFAULT_CMS_IMPL: ImplMode = ImplMode::Sketchlib; +pub const DEFAULT_KLL_IMPL: ImplMode = ImplMode::Legacy; +pub const DEFAULT_CMWH_IMPL: ImplMode = ImplMode::Legacy; + static COUNTMIN_MODE: OnceLock = OnceLock::new(); /// Returns true if Count-Min operations should use sketchlib-rust internally. pub fn use_sketchlib_for_count_min() -> bool { - *COUNTMIN_MODE.get_or_init(|| DEFAULT_IMPL_MODE) == ImplMode::Sketchlib + *COUNTMIN_MODE.get_or_init(|| DEFAULT_CMS_IMPL) == ImplMode::Sketchlib } static KLL_MODE: OnceLock = OnceLock::new(); /// Returns true if KLL operations should use sketchlib-rust internally. pub fn use_sketchlib_for_kll() -> bool { - *KLL_MODE.get_or_init(|| DEFAULT_IMPL_MODE) == ImplMode::Sketchlib + *KLL_MODE.get_or_init(|| DEFAULT_KLL_IMPL) == ImplMode::Sketchlib } static COUNTMIN_WITH_HEAP_MODE: OnceLock = OnceLock::new(); @@ -32,7 +36,7 @@ static COUNTMIN_WITH_HEAP_MODE: OnceLock = OnceLock::new(); /// Returns true if Count-Min-With-Heap operations should use sketchlib-rust internally for the /// Count-Min portion. pub fn use_sketchlib_for_count_min_with_heap() -> bool { - *COUNTMIN_WITH_HEAP_MODE.get_or_init(|| DEFAULT_IMPL_MODE) == ImplMode::Sketchlib + *COUNTMIN_WITH_HEAP_MODE.get_or_init(|| DEFAULT_CMWH_IMPL) == ImplMode::Sketchlib } /// Set backend modes for all sketch types. Call once at process startup, diff --git a/asap-common/sketch-core/src/count_min.rs b/asap-common/sketch-core/src/count_min.rs index fcd7794..a77e8bb 100644 --- a/asap-common/sketch-core/src/count_min.rs +++ b/asap-common/sketch-core/src/count_min.rs @@ -14,47 +14,113 @@ use serde::{Deserialize, Serialize}; use xxhash_rust::xxh32::xxh32; +use crate::config::use_sketchlib_for_count_min; +use crate::count_min_sketchlib::{ + matrix_from_sketchlib_cms, new_sketchlib_cms, sketchlib_cms_from_matrix, sketchlib_cms_query, + sketchlib_cms_update, SketchlibCms, +}; + +#[derive(Serialize, Deserialize)] +struct WireFormat { + sketch: Vec>, + row_num: usize, + col_num: usize, +} + +/// Backend implementation for Count-Min Sketch. Only one is active at a time. +#[derive(Debug, Clone)] +pub enum CountMinBackend { + /// Original hand-written matrix implementation. + Legacy(Vec>), + /// sketchlib-rust backed implementation. + Sketchlib(SketchlibCms), +} + /// Count-Min Sketch probabilistic data structure for frequency counting. /// Provides approximate frequency counts with error bounds. /// This is the canonical shared implementation; the msgpack wire format is the /// contract between Arroyo UDAFs (producers) and QueryEngineRust (consumer). -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone)] pub struct CountMinSketch { - pub sketch: Vec>, pub row_num: usize, pub col_num: usize, + pub backend: CountMinBackend, } impl CountMinSketch { pub fn new(row_num: usize, col_num: usize) -> Self { - let sketch = vec![vec![0.0; col_num]; row_num]; + let backend = if use_sketchlib_for_count_min() { + CountMinBackend::Sketchlib(new_sketchlib_cms(row_num, col_num)) + } else { + CountMinBackend::Legacy(vec![vec![0.0; col_num]; row_num]) + }; Self { - sketch, row_num, col_num, + backend, + } + } + + /// Returns the sketch matrix (for wire format, serialization, tests). + pub fn sketch(&self) -> Vec> { + match &self.backend { + CountMinBackend::Legacy(m) => m.clone(), + CountMinBackend::Sketchlib(s) => matrix_from_sketchlib_cms(s), + } + } + + /// Mutable access to the matrix. Only `Some` for Legacy backend. + pub fn sketch_mut(&mut self) -> Option<&mut Vec>> { + match &mut self.backend { + CountMinBackend::Legacy(m) => Some(m), + CountMinBackend::Sketchlib(_) => None, + } + } + + /// Construct from a legacy matrix (used by deserialization and query engine). + pub fn from_legacy_matrix(sketch: Vec>, row_num: usize, col_num: usize) -> Self { + let backend = if use_sketchlib_for_count_min() { + CountMinBackend::Sketchlib(sketchlib_cms_from_matrix(row_num, col_num, &sketch)) + } else { + CountMinBackend::Legacy(sketch) + }; + Self { + row_num, + col_num, + backend, } } pub fn update(&mut self, key: &str, value: f64) { - let key_bytes = key.as_bytes(); - // Update each row using different hash functions - for i in 0..self.row_num { - let hash_value = xxh32(key_bytes, i as u32); - let col_index = (hash_value as usize) % self.col_num; - self.sketch[i][col_index] += value; + match &mut self.backend { + CountMinBackend::Legacy(sketch) => { + let key_bytes = key.as_bytes(); + for (i, row) in sketch.iter_mut().enumerate().take(self.row_num) { + let hash_value = xxh32(key_bytes, i as u32); + let col_index = (hash_value as usize) % self.col_num; + row[col_index] += value; + } + } + CountMinBackend::Sketchlib(s) => { + sketchlib_cms_update(s, key, value); + } } } pub fn query_key(&self, key: &str) -> f64 { - let key_bytes = key.as_bytes(); - let mut min_value = f64::MAX; - // Query each row and take the minimum - for i in 0..self.row_num { - let hash_value = xxh32(key_bytes, i as u32); - let col_index = (hash_value as usize) % self.col_num; - min_value = min_value.min(self.sketch[i][col_index]); + match &self.backend { + CountMinBackend::Legacy(sketch) => { + let key_bytes = key.as_bytes(); + let mut min_value = f64::MAX; + for (i, row) in sketch.iter().enumerate().take(self.row_num) { + let hash_value = xxh32(key_bytes, i as u32); + let col_index = (hash_value as usize) % self.col_num; + min_value = min_value.min(row[col_index]); + } + min_value + } + CountMinBackend::Sketchlib(s) => sketchlib_cms_query(s, key), } - min_value } pub fn merge( @@ -80,17 +146,44 @@ impl CountMinSketch { } } - let mut merged = accumulators[0].clone(); - // Add all sketches element-wise - for acc in &accumulators[1..] { - for (merged_row, acc_row) in merged.sketch.iter_mut().zip(&acc.sketch) { - for (m_cell, a_cell) in merged_row.iter_mut().zip(acc_row.iter()) { - *m_cell += *a_cell; + if use_sketchlib_for_count_min() { + let mut sketchlib_inners: Vec = Vec::with_capacity(accumulators.len()); + for acc in accumulators { + let matrix = acc.sketch(); + let inner = sketchlib_cms_from_matrix(acc.row_num, acc.col_num, &matrix); + sketchlib_inners.push(inner); + } + let merged_sketchlib = sketchlib_inners + .into_iter() + .reduce(|mut lhs: SketchlibCms, rhs: SketchlibCms| { + lhs.merge(&rhs); + lhs + }) + .ok_or("No accumulators to merge")?; + + let sketch = matrix_from_sketchlib_cms(&merged_sketchlib); + let row_num = sketch.len(); + let col_num = sketch.first().map(|r| r.len()).unwrap_or(0); + + Ok(Self { + row_num, + col_num, + backend: CountMinBackend::Sketchlib(merged_sketchlib), + }) + } else { + let mut merged = accumulators[0].clone(); + for acc in &accumulators[1..] { + let acc_matrix = acc.sketch(); + if let CountMinBackend::Legacy(merged_matrix) = &mut merged.backend { + for (merged_row, acc_row) in merged_matrix.iter_mut().zip(acc_matrix.iter()) { + for (m_cell, a_cell) in merged_row.iter_mut().zip(acc_row.iter()) { + *m_cell += *a_cell; + } + } } } + Ok(merged) } - - Ok(merged) } /// Merge from references, allocating only the output — no input clones. @@ -112,31 +205,94 @@ impl CountMinSketch { } } - let mut merged = Self::new(row_num, col_num); - for acc in accumulators { - for (merged_row, acc_row) in merged.sketch.iter_mut().zip(&acc.sketch) { - for (m_cell, a_cell) in merged_row.iter_mut().zip(acc_row.iter()) { - *m_cell += *a_cell; + if use_sketchlib_for_count_min() { + let mut sketchlib_inners: Vec = Vec::with_capacity(accumulators.len()); + for acc in accumulators { + let acc_matrix = acc.sketch(); + let matrix_has_values = acc_matrix + .iter() + .any(|row: &Vec| row.iter().any(|&v| v != 0.0)); + + let inner = if matrix_has_values { + sketchlib_cms_from_matrix(acc.row_num, acc.col_num, &acc_matrix) + } else if let CountMinBackend::Sketchlib(s) = &acc.backend { + s.clone() + } else { + sketchlib_cms_from_matrix(acc.row_num, acc.col_num, &acc_matrix) + }; + + sketchlib_inners.push(inner); + } + + let merged_sketchlib = sketchlib_inners + .into_iter() + .reduce(|mut lhs: SketchlibCms, rhs: SketchlibCms| { + lhs.merge(&rhs); + lhs + }) + .ok_or("No accumulators to merge")?; + + let sketch = matrix_from_sketchlib_cms(&merged_sketchlib); + let r = sketch.len(); + let c = sketch.first().map(|row| row.len()).unwrap_or(0); + + Ok(Self { + row_num: r, + col_num: c, + backend: CountMinBackend::Sketchlib(merged_sketchlib), + }) + } else { + let mut merged = Self::new(row_num, col_num); + if let CountMinBackend::Legacy(ref mut merged_sketch) = merged.backend { + for acc in accumulators { + let acc_matrix = acc.sketch(); + for (merged_row, acc_row) in merged_sketch.iter_mut().zip(acc_matrix.iter()) { + for (m_cell, a_cell) in merged_row.iter_mut().zip(acc_row.iter()) { + *m_cell += *a_cell; + } + } } } + Ok(merged) } - - Ok(merged) } /// Serialize to MessagePack — matches the Arroyo UDF wire format exactly. pub fn serialize_msgpack(&self) -> Vec { - // Match Arroyo UDF: countminsketch.serialize(&mut Serializer::new(&mut buf)) + let sketch = self.sketch(); + let wire = WireFormat { + sketch, + row_num: self.row_num, + col_num: self.col_num, + }; + let mut buf = Vec::new(); - self.serialize(&mut rmp_serde::Serializer::new(&mut buf)) + wire.serialize(&mut rmp_serde::Serializer::new(&mut buf)) .unwrap(); buf } /// Deserialize from MessagePack produced by the Arroyo UDF. pub fn deserialize_msgpack(buffer: &[u8]) -> Result> { - rmp_serde::from_slice(buffer).map_err(|e| { - format!("Failed to deserialize CountMinSketch from MessagePack: {e}").into() + let wire: WireFormat = + rmp_serde::from_slice(buffer).map_err(|e| -> Box { + format!("Failed to deserialize CountMinSketch from MessagePack: {e}").into() + })?; + + let backend = if use_sketchlib_for_count_min() { + CountMinBackend::Sketchlib(sketchlib_cms_from_matrix( + wire.row_num, + wire.col_num, + &wire.sketch, + )) + } else { + CountMinBackend::Legacy(wire.sketch) + }; + + Ok(Self { + row_num: wire.row_num, + col_num: wire.col_num, + backend, }) } @@ -178,11 +334,12 @@ mod tests { let cms = CountMinSketch::new(4, 1000); assert_eq!(cms.row_num, 4); assert_eq!(cms.col_num, 1000); - assert_eq!(cms.sketch.len(), 4); - assert_eq!(cms.sketch[0].len(), 1000); + let sketch = cms.sketch(); + assert_eq!(sketch.len(), 4); + assert_eq!(sketch[0].len(), 1000); // Check all values are initialized to 0 - for row in &cms.sketch { + for row in &sketch { for &value in row { assert_eq!(value, 0.0); } @@ -206,20 +363,23 @@ mod tests { #[test] fn test_count_min_sketch_merge() { - let mut cms1 = CountMinSketch::new(2, 3); - let mut cms2 = CountMinSketch::new(2, 3); - - cms1.sketch[0][0] = 5.0; - cms1.sketch[1][2] = 10.0; + // Use from_legacy_matrix so the test works regardless of sketchlib/legacy config + let mut sketch1 = vec![vec![0.0; 3]; 2]; + sketch1[0][0] = 5.0; + sketch1[1][2] = 10.0; + let cms1 = CountMinSketch::from_legacy_matrix(sketch1, 2, 3); - cms2.sketch[0][0] = 3.0; - cms2.sketch[0][1] = 7.0; + let mut sketch2 = vec![vec![0.0; 3]; 2]; + sketch2[0][0] = 3.0; + sketch2[0][1] = 7.0; + let cms2 = CountMinSketch::from_legacy_matrix(sketch2, 2, 3); let merged = CountMinSketch::merge(vec![cms1, cms2]).unwrap(); + let merged_sketch = merged.sketch(); - assert_eq!(merged.sketch[0][0], 8.0); // 5 + 3 - assert_eq!(merged.sketch[0][1], 7.0); // 0 + 7 - assert_eq!(merged.sketch[1][2], 10.0); // 10 + 0 + assert_eq!(merged_sketch[0][0], 8.0); // 5 + 3 + assert_eq!(merged_sketch[0][1], 7.0); // 0 + 7 + assert_eq!(merged_sketch[1][2], 10.0); // 10 + 0 } #[test] @@ -231,17 +391,18 @@ mod tests { #[test] fn test_count_min_sketch_msgpack_round_trip() { - let mut cms = CountMinSketch::new(2, 3); - cms.sketch[0][1] = 42.0; - cms.sketch[1][2] = 100.0; + let mut cms = CountMinSketch::new(4, 256); + cms.update("apple", 5.0); + cms.update("banana", 3.0); + cms.update("apple", 2.0); // total "apple" = 7 let bytes = cms.serialize_msgpack(); let deserialized = CountMinSketch::deserialize_msgpack(&bytes).unwrap(); - assert_eq!(deserialized.row_num, 2); - assert_eq!(deserialized.col_num, 3); - assert_eq!(deserialized.sketch[0][1], 42.0); - assert_eq!(deserialized.sketch[1][2], 100.0); + assert_eq!(deserialized.row_num, 4); + assert_eq!(deserialized.col_num, 256); + assert!(deserialized.query_key("apple") >= 7.0); + assert!(deserialized.query_key("banana") >= 3.0); } #[test] diff --git a/asap-common/sketch-core/src/count_min_sketchlib.rs b/asap-common/sketch-core/src/count_min_sketchlib.rs new file mode 100644 index 0000000..20fe7be --- /dev/null +++ b/asap-common/sketch-core/src/count_min_sketchlib.rs @@ -0,0 +1,59 @@ +use sketchlib_rust::{CountMin, RegularPath, SketchInput, Vector2D}; + +/// Concrete Count-Min type from sketchlib-rust when sketchlib backend is enabled. +/// Uses f64 counters (Vector2D) for weighted updates without integer rounding. +pub type SketchlibCms = CountMin, RegularPath>; + +/// Creates a fresh sketchlib Count-Min sketch with the given dimensions. +pub fn new_sketchlib_cms(row_num: usize, col_num: usize) -> SketchlibCms { + SketchlibCms::with_dimensions(row_num, col_num) +} + +/// Builds a sketchlib Count-Min sketch from an existing `sketch` matrix. +pub fn sketchlib_cms_from_matrix( + row_num: usize, + col_num: usize, + sketch: &[Vec], +) -> SketchlibCms { + let matrix = Vector2D::from_fn(row_num, col_num, |r, c| { + sketch + .get(r) + .and_then(|row| row.get(c)) + .copied() + .unwrap_or(0.0) + }); + SketchlibCms::from_storage(matrix) +} + +/// Converts a sketchlib Count-Min sketch into the legacy `Vec>` matrix. +pub fn matrix_from_sketchlib_cms(inner: &SketchlibCms) -> Vec> { + let storage: &Vector2D = inner.as_storage(); + let rows = storage.rows(); + let cols = storage.cols(); + let mut sketch = vec![vec![0.0; cols]; rows]; + + for (r, row) in sketch.iter_mut().enumerate().take(rows) { + for (c, cell) in row.iter_mut().enumerate().take(cols) { + if let Some(v) = storage.get(r, c) { + *cell = *v; + } + } + } + + sketch +} + +/// Helper to update a sketchlib Count-Min with a weighted key. +pub fn sketchlib_cms_update(inner: &mut SketchlibCms, key: &str, value: f64) { + if value <= 0.0 { + return; + } + let input = SketchInput::String(key.to_owned()); + inner.insert_many(&input, value); +} + +/// Helper to query a sketchlib Count-Min for a key, returning f64. +pub fn sketchlib_cms_query(inner: &SketchlibCms, key: &str) -> f64 { + let input = SketchInput::String(key.to_owned()); + inner.estimate(&input) +} diff --git a/asap-common/sketch-core/src/lib.rs b/asap-common/sketch-core/src/lib.rs index 7d92ad1..f2616c2 100644 --- a/asap-common/sketch-core/src/lib.rs +++ b/asap-common/sketch-core/src/lib.rs @@ -6,6 +6,7 @@ fn init_sketch_legacy_for_tests() { pub mod config; pub mod count_min; +pub mod count_min_sketchlib; pub mod count_min_with_heap; pub mod delta_set_aggregator; pub mod hydra_kll; diff --git a/asap-query-engine/src/lib.rs b/asap-query-engine/src/lib.rs index a51c620..e70ad09 100644 --- a/asap-query-engine/src/lib.rs +++ b/asap-query-engine/src/lib.rs @@ -4,8 +4,8 @@ fn init_sketch_backend_for_tests() { #[cfg(feature = "sketchlib-tests")] let _ = sketch_core::config::configure( sketch_core::config::ImplMode::Sketchlib, - sketch_core::config::ImplMode::Sketchlib, - sketch_core::config::ImplMode::Sketchlib, + sketch_core::config::ImplMode::Legacy, + sketch_core::config::ImplMode::Legacy, ); #[cfg(not(feature = "sketchlib-tests"))] sketch_core::config::force_legacy_mode_for_tests(); diff --git a/asap-query-engine/src/main.rs b/asap-query-engine/src/main.rs index 3e437aa..00be2fe 100644 --- a/asap-query-engine/src/main.rs +++ b/asap-query-engine/src/main.rs @@ -111,15 +111,15 @@ struct Args { promsketch_config: Option, /// Backend implementation for Count-Min Sketch (legacy | sketchlib) - #[arg(long, value_enum, default_value_t = config::DEFAULT_IMPL_MODE)] + #[arg(long, value_enum, default_value_t = config::DEFAULT_CMS_IMPL)] sketch_cms_impl: ImplMode, /// Backend implementation for KLL Sketch (legacy | sketchlib) - #[arg(long, value_enum, default_value_t = config::DEFAULT_IMPL_MODE)] + #[arg(long, value_enum, default_value_t = config::DEFAULT_KLL_IMPL)] sketch_kll_impl: ImplMode, /// Backend implementation for Count-Min-With-Heap (legacy | sketchlib) - #[arg(long, value_enum, default_value_t = config::DEFAULT_IMPL_MODE)] + #[arg(long, value_enum, default_value_t = config::DEFAULT_CMWH_IMPL)] sketch_cmwh_impl: ImplMode, /// Enable OTLP metrics ingest (gRPC + HTTP) diff --git a/asap-query-engine/src/precompute_operators/count_min_sketch_accumulator.rs b/asap-query-engine/src/precompute_operators/count_min_sketch_accumulator.rs index bba716d..e149cba 100644 --- a/asap-query-engine/src/precompute_operators/count_min_sketch_accumulator.rs +++ b/asap-query-engine/src/precompute_operators/count_min_sketch_accumulator.rs @@ -56,11 +56,7 @@ impl CountMinSketchAccumulator { } Ok(Self { - inner: CountMinSketch { - sketch, - row_num, - col_num, - }, + inner: CountMinSketch::from_legacy_matrix(sketch, row_num, col_num), }) } @@ -111,11 +107,7 @@ impl CountMinSketchAccumulator { } Ok(Self { - inner: CountMinSketch { - row_num, - col_num, - sketch, - }, + inner: CountMinSketch::from_legacy_matrix(sketch, row_num, col_num), }) } @@ -168,7 +160,7 @@ impl SerializableToSink for CountMinSketchAccumulator { serde_json::json!({ "row_num": self.inner.row_num, "col_num": self.inner.col_num, - "sketch": self.inner.sketch + "sketch": self.inner.sketch() }) } @@ -261,10 +253,11 @@ mod tests { let cms = CountMinSketchAccumulator::new(4, 1000); assert_eq!(cms.inner.row_num, 4); assert_eq!(cms.inner.col_num, 1000); - assert_eq!(cms.inner.sketch.len(), 4); - assert_eq!(cms.inner.sketch[0].len(), 1000); + let sketch = cms.inner.sketch(); + assert_eq!(sketch.len(), 4); + assert_eq!(sketch[0].len(), 1000); - for row in &cms.inner.sketch { + for row in &sketch { for &value in row { assert_eq!(value, 0.0); } @@ -292,19 +285,28 @@ mod tests { #[test] fn test_count_min_sketch_merge() { - let mut cms1 = CountMinSketchAccumulator::new(2, 3); - let mut cms2 = CountMinSketchAccumulator::new(2, 3); - - cms1.inner.sketch[0][0] = 5.0; - cms1.inner.sketch[1][2] = 10.0; - cms2.inner.sketch[0][0] = 3.0; - cms2.inner.sketch[0][1] = 7.0; + // Build controlled state via from_legacy_matrix (works for both Legacy and Sketchlib backends). + let cms1 = CountMinSketchAccumulator { + inner: CountMinSketch::from_legacy_matrix( + vec![vec![5.0, 0.0, 0.0], vec![0.0, 0.0, 10.0]], + 2, + 3, + ), + }; + let cms2 = CountMinSketchAccumulator { + inner: CountMinSketch::from_legacy_matrix( + vec![vec![3.0, 7.0, 0.0], vec![0.0, 0.0, 0.0]], + 2, + 3, + ), + }; let merged = CountMinSketchAccumulator::merge_accumulators(vec![cms1, cms2]).unwrap(); - assert_eq!(merged.inner.sketch[0][0], 8.0); - assert_eq!(merged.inner.sketch[0][1], 7.0); - assert_eq!(merged.inner.sketch[1][2], 10.0); + let merged_sketch = merged.inner.sketch(); + assert_eq!(merged_sketch[0][0], 8.0); + assert_eq!(merged_sketch[0][1], 7.0); + assert_eq!(merged_sketch[1][2], 10.0); } #[test] @@ -317,9 +319,13 @@ mod tests { #[test] fn test_count_min_sketch_serialization() { - let mut cms = CountMinSketchAccumulator::new(2, 3); - cms.inner.sketch[0][1] = 42.0; - cms.inner.sketch[1][2] = 100.0; + let cms = CountMinSketchAccumulator { + inner: CountMinSketch::from_legacy_matrix( + vec![vec![0.0, 42.0, 0.0], vec![0.0, 0.0, 100.0]], + 2, + 3, + ), + }; let bytes = cms.serialize_to_bytes(); let deserialized = @@ -327,8 +333,9 @@ mod tests { assert_eq!(deserialized.inner.row_num, 2); assert_eq!(deserialized.inner.col_num, 3); - assert_eq!(deserialized.inner.sketch[0][1], 42.0); - assert_eq!(deserialized.inner.sketch[1][2], 100.0); + let deser_sketch = deserialized.inner.sketch(); + assert_eq!(deser_sketch[0][1], 42.0); + assert_eq!(deser_sketch[1][2], 100.0); } #[test] @@ -396,25 +403,38 @@ mod tests { #[test] fn test_count_min_sketch_merge_multiple() { - let mut cms1 = CountMinSketchAccumulator::new(2, 3); - let mut cms2 = CountMinSketchAccumulator::new(2, 3); - let mut cms3 = CountMinSketchAccumulator::new(2, 3); - - cms1.inner.sketch[0][0] = 5.0; - cms1.inner.sketch[1][2] = 10.0; - cms2.inner.sketch[0][0] = 3.0; - cms2.inner.sketch[0][1] = 7.0; - cms3.inner.sketch[0][0] = 2.0; - cms3.inner.sketch[1][2] = 5.0; + // Build controlled state via from_legacy_matrix (works for both Legacy and Sketchlib backends). + let cms1 = CountMinSketchAccumulator { + inner: CountMinSketch::from_legacy_matrix( + vec![vec![5.0, 0.0, 0.0], vec![0.0, 0.0, 10.0]], + 2, + 3, + ), + }; + let cms2 = CountMinSketchAccumulator { + inner: CountMinSketch::from_legacy_matrix( + vec![vec![3.0, 7.0, 0.0], vec![0.0, 0.0, 0.0]], + 2, + 3, + ), + }; + let cms3 = CountMinSketchAccumulator { + inner: CountMinSketch::from_legacy_matrix( + vec![vec![2.0, 0.0, 0.0], vec![0.0, 0.0, 5.0]], + 2, + 3, + ), + }; let boxed_accs: Vec> = vec![Box::new(cms1), Box::new(cms2), Box::new(cms3)]; let merged = CountMinSketchAccumulator::merge_multiple(&boxed_accs).unwrap(); - assert_eq!(merged.inner.sketch[0][0], 10.0); - assert_eq!(merged.inner.sketch[0][1], 7.0); - assert_eq!(merged.inner.sketch[1][2], 15.0); + let merged_sketch = merged.inner.sketch(); + assert_eq!(merged_sketch[0][0], 10.0); + assert_eq!(merged_sketch[0][1], 7.0); + assert_eq!(merged_sketch[1][2], 15.0); } #[test] diff --git a/asap-summary-ingest/run_arroyosketch.py b/asap-summary-ingest/run_arroyosketch.py index d5f7414..3de3f28 100644 --- a/asap-summary-ingest/run_arroyosketch.py +++ b/asap-summary-ingest/run_arroyosketch.py @@ -443,8 +443,8 @@ def create_pipeline( template_path = os.path.join(udf_dir, f"{udf_name}.rs.j2") regular_path = os.path.join(udf_dir, f"{udf_name}.rs") - # Get parameters for this UDF - params = agg_function_params.get(udf_name, {}) + # Get parameters for this UDF (impl_mode injected in main() for sketch UDFs) + params = dict(agg_function_params.get(udf_name, {})) if len(params) > 0 and not os.path.exists(template_path): raise ValueError( @@ -943,6 +943,20 @@ def main(args): filter_metric_name, ) + parameters = dict(parameters) + if agg_function in ("countminsketch_count", "countminsketch_sum"): + parameters["impl_mode"] = getattr( + args, "sketch_cms_impl", "legacy" + ).capitalize() + elif agg_function == "countminsketchwithheap_topk": + parameters["impl_mode"] = getattr( + args, "sketch_cmwh_impl", "legacy" + ).capitalize() + elif agg_function in ("datasketcheskll_", "hydrakll_"): + parameters["impl_mode"] = getattr( + args, "sketch_kll_impl", "legacy" + ).capitalize() + sql_queries.append(sql_query) # if not is_labels_accumulator: agg_functions_with_params.append((agg_function, parameters)) @@ -1097,6 +1111,29 @@ def main(args): help="Query language for schema interpretation (default: promql)", ) + # Sketch implementation mode - must match QueryEngine (--sketch-cms-impl etc.) + parser.add_argument( + "--sketch_cms_impl", + type=str, + choices=["legacy", "sketchlib"], + default="sketchlib", + help="Count-Min Sketch backend (legacy | sketchlib). Must match QueryEngine.", + ) + parser.add_argument( + "--sketch_kll_impl", + type=str, + choices=["legacy", "sketchlib"], + default="legacy", + help="KLL Sketch backend (legacy | sketchlib). Must match QueryEngine.", + ) + parser.add_argument( + "--sketch_cmwh_impl", + type=str, + choices=["legacy", "sketchlib"], + default="legacy", + help="Count-Min-With-Heap backend (legacy | sketchlib). Must match QueryEngine.", + ) + args = parser.parse_args() check_args(args) main(args) diff --git a/asap-summary-ingest/templates/udfs/countminsketch_count.rs.j2 b/asap-summary-ingest/templates/udfs/countminsketch_count.rs.j2 index 16b532c..6da33fb 100644 --- a/asap-summary-ingest/templates/udfs/countminsketch_count.rs.j2 +++ b/asap-summary-ingest/templates/udfs/countminsketch_count.rs.j2 @@ -3,16 +3,35 @@ rmp-serde = "1.1" serde = { version = "1.0", features = ["derive"] } twox-hash = "2.1.0" +sketchlib-rust = { git = "https://github.com/ProjectASAP/sketchlib-rust" } */ + use arroyo_udf_plugin::udf; use rmp_serde::Serializer; use serde::{Deserialize, Serialize}; use twox_hash::XxHash32; +use sketchlib_rust::{CountMin as SketchlibCountMin, RegularPath, SketchInput, Vector2D}; + // Count-Min Sketch parameters const DEPTH: usize = {{ depth }}; // Number of hash functions const WIDTH: usize = {{ width }}; // Number of buckets per hash function +// Implementation mode for Count-Min Sketch. Set at compile time; no env vars. +enum ImplMode { + Legacy, + Sketchlib, +} + +{% set _impl_mode = impl_mode | default("Sketchlib") %} +const IMPL_MODE: ImplMode = ImplMode::{% if _impl_mode == "Legacy" or _impl_mode == "Sketchlib" %}{{ _impl_mode }}{% else %}Sketchlib{% endif %}; + +fn use_sketchlib_for_cms() -> bool { + matches!(IMPL_MODE, ImplMode::Sketchlib) +} + +type SketchlibCms = SketchlibCountMin, RegularPath>; + #[derive(Serialize, Deserialize, Clone)] struct CountMinSketch { sketch: Vec>, @@ -29,7 +48,7 @@ impl CountMinSketch { } } - // Update the sketch with a key-value pair + // Legacy path: update the sketch with a key-value pair using twox-hash. fn update(&mut self, key: &str, value: f64) { for i in 0..self.row_num { // already UTF-8 @@ -42,17 +61,53 @@ impl CountMinSketch { #[udf] fn countminsketch_count(keys: Vec<&str>, values: Vec) -> Option> { - // Create a new Count-Min Sketch - let mut countminsketch = CountMinSketch::new(); + if use_sketchlib_for_cms() { + // sketchlib-rust backed implementation: integer counters + internal hashing. + let mut inner = SketchlibCms::with_dimensions(DEPTH, WIDTH); - // Iterate through the keys and values and update the sketch for each entry - for (i, &key) in keys.iter().enumerate() { - countminsketch.update(key, 1.0); - } + for &key in keys.iter() { + let input = SketchInput::String(key.to_owned()); + inner.insert_many(&input, 1); + } + + // Convert sketchlib storage to legacy matrix wire format. + let storage: &Vector2D = inner.as_storage(); + let rows = storage.rows(); + let cols = storage.cols(); + let mut sketch = vec![vec![0.0; cols]; rows]; + + for r in 0..rows { + for c in 0..cols { + if let Some(v) = storage.get(r, c) { + sketch[r][c] = *v as f64; + } + } + } + + let countminsketch = CountMinSketch { + sketch, + row_num: rows, + col_num: cols, + }; - let mut buf = Vec::new(); - countminsketch - .serialize(&mut Serializer::new(&mut buf)) - .ok()?; - Some(buf) + let mut buf = Vec::new(); + countminsketch + .serialize(&mut Serializer::new(&mut buf)) + .ok()?; + Some(buf) + } else { + // Legacy twox-hash backed implementation (unchanged). + let mut countminsketch = CountMinSketch::new(); + + // Iterate through the keys and update the sketch for each entry + for &key in keys.iter() { + countminsketch.update(key, 1.0); + } + + let mut buf = Vec::new(); + countminsketch + .serialize(&mut Serializer::new(&mut buf)) + .ok()?; + Some(buf) + } } diff --git a/asap-summary-ingest/templates/udfs/countminsketch_sum.rs.j2 b/asap-summary-ingest/templates/udfs/countminsketch_sum.rs.j2 index 8bf0530..0c83694 100644 --- a/asap-summary-ingest/templates/udfs/countminsketch_sum.rs.j2 +++ b/asap-summary-ingest/templates/udfs/countminsketch_sum.rs.j2 @@ -3,16 +3,35 @@ rmp-serde = "1.1" serde = { version = "1.0", features = ["derive"] } twox-hash = "2.1.0" +sketchlib-rust = { git = "https://github.com/ProjectASAP/sketchlib-rust" } */ + use arroyo_udf_plugin::udf; use rmp_serde::Serializer; use serde::{Deserialize, Serialize}; use twox_hash::XxHash32; +use sketchlib_rust::{CountMin as SketchlibCountMin, RegularPath, SketchInput, Vector2D}; + // Count-Min Sketch parameters const DEPTH: usize = {{ depth }}; // Number of hash functions const WIDTH: usize = {{ width }}; // Number of buckets per hash function +// Implementation mode for Count-Min Sketch. Set at compile time; no env vars. +enum ImplMode { + Legacy, + Sketchlib, +} + +{% set _impl_mode = impl_mode | default("Sketchlib") %} +const IMPL_MODE: ImplMode = ImplMode::{% if _impl_mode == "Legacy" or _impl_mode == "Sketchlib" %}{{ _impl_mode }}{% else %}Sketchlib{% endif %}; + +fn use_sketchlib_for_cms() -> bool { + matches!(IMPL_MODE, ImplMode::Sketchlib) +} + +type SketchlibCms = SketchlibCountMin, RegularPath>; + #[derive(Serialize, Deserialize, Clone)] struct CountMinSketch { sketch: Vec>, @@ -29,7 +48,7 @@ impl CountMinSketch { } } - // Update the sketch with a key-value pair + // Legacy path: update the sketch with a key-value pair using twox-hash. fn update(&mut self, key: &str, value: f64) { for i in 0..self.row_num { // already UTF-8 @@ -47,17 +66,59 @@ fn countminsketch_sum(keys: Vec<&str>, values: Vec) -> Option> { return None; } - // Create a new Count-Min Sketch - let mut countminsketch = CountMinSketch::new(); + if use_sketchlib_for_cms() { + // sketchlib-rust backed implementation: integer counters + internal hashing. + let mut inner = SketchlibCms::with_dimensions(DEPTH, WIDTH); - // Iterate through the keys and values and update the sketch for each entry - for (i, &key) in keys.iter().enumerate() { - countminsketch.update(key, values[i]); - } + for (i, &key) in keys.iter().enumerate() { + let value = values[i]; + // Values arrive as f64; Count-Min counters are integers. + let many = value.round() as i64; + if many <= 0 { + continue; + } + let input = SketchInput::String(key.to_owned()); + inner.insert_many(&input, many); + } + + // Convert sketchlib storage to legacy matrix wire format. + let storage: &Vector2D = inner.as_storage(); + let rows = storage.rows(); + let cols = storage.cols(); + let mut sketch = vec![vec![0.0; cols]; rows]; + + for r in 0..rows { + for c in 0..cols { + if let Some(v) = storage.get(r, c) { + sketch[r][c] = *v as f64; + } + } + } + + let countminsketch = CountMinSketch { + sketch, + row_num: rows, + col_num: cols, + }; - let mut buf = Vec::new(); - countminsketch - .serialize(&mut Serializer::new(&mut buf)) - .ok()?; - Some(buf) + let mut buf = Vec::new(); + countminsketch + .serialize(&mut Serializer::new(&mut buf)) + .ok()?; + Some(buf) + } else { + // Legacy twox-hash backed implementation (unchanged). + let mut countminsketch = CountMinSketch::new(); + + // Iterate through the keys and values and update the sketch for each entry + for (i, &key) in keys.iter().enumerate() { + countminsketch.update(key, values[i]); + } + + let mut buf = Vec::new(); + countminsketch + .serialize(&mut Serializer::new(&mut buf)) + .ok()?; + Some(buf) + } } diff --git a/asap-tools/experiments/experiment_utils/services/arroyo.py b/asap-tools/experiments/experiment_utils/services/arroyo.py index e329a80..de58dc4 100644 --- a/asap-tools/experiments/experiment_utils/services/arroyo.py +++ b/asap-tools/experiments/experiment_utils/services/arroyo.py @@ -105,6 +105,9 @@ def run_arroyosketch( use_kafka_ingest: bool = False, enable_optimized_remote_write: bool = False, avoid_long_ssh: bool = False, + sketch_cms_impl: str = "sketchlib", + sketch_kll_impl: str = "legacy", + sketch_cmwh_impl: str = "legacy", ) -> str: """ Run ArroyoSketch pipeline. @@ -122,6 +125,9 @@ def run_arroyosketch( parallelism: Pipeline parallelism enable_optimized_remote_write: If True, use optimized Prometheus remote_write source (10-20x faster) avoid_long_ssh: If True, run command in background to avoid long SSH connections + sketch_cms_impl: Count-Min Sketch backend (legacy|sketchlib). Must match QueryEngine. + sketch_kll_impl: KLL Sketch backend (legacy|sketchlib). Must match QueryEngine. + sketch_cmwh_impl: Count-Min-With-Heap backend (legacy|sketchlib). Must match QueryEngine. Returns: Pipeline ID @@ -134,7 +140,7 @@ def run_arroyosketch( ) if use_kafka_ingest: - cmd = "python run_arroyosketch.py --source_type kafka --kafka_input_format {} --output_format {} --pipeline_name {} --config_file_path {}/streaming_config.yaml --input_kafka_topic {} --output_kafka_topic {} --output_dir {}".format( + cmd = "python run_arroyosketch.py --source_type kafka --kafka_input_format {} --output_format {} --pipeline_name {} --config_file_path {}/streaming_config.yaml --input_kafka_topic {} --output_kafka_topic {} --output_dir {} --sketch_cms_impl {} --sketch_kll_impl {} --sketch_cmwh_impl {}".format( flink_input_format, flink_output_format, experiment_name, @@ -142,6 +148,9 @@ def run_arroyosketch( constants.FLINK_INPUT_TOPIC, constants.FLINK_OUTPUT_TOPIC, arroyosketch_output_dir, + sketch_cms_impl, + sketch_kll_impl, + sketch_cmwh_impl, ) else: # Build base command for Prometheus remote write @@ -159,6 +168,12 @@ def run_arroyosketch( # Add optimized source flag if enabled if enable_optimized_remote_write: cmd += " --prometheus_remote_write_source optimized" + # Sketch impl mode - must match QueryEngine + cmd += ( + " --sketch_cms_impl {} --sketch_kll_impl {} --sketch_cmwh_impl {}".format( + sketch_cms_impl, sketch_kll_impl, sketch_cmwh_impl + ) + ) cmd_dir = os.path.join( constants.CLOUDLAB_HOME_DIR, "code", "asap-summary-ingest" )