From fef57234e67172baa05c93c41fbe62a0978440cf Mon Sep 17 00:00:00 2001 From: zz_y Date: Wed, 7 Oct 2026 20:36:34 +0000 Subject: [PATCH 1/3] deps: asap_sketchlib 0.3.0 (capacity-independent top-k heap) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit asap_sketchlib 0.2.2's HHHeap rebuilt its key index after every accepted update, so CMSHeap/CSHeap inserts cost O(k) in the heap capacity; 0.3.0 (asap_sketchlib#107) patches the index through each sift. With #182 sizing top-k heaps to m·k, the 0.2.2 cost grew with every merged window. - Pin asap_sketchlib 0.3.0 (aqpbm-planeval already used it). - Hydra: 0.3.0 fixes a grid's key columns at construction (with_schema) and queries positionally. hydra_shared's new_hydra/update/query/merge set the schema from the first record (one column per ';'-joined label), constrain the probe's leading label columns (the scored subpopulations group by column 0) and skip shards that saw no record. A probe now matches its column only, not an equal value in another label column. - DDSketch::merge now returns a Result; the wrappers expect it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- Cargo.lock | 32 +---------- Cargo.toml | 2 +- sketch-bench/src/wrappers/dd/sketchlib.rs | 13 ++++- sketch-bench/src/wrappers/hydra_cms/mod.rs | 16 +++--- .../src/wrappers/hydra_cms/sketchlib.rs | 30 +++++----- sketch-bench/src/wrappers/hydra_cs/mod.rs | 16 +++--- .../src/wrappers/hydra_cs/sketchlib.rs | 30 +++++----- sketch-bench/src/wrappers/hydra_hll/mod.rs | 16 +++--- .../src/wrappers/hydra_hll/sketchlib.rs | 24 +++----- sketch-bench/src/wrappers/hydra_kll/mod.rs | 12 ++-- .../src/wrappers/hydra_kll/sketchlib.rs | 24 +++----- sketch-bench/src/wrappers/hydra_shared.rs | 56 ++++++++++++++++++- .../src/wrappers/hydra_univmon/mod.rs | 16 +++--- .../src/wrappers/hydra_univmon/sketchlib.rs | 30 ++++------ 14 files changed, 166 insertions(+), 151 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 04654326..8c52dbca 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -233,23 +233,6 @@ dependencies = [ "thiserror", ] -[[package]] -name = "asap_sketchlib" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d71e22a03cabb3fbbde6078a6ce493d4c21d007b895ad1d32ae986cfa7b1ac65" -dependencies = [ - "bytes", - "prost", - "rand 0.9.4", - "rmp-serde", - "serde", - "serde-big-array", - "smallvec", - "twox-hash", - "xxhash-rust", -] - [[package]] name = "asap_sketchlib" version = "0.3.0" @@ -369,7 +352,7 @@ dependencies = [ "bitflags", "cexpr", "clang-sys", - "itertools 0.13.0", + "itertools", "log", "prettyplease", "proc-macro2", @@ -1153,15 +1136,6 @@ dependencies = [ "either", ] -[[package]] -name = "itertools" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" -dependencies = [ - "either", -] - [[package]] name = "itoa" version = "1.0.18" @@ -2073,7 +2047,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a56d757972c98b346a9b766e3f02746cde6dd1cd1d1d563472929fdd74bec4d" dependencies = [ "anyhow", - "itertools 0.14.0", + "itertools", "proc-macro2", "quote", "syn 2.0.117", @@ -2523,7 +2497,7 @@ name = "sketch-bench" version = "0.1.0" dependencies = [ "aqpbm-core", - "asap_sketchlib 0.2.2", + "asap_sketchlib 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", "datasketches", "polars", "serde", diff --git a/Cargo.toml b/Cargo.toml index 0c2ddc77..949c9204 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -55,7 +55,7 @@ bitflags = "2" polars = { version = "0.46", features = ["lazy", "ipc", "ipc_streaming"] } sketch_oxide = "0.1.6" datasketches = "0.2.0" -asap_sketchlib = { version = "0.2.2", features = ["experimental"] } +asap_sketchlib = { version = "0.3.0", features = ["experimental"] } # Internal workspace crates. aqpbm-datagen = { path = "aqpbm-datagen" } diff --git a/sketch-bench/src/wrappers/dd/sketchlib.rs b/sketch-bench/src/wrappers/dd/sketchlib.rs index cdc9c845..5dc7f6bb 100644 --- a/sketch-bench/src/wrappers/dd/sketchlib.rs +++ b/sketch-bench/src/wrappers/dd/sketchlib.rs @@ -113,7 +113,10 @@ where // Built, fed and folded here: the closure below asks, and only asks. let (mut sketch, rest) = dd_lib_shards(params, &items, shards)?; for other in rest.iter() { - sketch.inner.merge(&other.inner); + sketch + .inner + .merge(&other.inner) + .expect("both operands built from one ParamSet, so alpha matches"); } let probes = probes.clone(); out.push(Box::new(move || { @@ -142,7 +145,9 @@ where let (mut acc, rest) = dd_lib_shards(params, &items, shards)?; out.push(Box::new(move || { for other in rest.iter() { - acc.inner.merge(&other.inner); + acc.inner + .merge(&other.inner) + .expect("both operands built from one ParamSet, so alpha matches"); } memory_dd_lib::(&acc) }) as Pass); @@ -168,7 +173,9 @@ where steps: rest.len(), step: Box::new(move |i| { let acc = &mut *driven.borrow_mut(); - acc.inner.merge(&rest[i].inner); + acc.inner + .merge(&rest[i].inner) + .expect("both operands built from one ParamSet, so alpha matches"); }), footprint: Box::new(move || memory_dd_lib::(&read.borrow())), }); diff --git a/sketch-bench/src/wrappers/hydra_cms/mod.rs b/sketch-bench/src/wrappers/hydra_cms/mod.rs index 0c6fb140..870176a1 100644 --- a/sketch-bench/src/wrappers/hydra_cms/mod.rs +++ b/sketch-bench/src/wrappers/hydra_cms/mod.rs @@ -7,7 +7,9 @@ use crate::params::*; pub mod polars; pub mod sketchlib; -pub(crate) use super::hydra_shared::{check_grid, grid_overhead_bytes, labels}; +pub(crate) use super::hydra_shared::{ + check_grid, grid_overhead_bytes, labels, merge, new_hydra, query, update, +}; #[cfg(test)] mod tests { @@ -32,9 +34,11 @@ mod tests { } fn fed(sketch: &mut HydraCms, r: &(String, i64)) { - sketch - .inner - .update(&r.0, &asap_sketchlib::DataInput::I64(r.1), None); + update( + &mut sketch.inner, + &r.0, + &asap_sketchlib::DataInput::I64(r.1), + ); } /// The statistic is the frequency of a value *within* a subpopulation, and @@ -80,9 +84,7 @@ mod tests { for _ in 0..4 { fed(&mut right, &record("a;x", 10)); } - left.inner - .merge(&right.inner) - .expect("both operands built from one ParamSet, so shapes match"); + merge(&mut left.inner, &right.inner); assert_eq!(left.estimate_subpop_frequency(&["a"], &10i64), 7.0); } diff --git a/sketch-bench/src/wrappers/hydra_cms/sketchlib.rs b/sketch-bench/src/wrappers/hydra_cms/sketchlib.rs index 36e7053f..fa8beee5 100644 --- a/sketch-bench/src/wrappers/hydra_cms/sketchlib.rs +++ b/sketch-bench/src/wrappers/hydra_cms/sketchlib.rs @@ -8,7 +8,7 @@ use crate::params::ParamSet; use crate::wrappers::frequency_value::FrequencyValue; use crate::wrappers::partition; use crate::wrappers::{BuildError, Pass, QueryPass, Shared, StepPass}; -use asap_sketchlib::input::HydraCounter; +use asap_sketchlib::input::{HydraCounter, HydraQuery}; use asap_sketchlib::{CountMin, FastPath, Hydra, Vector2D}; use std::cell::RefCell; use std::rc::Rc; @@ -31,7 +31,7 @@ pub fn build_hydra_cms(config: &ParamSet) -> Result { p.cell_cols, )); Ok(HydraCms { - inner: Hydra::with_dimensions(p.rows, p.cols, cell), + inner: new_hydra(p.rows, p.cols, cell), params: p, }) } @@ -39,8 +39,11 @@ pub fn build_hydra_cms(config: &ParamSet) -> Result { impl HydraCms { #[inline] pub fn estimate_subpop_frequency(&self, labels: &[&str], value: &V) -> f64 { - self.inner - .query_frequency(labels.to_vec(), &value.data_input()) + query( + &self.inner, + labels, + &HydraQuery::Frequency(value.data_input()), + ) } } @@ -64,7 +67,7 @@ pub fn insert_hydra_cms( let items = items.clone(); out.push(Box::new(move || { for v in items.iter() { - sketch.inner.update(&v.0, &v.1.data_input(), None); + update(&mut sketch.inner, &v.0, &v.1.data_input()); } memory_hydra_cms(&sketch) }) as Pass); @@ -87,7 +90,7 @@ pub fn insert_step_hydra_cms( step: Box::new(move |i| { let sketch = &mut *driven.borrow_mut(); let v = &stream[i]; - sketch.inner.update(&v.0, &v.1.data_input(), None); + update(&mut sketch.inner, &v.0, &v.1.data_input()); }), footprint: Box::new(move || memory_hydra_cms(&read.borrow())), }); @@ -118,10 +121,7 @@ pub fn merge_query_hydra_cms( // Built, fed and folded here: the closure below asks, and only asks. let (mut sketch, rest) = hydra_cms_shards(params, &items, shards)?; for other in rest.iter() { - sketch - .inner - .merge(&other.inner) - .expect("both operands built from one ParamSet, so grid and cell shapes match"); + merge(&mut sketch.inner, &other.inner); } let probes = probes.clone(); out.push(Box::new(move || { @@ -147,9 +147,7 @@ pub fn merge_hydra_cms( let (mut acc, rest) = hydra_cms_shards(params, &items, shards)?; out.push(Box::new(move || { for other in rest.iter() { - acc.inner - .merge(&other.inner) - .expect("both operands built from one ParamSet, so grid and cell shapes match"); + merge(&mut acc.inner, &other.inner); } memory_hydra_cms(&acc) }) as Pass); @@ -173,9 +171,7 @@ pub fn merge_step_hydra_cms( step: Box::new(move |i| { let acc = &mut *driven.borrow_mut(); let other = &rest[i]; - acc.inner - .merge(&other.inner) - .expect("both operands built from one ParamSet, so grid and cell shapes match"); + merge(&mut acc.inner, &other.inner); }), footprint: Box::new(move || memory_hydra_cms(&read.borrow())), }); @@ -195,7 +191,7 @@ fn hydra_cms_shards( for shard in partition(items, shards) { let mut sketch = build_hydra_cms(params)?; for v in shard { - sketch.inner.update(&v.0, &v.1.data_input(), None); + update(&mut sketch.inner, &v.0, &v.1.data_input()); } parts.push(sketch); } diff --git a/sketch-bench/src/wrappers/hydra_cs/mod.rs b/sketch-bench/src/wrappers/hydra_cs/mod.rs index a5cd5b8c..ba6c2b5f 100644 --- a/sketch-bench/src/wrappers/hydra_cs/mod.rs +++ b/sketch-bench/src/wrappers/hydra_cs/mod.rs @@ -7,7 +7,9 @@ use crate::params::*; pub mod polars; pub mod sketchlib; -pub(crate) use super::hydra_shared::{check_grid, grid_overhead_bytes, labels}; +pub(crate) use super::hydra_shared::{ + check_grid, grid_overhead_bytes, labels, merge, new_hydra, query, update, +}; #[cfg(test)] mod tests { @@ -32,9 +34,11 @@ mod tests { } fn fed(sketch: &mut HydraCs, r: &(String, i64)) { - sketch - .inner - .update(&r.0, &asap_sketchlib::DataInput::I64(r.1), None); + update( + &mut sketch.inner, + &r.0, + &asap_sketchlib::DataInput::I64(r.1), + ); } /// The statistic is the frequency of a value *within* a subpopulation, and @@ -80,9 +84,7 @@ mod tests { for _ in 0..4 { fed(&mut right, &record("a;x", 10)); } - left.inner - .merge(&right.inner) - .expect("both operands built from one ParamSet, so shapes match"); + merge(&mut left.inner, &right.inner); assert_eq!(left.estimate_subpop_frequency(&["a"], &10i64), 7.0); } diff --git a/sketch-bench/src/wrappers/hydra_cs/sketchlib.rs b/sketch-bench/src/wrappers/hydra_cs/sketchlib.rs index dcad1eb8..7108f819 100644 --- a/sketch-bench/src/wrappers/hydra_cs/sketchlib.rs +++ b/sketch-bench/src/wrappers/hydra_cs/sketchlib.rs @@ -8,7 +8,7 @@ use crate::params::ParamSet; use crate::wrappers::frequency_value::FrequencyValue; use crate::wrappers::partition; use crate::wrappers::{BuildError, Pass, QueryPass, Shared, StepPass}; -use asap_sketchlib::input::HydraCounter; +use asap_sketchlib::input::{HydraCounter, HydraQuery}; use asap_sketchlib::{Count, FastPath, Hydra, Vector2D}; use std::cell::RefCell; use std::rc::Rc; @@ -31,7 +31,7 @@ pub fn build_hydra_cs(config: &ParamSet) -> Result { p.cell_cols, )); Ok(HydraCs { - inner: Hydra::with_dimensions(p.rows, p.cols, cell), + inner: new_hydra(p.rows, p.cols, cell), params: p, }) } @@ -39,8 +39,11 @@ pub fn build_hydra_cs(config: &ParamSet) -> Result { impl HydraCs { #[inline] pub fn estimate_subpop_frequency(&self, labels: &[&str], value: &V) -> f64 { - self.inner - .query_frequency(labels.to_vec(), &value.data_input()) + query( + &self.inner, + labels, + &HydraQuery::Frequency(value.data_input()), + ) } } @@ -64,7 +67,7 @@ pub fn insert_hydra_cs( let items = items.clone(); out.push(Box::new(move || { for v in items.iter() { - sketch.inner.update(&v.0, &v.1.data_input(), None); + update(&mut sketch.inner, &v.0, &v.1.data_input()); } memory_hydra_cs(&sketch) }) as Pass); @@ -87,7 +90,7 @@ pub fn insert_step_hydra_cs( step: Box::new(move |i| { let sketch = &mut *driven.borrow_mut(); let v = &stream[i]; - sketch.inner.update(&v.0, &v.1.data_input(), None); + update(&mut sketch.inner, &v.0, &v.1.data_input()); }), footprint: Box::new(move || memory_hydra_cs(&read.borrow())), }); @@ -118,10 +121,7 @@ pub fn merge_query_hydra_cs( // Built, fed and folded here: the closure below asks, and only asks. let (mut sketch, rest) = hydra_cs_shards(params, &items, shards)?; for other in rest.iter() { - sketch - .inner - .merge(&other.inner) - .expect("both operands built from one ParamSet, so grid and cell shapes match"); + merge(&mut sketch.inner, &other.inner); } let probes = probes.clone(); out.push(Box::new(move || { @@ -147,9 +147,7 @@ pub fn merge_hydra_cs( let (mut acc, rest) = hydra_cs_shards(params, &items, shards)?; out.push(Box::new(move || { for other in rest.iter() { - acc.inner - .merge(&other.inner) - .expect("both operands built from one ParamSet, so grid and cell shapes match"); + merge(&mut acc.inner, &other.inner); } memory_hydra_cs(&acc) }) as Pass); @@ -173,9 +171,7 @@ pub fn merge_step_hydra_cs( step: Box::new(move |i| { let acc = &mut *driven.borrow_mut(); let other = &rest[i]; - acc.inner - .merge(&other.inner) - .expect("both operands built from one ParamSet, so grid and cell shapes match"); + merge(&mut acc.inner, &other.inner); }), footprint: Box::new(move || memory_hydra_cs(&read.borrow())), }); @@ -195,7 +191,7 @@ fn hydra_cs_shards( for shard in partition(items, shards) { let mut sketch = build_hydra_cs(params)?; for v in shard { - sketch.inner.update(&v.0, &v.1.data_input(), None); + update(&mut sketch.inner, &v.0, &v.1.data_input()); } parts.push(sketch); } diff --git a/sketch-bench/src/wrappers/hydra_hll/mod.rs b/sketch-bench/src/wrappers/hydra_hll/mod.rs index c9ff2da2..a76d28b8 100644 --- a/sketch-bench/src/wrappers/hydra_hll/mod.rs +++ b/sketch-bench/src/wrappers/hydra_hll/mod.rs @@ -7,7 +7,9 @@ use crate::params::*; pub mod polars; pub mod sketchlib; -pub(crate) use super::hydra_shared::{check_grid, grid_overhead_bytes, labels}; +pub(crate) use super::hydra_shared::{ + check_grid, grid_overhead_bytes, labels, merge, new_hydra, query, update, +}; /// Registers in one `HyperLogLog` cell. The library fixes the cell at /// `HyperLogLogP14`, so this is `2^14` and not a parameter. Named here because @@ -32,9 +34,11 @@ mod tests { } fn fed_hll(sketch: &mut HydraHll, r: &(String, i64)) { - sketch - .inner - .update(&r.0, &asap_sketchlib::DataInput::I64(r.1), None); + update( + &mut sketch.inner, + &r.0, + &asap_sketchlib::DataInput::I64(r.1), + ); } #[test] @@ -76,9 +80,7 @@ mod tests { fed_hll(&mut left, &record("a;x", 20)); fed_hll(&mut right, &record("a;x", 20)); fed_hll(&mut right, &record("a;x", 30)); - left.inner - .merge(&right.inner) - .expect("both operands built from one ParamSet, so shapes match"); + merge(&mut left.inner, &right.inner); let est = left.estimate_subpop_cardinality(&["a"]); assert!( (est - 3.0).abs() < 0.5, diff --git a/sketch-bench/src/wrappers/hydra_hll/sketchlib.rs b/sketch-bench/src/wrappers/hydra_hll/sketchlib.rs index 80afbba4..b70bbc03 100644 --- a/sketch-bench/src/wrappers/hydra_hll/sketchlib.rs +++ b/sketch-bench/src/wrappers/hydra_hll/sketchlib.rs @@ -27,7 +27,7 @@ pub fn build_hydra_hll(config: &ParamSet) -> Result { // estimators the alias can carry. The enum fixes this one. let cell = HydraCounter::HLL(HyperLogLog::::new()); Ok(HydraHll { - inner: Hydra::with_dimensions(p.rows, p.cols, cell), + inner: new_hydra(p.rows, p.cols, cell), params: p, }) } @@ -35,8 +35,7 @@ pub fn build_hydra_hll(config: &ParamSet) -> Result { impl HydraHll { #[inline] pub fn estimate_subpop_cardinality(&self, labels: &[&str]) -> f64 { - self.inner - .query_key(labels.to_vec(), &HydraQuery::Cardinality) + query(&self.inner, labels, &HydraQuery::Cardinality) } } @@ -59,7 +58,7 @@ pub fn insert_hydra_hll( let items = items.clone(); out.push(Box::new(move || { for v in items.iter() { - sketch.inner.update(&v.0, &v.1.data_input(), None); + update(&mut sketch.inner, &v.0, &v.1.data_input()); } memory_hydra_hll(&sketch) }) as Pass); @@ -82,7 +81,7 @@ pub fn insert_step_hydra_hll( step: Box::new(move |i| { let sketch = &mut *driven.borrow_mut(); let v = &stream[i]; - sketch.inner.update(&v.0, &v.1.data_input(), None); + update(&mut sketch.inner, &v.0, &v.1.data_input()); }), footprint: Box::new(move || memory_hydra_hll(&read.borrow())), }); @@ -113,10 +112,7 @@ pub fn merge_query_hydra_hll( // Built, fed and folded here: the closure below asks, and only asks. let (mut sketch, rest) = hydra_hll_shards(params, &items, shards)?; for other in rest.iter() { - sketch - .inner - .merge(&other.inner) - .expect("both operands built from one ParamSet, so grid and cell shapes match"); + merge(&mut sketch.inner, &other.inner); } let probes = probes.clone(); out.push(Box::new(move || { @@ -142,9 +138,7 @@ pub fn merge_hydra_hll( let (mut acc, rest) = hydra_hll_shards(params, &items, shards)?; out.push(Box::new(move || { for other in rest.iter() { - acc.inner - .merge(&other.inner) - .expect("both operands built from one ParamSet, so grid and cell shapes match"); + merge(&mut acc.inner, &other.inner); } memory_hydra_hll(&acc) }) as Pass); @@ -168,9 +162,7 @@ pub fn merge_step_hydra_hll( step: Box::new(move |i| { let acc = &mut *driven.borrow_mut(); let other = &rest[i]; - acc.inner - .merge(&other.inner) - .expect("both operands built from one ParamSet, so grid and cell shapes match"); + merge(&mut acc.inner, &other.inner); }), footprint: Box::new(move || memory_hydra_hll(&read.borrow())), }); @@ -190,7 +182,7 @@ fn hydra_hll_shards( for shard in partition(items, shards) { let mut sketch = build_hydra_hll(params)?; for v in shard { - sketch.inner.update(&v.0, &v.1.data_input(), None); + update(&mut sketch.inner, &v.0, &v.1.data_input()); } parts.push(sketch); } diff --git a/sketch-bench/src/wrappers/hydra_kll/mod.rs b/sketch-bench/src/wrappers/hydra_kll/mod.rs index 6767a807..46b919b7 100644 --- a/sketch-bench/src/wrappers/hydra_kll/mod.rs +++ b/sketch-bench/src/wrappers/hydra_kll/mod.rs @@ -7,7 +7,9 @@ use crate::params::*; pub mod polars; pub mod sketchlib; -pub(crate) use super::hydra_shared::{check_grid, grid_overhead_bytes, labels}; +pub(crate) use super::hydra_shared::{ + check_grid, grid_overhead_bytes, labels, merge, new_hydra, query, update, +}; // Level count and decay of an `asap_sketchlib::KLL`. Both are private constants // in the library, reproduced here because a cell's footprint is a function of @@ -64,9 +66,11 @@ mod tests { } fn fed_kll(sketch: &mut HydraKll, r: &(String, f64)) { - sketch - .inner - .update(&r.0, &asap_sketchlib::DataInput::F64(r.1), None); + update( + &mut sketch.inner, + &r.0, + &asap_sketchlib::DataInput::F64(r.1), + ); } #[test] diff --git a/sketch-bench/src/wrappers/hydra_kll/sketchlib.rs b/sketch-bench/src/wrappers/hydra_kll/sketchlib.rs index beb72ed1..159baa90 100644 --- a/sketch-bench/src/wrappers/hydra_kll/sketchlib.rs +++ b/sketch-bench/src/wrappers/hydra_kll/sketchlib.rs @@ -35,7 +35,7 @@ pub fn build_hydra_kll(config: &ParamSet) -> Result { } let cell = HydraCounter::KLL(KLL::init_kll(p.cell_k as i32)); Ok(HydraKll { - inner: Hydra::with_dimensions(p.rows, p.cols, cell), + inner: new_hydra(p.rows, p.cols, cell), params: p, }) } @@ -46,8 +46,7 @@ impl HydraKll { /// answers the inverse question. #[inline] pub fn estimate_subpop_quantile(&self, labels: &[&str], phi: f64) -> f64 { - self.inner - .query_key(labels.to_vec(), &HydraQuery::Quantile(phi)) + query(&self.inner, labels, &HydraQuery::Quantile(phi)) } } @@ -73,7 +72,7 @@ pub fn insert_hydra_kll( let items = items.clone(); out.push(Box::new(move || { for v in items.iter() { - sketch.inner.update(&v.0, &v.1.data_input(), None); + update(&mut sketch.inner, &v.0, &v.1.data_input()); } memory_hydra_kll(&sketch) }) as Pass); @@ -96,7 +95,7 @@ pub fn insert_step_hydra_kll( step: Box::new(move |i| { let sketch = &mut *driven.borrow_mut(); let v = &stream[i]; - sketch.inner.update(&v.0, &v.1.data_input(), None); + update(&mut sketch.inner, &v.0, &v.1.data_input()); }), footprint: Box::new(move || memory_hydra_kll(&read.borrow())), }); @@ -127,10 +126,7 @@ pub fn merge_query_hydra_kll( // Built, fed and folded here: the closure below asks, and only asks. let (mut sketch, rest) = hydra_kll_shards(params, &items, shards)?; for other in rest.iter() { - sketch - .inner - .merge(&other.inner) - .expect("both operands built from one ParamSet, so grid and cell shapes match"); + merge(&mut sketch.inner, &other.inner); } let probes = probes.clone(); out.push(Box::new(move || { @@ -156,9 +152,7 @@ pub fn merge_hydra_kll( let (mut acc, rest) = hydra_kll_shards(params, &items, shards)?; out.push(Box::new(move || { for other in rest.iter() { - acc.inner - .merge(&other.inner) - .expect("both operands built from one ParamSet, so grid and cell shapes match"); + merge(&mut acc.inner, &other.inner); } memory_hydra_kll(&acc) }) as Pass); @@ -182,9 +176,7 @@ pub fn merge_step_hydra_kll( step: Box::new(move |i| { let acc = &mut *driven.borrow_mut(); let other = &rest[i]; - acc.inner - .merge(&other.inner) - .expect("both operands built from one ParamSet, so grid and cell shapes match"); + merge(&mut acc.inner, &other.inner); }), footprint: Box::new(move || memory_hydra_kll(&read.borrow())), }); @@ -204,7 +196,7 @@ fn hydra_kll_shards( for shard in partition(items, shards) { let mut sketch = build_hydra_kll(params)?; for v in shard { - sketch.inner.update(&v.0, &v.1.data_input(), None); + update(&mut sketch.inner, &v.0, &v.1.data_input()); } parts.push(sketch); } diff --git a/sketch-bench/src/wrappers/hydra_shared.rs b/sketch-bench/src/wrappers/hydra_shared.rs index 1e2a4cba..aa47d265 100644 --- a/sketch-bench/src/wrappers/hydra_shared.rs +++ b/sketch-bench/src/wrappers/hydra_shared.rs @@ -3,12 +3,66 @@ //! `d` labels cost `2^d - 1` cells and throughput is records per second. use crate::wrappers::BuildError; -use asap_sketchlib::input::HydraCounter; +use asap_sketchlib::input::{HydraCounter, HydraQuery}; +use asap_sketchlib::{DataInput, Hydra}; pub(crate) fn labels(group: &[String]) -> Vec<&str> { group.iter().map(String::as_str).collect() } +/// The schema a grid holds until its first record names the label columns: +/// asap_sketchlib 0.3 fixes a Hydra's key columns at construction, and the +/// wrappers learn them from the stream. +const UNSET: &str = "__label_columns_unset__"; + +/// A grid whose key columns the first [`update`] sets. +pub(crate) fn new_hydra(rows: usize, cols: usize, cell: HydraCounter) -> Hydra { + Hydra::with_schema(rows, cols, [UNSET], cell).expect("one label column is a valid schema") +} + +fn unset(h: &Hydra) -> bool { + h.schema() == [UNSET] +} + +/// Records one `;`-joined record: one label value per column, positionally. +pub(crate) fn update(h: &mut Hydra, key: &str, value: &DataInput) { + let parts: Vec<&str> = key.split(';').filter(|s| !s.is_empty()).collect(); + if unset(h) { + let schema = (0..parts.len()).map(|i| format!("label{i}")); + *h = Hydra::with_schema(h.row_num, h.col_num, schema, h.type_to_clone.clone()) + .expect("a record names at least one label"); + } + h.update(&parts, value, None) + .expect("every record carries one value per label column"); +} + +/// Asks `query` of the subpopulation `group` constrains: its values are the +/// leading label columns' (the scored subpopulations group by column 0), the +/// rest unconstrained. An empty grid answers 0. +pub(crate) fn query(h: &Hydra, group: &[&str], query: &HydraQuery) -> f64 { + if unset(h) { + return 0.0; + } + let mut key: Vec> = group.iter().map(|v| Some(*v)).collect(); + key.resize(h.schema().len(), None); + h.query_key(&key, query) + .expect("a probe constrains the leading label columns") +} + +/// Folds `other` into `acc`; a shard that saw no record (still unset) adds +/// nothing. +pub(crate) fn merge(acc: &mut Hydra, other: &Hydra) { + if unset(other) { + return; + } + if unset(acc) { + *acc = other.clone(); + return; + } + acc.merge(other) + .expect("both operands built from one ParamSet, so grid and cell shapes match"); +} + /// outer grid is the one shape they have in common. pub(crate) fn check_grid(rows: usize, cols: usize, algorithm: &str) -> Result<(), BuildError> { for (name, v) in [("rows", rows), ("cols", cols)] { diff --git a/sketch-bench/src/wrappers/hydra_univmon/mod.rs b/sketch-bench/src/wrappers/hydra_univmon/mod.rs index ef649176..db63a39b 100644 --- a/sketch-bench/src/wrappers/hydra_univmon/mod.rs +++ b/sketch-bench/src/wrappers/hydra_univmon/mod.rs @@ -7,7 +7,9 @@ use crate::params::*; pub mod polars; pub mod sketchlib; -pub(crate) use super::hydra_shared::{check_grid, grid_overhead_bytes, labels}; +pub(crate) use super::hydra_shared::{ + check_grid, grid_overhead_bytes, labels, merge, new_hydra, query, update, +}; #[cfg(test)] mod tests { @@ -34,9 +36,11 @@ mod tests { } fn fed(sketch: &mut HydraUnivmon, r: &(String, i64)) { - sketch - .inner - .update(&r.0, &asap_sketchlib::DataInput::I64(r.1), None); + update( + &mut sketch.inner, + &r.0, + &asap_sketchlib::DataInput::I64(r.1), + ); } #[test] @@ -105,9 +109,7 @@ mod tests { for _ in 0..4 { fed(&mut right, &record("a;x", 10)); } - left.inner - .merge(&right.inner) - .expect("both operands built from one ParamSet, so shapes match"); + merge(&mut left.inner, &right.inner); let est = left.estimate_subpop_l1_norm(&["a"]); assert!( (est - 7.0).abs() < 0.5, diff --git a/sketch-bench/src/wrappers/hydra_univmon/sketchlib.rs b/sketch-bench/src/wrappers/hydra_univmon/sketchlib.rs index 4362677b..e856ce6e 100644 --- a/sketch-bench/src/wrappers/hydra_univmon/sketchlib.rs +++ b/sketch-bench/src/wrappers/hydra_univmon/sketchlib.rs @@ -38,7 +38,7 @@ pub fn build_hydra_univmon(config: &ParamSet) -> Result Result f64 { - self.inner - .query_key(labels.to_vec(), &HydraQuery::Cardinality) + query(&self.inner, labels, &HydraQuery::Cardinality) } #[inline] pub fn estimate_subpop_l1_norm(&self, labels: &[&str]) -> f64 { - self.inner.query_key(labels.to_vec(), &HydraQuery::L1Norm) + query(&self.inner, labels, &HydraQuery::L1Norm) } #[inline] pub fn estimate_subpop_l2_norm(&self, labels: &[&str]) -> f64 { - self.inner.query_key(labels.to_vec(), &HydraQuery::L2Norm) + query(&self.inner, labels, &HydraQuery::L2Norm) } #[inline] pub fn estimate_subpop_entropy(&self, labels: &[&str]) -> f64 { - self.inner.query_key(labels.to_vec(), &HydraQuery::Entropy) + query(&self.inner, labels, &HydraQuery::Entropy) } } @@ -86,7 +85,7 @@ pub fn insert_hydra_univmon( let items = items.clone(); out.push(Box::new(move || { for v in items.iter() { - sketch.inner.update(&v.0, &v.1.data_input(), None); + update(&mut sketch.inner, &v.0, &v.1.data_input()); } memory_hydra_univmon(&sketch) }) as Pass); @@ -109,7 +108,7 @@ pub fn insert_step_hydra_univmon( step: Box::new(move |i| { let sketch = &mut *driven.borrow_mut(); let v = &stream[i]; - sketch.inner.update(&v.0, &v.1.data_input(), None); + update(&mut sketch.inner, &v.0, &v.1.data_input()); }), footprint: Box::new(move || memory_hydra_univmon(&read.borrow())), }); @@ -130,10 +129,7 @@ fn asked_hydra_univmon( // Built, fed and folded here: the closure below asks, and only asks. let (mut sketch, rest) = hydra_univmon_shards(params, &items, shards)?; for other in rest.iter() { - sketch - .inner - .merge(&other.inner) - .expect("both operands built from one ParamSet, so grid and cell shapes match"); + merge(&mut sketch.inner, &other.inner); } let probes = probes.clone(); out.push(Box::new(move || { @@ -299,9 +295,7 @@ pub fn merge_hydra_univmon( let (mut acc, rest) = hydra_univmon_shards(params, &items, shards)?; out.push(Box::new(move || { for other in rest.iter() { - acc.inner - .merge(&other.inner) - .expect("both operands built from one ParamSet, so grid and cell shapes match"); + merge(&mut acc.inner, &other.inner); } memory_hydra_univmon(&acc) }) as Pass); @@ -325,9 +319,7 @@ pub fn merge_step_hydra_univmon( step: Box::new(move |i| { let acc = &mut *driven.borrow_mut(); let other = &rest[i]; - acc.inner - .merge(&other.inner) - .expect("both operands built from one ParamSet, so grid and cell shapes match"); + merge(&mut acc.inner, &other.inner); }), footprint: Box::new(move || memory_hydra_univmon(&read.borrow())), }); @@ -347,7 +339,7 @@ fn hydra_univmon_shards( for shard in partition(items, shards) { let mut sketch = build_hydra_univmon(params)?; for v in shard { - sketch.inner.update(&v.0, &v.1.data_input(), None); + update(&mut sketch.inner, &v.0, &v.1.data_input()); } parts.push(sketch); } From 71f13de0c239dfde93e8e87ec40a8ac06bd397dd Mon Sep 17 00:00:00 2001 From: zz_y Date: Wed, 7 Oct 2026 20:43:01 +0000 Subject: [PATCH 2/3] hydra: the label-column count fixes the schema at construction From the first review of #183: - build_hydra_* take the stream's label-column count (its first record's, label_columns) and new_hydra builds the schema once. The placeholder schema, the rebuild on the first update and the clone-on-empty merge are gone; grids built from one ParamSet and stream merge as before. - A record keeps an empty label in its own column (no dropped segments shifting the rest). A record or probe of another width is refused, naming the variant and both widths, instead of being resized. - A zero label-column count is a BuildError. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- sketch-bench/src/wrappers/hydra_cms/mod.rs | 44 +++++++--- .../src/wrappers/hydra_cms/sketchlib.rs | 34 +++++--- sketch-bench/src/wrappers/hydra_cs/mod.rs | 26 +++--- .../src/wrappers/hydra_cs/sketchlib.rs | 32 ++++--- sketch-bench/src/wrappers/hydra_hll/mod.rs | 13 +-- .../src/wrappers/hydra_hll/sketchlib.rs | 35 +++++--- sketch-bench/src/wrappers/hydra_kll/mod.rs | 20 +++-- .../src/wrappers/hydra_kll/sketchlib.rs | 35 +++++--- sketch-bench/src/wrappers/hydra_shared.rs | 83 ++++++++++--------- .../src/wrappers/hydra_univmon/mod.rs | 30 ++++--- .../src/wrappers/hydra_univmon/sketchlib.rs | 49 +++++++---- 11 files changed, 254 insertions(+), 147 deletions(-) diff --git a/sketch-bench/src/wrappers/hydra_cms/mod.rs b/sketch-bench/src/wrappers/hydra_cms/mod.rs index 870176a1..995ef25b 100644 --- a/sketch-bench/src/wrappers/hydra_cms/mod.rs +++ b/sketch-bench/src/wrappers/hydra_cms/mod.rs @@ -8,7 +8,7 @@ pub mod polars; pub mod sketchlib; pub(crate) use super::hydra_shared::{ - check_grid, grid_overhead_bytes, labels, merge, new_hydra, query, update, + check_grid, grid_overhead_bytes, label_columns, labels, new_hydra, query, update, }; #[cfg(test)] @@ -20,12 +20,15 @@ mod tests { use crate::params::SketchParams; fn built() -> HydraCms { - build_hydra_cms(&ParamSet::of(&HydraCmsParams { - rows: 3, - cols: 64, - cell_rows: 3, - cell_cols: 256, - })) + build_hydra_cms( + &ParamSet::of(&HydraCmsParams { + rows: 3, + cols: 64, + cell_rows: 3, + cell_cols: 256, + }), + 2, + ) .expect("canonical dimensions build") } @@ -38,6 +41,7 @@ mod tests { &mut sketch.inner, &r.0, &asap_sketchlib::DataInput::I64(r.1), + "hydra-cms", ); } @@ -84,10 +88,30 @@ mod tests { for _ in 0..4 { fed(&mut right, &record("a;x", 10)); } - merge(&mut left.inner, &right.inner); + left.inner + .merge(&right.inner) + .expect("both operands built from one ParamSet, so shapes match"); assert_eq!(left.estimate_subpop_frequency(&["a"], &10i64), 7.0); } + /// The grid's key columns are fixed at construction: a record of another + /// width is refused, naming the variant and both widths. + #[test] + #[should_panic(expected = "hydra-cms: record \"a;x;z\" has 3 label(s), the grid 2")] + fn a_record_of_another_width_is_refused() { + fed(&mut built(), &record("a;x;z", 10)); + } + + /// An empty label is a value in its own column: it doesn't shift the + /// labels after it. + #[test] + fn an_empty_label_keeps_its_column() { + let mut h = built(); + fed(&mut h, &record(";x", 10)); + assert_eq!(h.estimate_subpop_frequency(&[""], &10i64), 1.0); + assert_eq!(h.estimate_subpop_frequency(&["x"], &10i64), 0.0); + } + #[test] fn zero_dimensions_are_refused_by_name() { let bad = ParamSet::of(&HydraCmsParams { @@ -96,7 +120,7 @@ mod tests { cell_rows: 3, cell_cols: 256, }); - let Err(err) = build_hydra_cms(&bad) else { + let Err(err) = build_hydra_cms(&bad, 2) else { panic!("a zero dimension must be refused, not built"); }; let err = err.to_string(); @@ -117,6 +141,6 @@ mod tests { #[test] fn canonical_params_build() { - assert!(build_hydra_cms(&ParamSet::of(&HydraCmsParams::canonical())).is_ok()); + assert!(build_hydra_cms(&ParamSet::of(&HydraCmsParams::canonical()), 2).is_ok()); } } diff --git a/sketch-bench/src/wrappers/hydra_cms/sketchlib.rs b/sketch-bench/src/wrappers/hydra_cms/sketchlib.rs index fa8beee5..a9a42e29 100644 --- a/sketch-bench/src/wrappers/hydra_cms/sketchlib.rs +++ b/sketch-bench/src/wrappers/hydra_cms/sketchlib.rs @@ -18,7 +18,8 @@ pub struct HydraCms { params: HydraCmsParams, } -pub fn build_hydra_cms(config: &ParamSet) -> Result { +/// `label_columns`: the key columns every record carries. +pub fn build_hydra_cms(config: &ParamSet, label_columns: usize) -> Result { let p: HydraCmsParams = config.parse()?; check_grid(p.rows, p.cols, "hydra-cms")?; for (name, v) in [("cell_rows", p.cell_rows), ("cell_cols", p.cell_cols)] { @@ -31,7 +32,7 @@ pub fn build_hydra_cms(config: &ParamSet) -> Result { p.cell_cols, )); Ok(HydraCms { - inner: new_hydra(p.rows, p.cols, cell), + inner: new_hydra(p.rows, p.cols, label_columns, cell, "hydra-cms")?, params: p, }) } @@ -43,6 +44,7 @@ impl HydraCms { &self.inner, labels, &HydraQuery::Frequency(value.data_input()), + "hydra-cms", ) } } @@ -63,11 +65,11 @@ pub fn insert_hydra_cms( let mut out = Vec::with_capacity(passes); for _ in 0..passes { // Built here, so calling the closure is the insert and nothing else. - let mut sketch = build_hydra_cms(params)?; + let mut sketch = build_hydra_cms(params, label_columns(&items))?; let items = items.clone(); out.push(Box::new(move || { for v in items.iter() { - update(&mut sketch.inner, &v.0, &v.1.data_input()); + update(&mut sketch.inner, &v.0, &v.1.data_input(), "hydra-cms"); } memory_hydra_cms(&sketch) }) as Pass); @@ -82,7 +84,10 @@ pub fn insert_step_hydra_cms( ) -> Result, BuildError> { let mut out = Vec::with_capacity(passes); for _ in 0..passes { - let sketch: Shared<_> = Rc::new(RefCell::new(build_hydra_cms(params)?)); + let sketch: Shared<_> = Rc::new(RefCell::new(build_hydra_cms( + params, + label_columns(&items), + )?)); let (driven, read) = (sketch.clone(), sketch); let stream = items.clone(); out.push(StepPass { @@ -90,7 +95,7 @@ pub fn insert_step_hydra_cms( step: Box::new(move |i| { let sketch = &mut *driven.borrow_mut(); let v = &stream[i]; - update(&mut sketch.inner, &v.0, &v.1.data_input()); + update(&mut sketch.inner, &v.0, &v.1.data_input(), "hydra-cms"); }), footprint: Box::new(move || memory_hydra_cms(&read.borrow())), }); @@ -121,7 +126,10 @@ pub fn merge_query_hydra_cms( // Built, fed and folded here: the closure below asks, and only asks. let (mut sketch, rest) = hydra_cms_shards(params, &items, shards)?; for other in rest.iter() { - merge(&mut sketch.inner, &other.inner); + sketch + .inner + .merge(&other.inner) + .expect("both operands built from one ParamSet, so grid and cell shapes match"); } let probes = probes.clone(); out.push(Box::new(move || { @@ -147,7 +155,9 @@ pub fn merge_hydra_cms( let (mut acc, rest) = hydra_cms_shards(params, &items, shards)?; out.push(Box::new(move || { for other in rest.iter() { - merge(&mut acc.inner, &other.inner); + acc.inner + .merge(&other.inner) + .expect("both operands built from one ParamSet, so grid and cell shapes match"); } memory_hydra_cms(&acc) }) as Pass); @@ -171,7 +181,9 @@ pub fn merge_step_hydra_cms( step: Box::new(move |i| { let acc = &mut *driven.borrow_mut(); let other = &rest[i]; - merge(&mut acc.inner, &other.inner); + acc.inner + .merge(&other.inner) + .expect("both operands built from one ParamSet, so grid and cell shapes match"); }), footprint: Box::new(move || memory_hydra_cms(&read.borrow())), }); @@ -189,9 +201,9 @@ fn hydra_cms_shards( ) -> Result<(HydraCms, Vec), BuildError> { let mut parts: Vec = Vec::new(); for shard in partition(items, shards) { - let mut sketch = build_hydra_cms(params)?; + let mut sketch = build_hydra_cms(params, label_columns(items))?; for v in shard { - update(&mut sketch.inner, &v.0, &v.1.data_input()); + update(&mut sketch.inner, &v.0, &v.1.data_input(), "hydra-cms"); } parts.push(sketch); } diff --git a/sketch-bench/src/wrappers/hydra_cs/mod.rs b/sketch-bench/src/wrappers/hydra_cs/mod.rs index ba6c2b5f..6d49033b 100644 --- a/sketch-bench/src/wrappers/hydra_cs/mod.rs +++ b/sketch-bench/src/wrappers/hydra_cs/mod.rs @@ -8,7 +8,7 @@ pub mod polars; pub mod sketchlib; pub(crate) use super::hydra_shared::{ - check_grid, grid_overhead_bytes, labels, merge, new_hydra, query, update, + check_grid, grid_overhead_bytes, label_columns, labels, new_hydra, query, update, }; #[cfg(test)] @@ -20,12 +20,15 @@ mod tests { use crate::params::SketchParams; fn built() -> HydraCs { - build_hydra_cs(&ParamSet::of(&HydraCsParams { - rows: 3, - cols: 64, - cell_rows: 3, - cell_cols: 256, - })) + build_hydra_cs( + &ParamSet::of(&HydraCsParams { + rows: 3, + cols: 64, + cell_rows: 3, + cell_cols: 256, + }), + 2, + ) .expect("canonical dimensions build") } @@ -38,6 +41,7 @@ mod tests { &mut sketch.inner, &r.0, &asap_sketchlib::DataInput::I64(r.1), + "hydra-cs", ); } @@ -84,7 +88,9 @@ mod tests { for _ in 0..4 { fed(&mut right, &record("a;x", 10)); } - merge(&mut left.inner, &right.inner); + left.inner + .merge(&right.inner) + .expect("both operands built from one ParamSet, so shapes match"); assert_eq!(left.estimate_subpop_frequency(&["a"], &10i64), 7.0); } @@ -96,7 +102,7 @@ mod tests { cell_rows: 3, cell_cols: 256, }); - let Err(err) = build_hydra_cs(&bad) else { + let Err(err) = build_hydra_cs(&bad, 2) else { panic!("a zero dimension must be refused, not built"); }; let err = err.to_string(); @@ -117,6 +123,6 @@ mod tests { #[test] fn canonical_params_build() { - assert!(build_hydra_cs(&ParamSet::of(&HydraCsParams::canonical())).is_ok()); + assert!(build_hydra_cs(&ParamSet::of(&HydraCsParams::canonical()), 2).is_ok()); } } diff --git a/sketch-bench/src/wrappers/hydra_cs/sketchlib.rs b/sketch-bench/src/wrappers/hydra_cs/sketchlib.rs index 7108f819..1ae832bf 100644 --- a/sketch-bench/src/wrappers/hydra_cs/sketchlib.rs +++ b/sketch-bench/src/wrappers/hydra_cs/sketchlib.rs @@ -18,7 +18,8 @@ pub struct HydraCs { params: HydraCsParams, } -pub fn build_hydra_cs(config: &ParamSet) -> Result { +/// `label_columns`: the key columns every record carries. +pub fn build_hydra_cs(config: &ParamSet, label_columns: usize) -> Result { let p: HydraCsParams = config.parse()?; check_grid(p.rows, p.cols, "hydra-cs")?; for (name, v) in [("cell_rows", p.cell_rows), ("cell_cols", p.cell_cols)] { @@ -31,7 +32,7 @@ pub fn build_hydra_cs(config: &ParamSet) -> Result { p.cell_cols, )); Ok(HydraCs { - inner: new_hydra(p.rows, p.cols, cell), + inner: new_hydra(p.rows, p.cols, label_columns, cell, "hydra-cs")?, params: p, }) } @@ -43,6 +44,7 @@ impl HydraCs { &self.inner, labels, &HydraQuery::Frequency(value.data_input()), + "hydra-cs", ) } } @@ -63,11 +65,11 @@ pub fn insert_hydra_cs( let mut out = Vec::with_capacity(passes); for _ in 0..passes { // Built here, so calling the closure is the insert and nothing else. - let mut sketch = build_hydra_cs(params)?; + let mut sketch = build_hydra_cs(params, label_columns(&items))?; let items = items.clone(); out.push(Box::new(move || { for v in items.iter() { - update(&mut sketch.inner, &v.0, &v.1.data_input()); + update(&mut sketch.inner, &v.0, &v.1.data_input(), "hydra-cs"); } memory_hydra_cs(&sketch) }) as Pass); @@ -82,7 +84,8 @@ pub fn insert_step_hydra_cs( ) -> Result, BuildError> { let mut out = Vec::with_capacity(passes); for _ in 0..passes { - let sketch: Shared<_> = Rc::new(RefCell::new(build_hydra_cs(params)?)); + let sketch: Shared<_> = + Rc::new(RefCell::new(build_hydra_cs(params, label_columns(&items))?)); let (driven, read) = (sketch.clone(), sketch); let stream = items.clone(); out.push(StepPass { @@ -90,7 +93,7 @@ pub fn insert_step_hydra_cs( step: Box::new(move |i| { let sketch = &mut *driven.borrow_mut(); let v = &stream[i]; - update(&mut sketch.inner, &v.0, &v.1.data_input()); + update(&mut sketch.inner, &v.0, &v.1.data_input(), "hydra-cs"); }), footprint: Box::new(move || memory_hydra_cs(&read.borrow())), }); @@ -121,7 +124,10 @@ pub fn merge_query_hydra_cs( // Built, fed and folded here: the closure below asks, and only asks. let (mut sketch, rest) = hydra_cs_shards(params, &items, shards)?; for other in rest.iter() { - merge(&mut sketch.inner, &other.inner); + sketch + .inner + .merge(&other.inner) + .expect("both operands built from one ParamSet, so grid and cell shapes match"); } let probes = probes.clone(); out.push(Box::new(move || { @@ -147,7 +153,9 @@ pub fn merge_hydra_cs( let (mut acc, rest) = hydra_cs_shards(params, &items, shards)?; out.push(Box::new(move || { for other in rest.iter() { - merge(&mut acc.inner, &other.inner); + acc.inner + .merge(&other.inner) + .expect("both operands built from one ParamSet, so grid and cell shapes match"); } memory_hydra_cs(&acc) }) as Pass); @@ -171,7 +179,9 @@ pub fn merge_step_hydra_cs( step: Box::new(move |i| { let acc = &mut *driven.borrow_mut(); let other = &rest[i]; - merge(&mut acc.inner, &other.inner); + acc.inner + .merge(&other.inner) + .expect("both operands built from one ParamSet, so grid and cell shapes match"); }), footprint: Box::new(move || memory_hydra_cs(&read.borrow())), }); @@ -189,9 +199,9 @@ fn hydra_cs_shards( ) -> Result<(HydraCs, Vec), BuildError> { let mut parts: Vec = Vec::new(); for shard in partition(items, shards) { - let mut sketch = build_hydra_cs(params)?; + let mut sketch = build_hydra_cs(params, label_columns(items))?; for v in shard { - update(&mut sketch.inner, &v.0, &v.1.data_input()); + update(&mut sketch.inner, &v.0, &v.1.data_input(), "hydra-cs"); } parts.push(sketch); } diff --git a/sketch-bench/src/wrappers/hydra_hll/mod.rs b/sketch-bench/src/wrappers/hydra_hll/mod.rs index a76d28b8..52ef926f 100644 --- a/sketch-bench/src/wrappers/hydra_hll/mod.rs +++ b/sketch-bench/src/wrappers/hydra_hll/mod.rs @@ -8,7 +8,7 @@ pub mod polars; pub mod sketchlib; pub(crate) use super::hydra_shared::{ - check_grid, grid_overhead_bytes, labels, merge, new_hydra, query, update, + check_grid, grid_overhead_bytes, label_columns, labels, new_hydra, query, update, }; /// Registers in one `HyperLogLog` cell. The library fixes the cell at @@ -25,7 +25,7 @@ mod tests { use crate::params::SketchParams; fn built_hll() -> HydraHll { - build_hydra_hll(&ParamSet::of(&HydraHllParams { rows: 3, cols: 64 })) + build_hydra_hll(&ParamSet::of(&HydraHllParams { rows: 3, cols: 64 }), 2) .expect("canonical dimensions build") } @@ -38,12 +38,13 @@ mod tests { &mut sketch.inner, &r.0, &asap_sketchlib::DataInput::I64(r.1), + "hydra-hll", ); } #[test] fn canonical_params_build() { - assert!(build_hydra_hll(&ParamSet::of(&HydraHllParams::canonical())).is_ok()); + assert!(build_hydra_hll(&ParamSet::of(&HydraHllParams::canonical()), 2).is_ok()); } /// The statistic is the *size* of the group, so repeats of one value must @@ -80,7 +81,9 @@ mod tests { fed_hll(&mut left, &record("a;x", 20)); fed_hll(&mut right, &record("a;x", 20)); fed_hll(&mut right, &record("a;x", 30)); - merge(&mut left.inner, &right.inner); + left.inner + .merge(&right.inner) + .expect("both operands built from one ParamSet, so shapes match"); let est = left.estimate_subpop_cardinality(&["a"]); assert!( (est - 3.0).abs() < 0.5, @@ -102,7 +105,7 @@ mod tests { #[test] fn zero_dimensions_are_refused_by_name() { let bad = ParamSet::of(&HydraHllParams { rows: 3, cols: 0 }); - let Err(err) = build_hydra_hll(&bad) else { + let Err(err) = build_hydra_hll(&bad, 2) else { panic!("a zero dimension must be refused, not built"); }; let err = err.to_string(); diff --git a/sketch-bench/src/wrappers/hydra_hll/sketchlib.rs b/sketch-bench/src/wrappers/hydra_hll/sketchlib.rs index b70bbc03..4e40da4e 100644 --- a/sketch-bench/src/wrappers/hydra_hll/sketchlib.rs +++ b/sketch-bench/src/wrappers/hydra_hll/sketchlib.rs @@ -19,7 +19,8 @@ pub struct HydraHll { params: HydraHllParams, } -pub fn build_hydra_hll(config: &ParamSet) -> Result { +/// `label_columns`: the key columns every record carries. +pub fn build_hydra_hll(config: &ParamSet, label_columns: usize) -> Result { let p: HydraHllParams = config.parse()?; check_grid(p.rows, p.cols, "hydra-hll")?; // Named through the `ErtlMLE` impl explicitly: `HyperLogLog` is a type @@ -27,7 +28,7 @@ pub fn build_hydra_hll(config: &ParamSet) -> Result { // estimators the alias can carry. The enum fixes this one. let cell = HydraCounter::HLL(HyperLogLog::::new()); Ok(HydraHll { - inner: new_hydra(p.rows, p.cols, cell), + inner: new_hydra(p.rows, p.cols, label_columns, cell, "hydra-hll")?, params: p, }) } @@ -35,7 +36,7 @@ pub fn build_hydra_hll(config: &ParamSet) -> Result { impl HydraHll { #[inline] pub fn estimate_subpop_cardinality(&self, labels: &[&str]) -> f64 { - query(&self.inner, labels, &HydraQuery::Cardinality) + query(&self.inner, labels, &HydraQuery::Cardinality, "hydra-hll") } } @@ -54,11 +55,11 @@ pub fn insert_hydra_hll( let mut out = Vec::with_capacity(passes); for _ in 0..passes { // Built here, so calling the closure is the insert and nothing else. - let mut sketch = build_hydra_hll(params)?; + let mut sketch = build_hydra_hll(params, label_columns(&items))?; let items = items.clone(); out.push(Box::new(move || { for v in items.iter() { - update(&mut sketch.inner, &v.0, &v.1.data_input()); + update(&mut sketch.inner, &v.0, &v.1.data_input(), "hydra-hll"); } memory_hydra_hll(&sketch) }) as Pass); @@ -73,7 +74,10 @@ pub fn insert_step_hydra_hll( ) -> Result, BuildError> { let mut out = Vec::with_capacity(passes); for _ in 0..passes { - let sketch: Shared<_> = Rc::new(RefCell::new(build_hydra_hll(params)?)); + let sketch: Shared<_> = Rc::new(RefCell::new(build_hydra_hll( + params, + label_columns(&items), + )?)); let (driven, read) = (sketch.clone(), sketch); let stream = items.clone(); out.push(StepPass { @@ -81,7 +85,7 @@ pub fn insert_step_hydra_hll( step: Box::new(move |i| { let sketch = &mut *driven.borrow_mut(); let v = &stream[i]; - update(&mut sketch.inner, &v.0, &v.1.data_input()); + update(&mut sketch.inner, &v.0, &v.1.data_input(), "hydra-hll"); }), footprint: Box::new(move || memory_hydra_hll(&read.borrow())), }); @@ -112,7 +116,10 @@ pub fn merge_query_hydra_hll( // Built, fed and folded here: the closure below asks, and only asks. let (mut sketch, rest) = hydra_hll_shards(params, &items, shards)?; for other in rest.iter() { - merge(&mut sketch.inner, &other.inner); + sketch + .inner + .merge(&other.inner) + .expect("both operands built from one ParamSet, so grid and cell shapes match"); } let probes = probes.clone(); out.push(Box::new(move || { @@ -138,7 +145,9 @@ pub fn merge_hydra_hll( let (mut acc, rest) = hydra_hll_shards(params, &items, shards)?; out.push(Box::new(move || { for other in rest.iter() { - merge(&mut acc.inner, &other.inner); + acc.inner + .merge(&other.inner) + .expect("both operands built from one ParamSet, so grid and cell shapes match"); } memory_hydra_hll(&acc) }) as Pass); @@ -162,7 +171,9 @@ pub fn merge_step_hydra_hll( step: Box::new(move |i| { let acc = &mut *driven.borrow_mut(); let other = &rest[i]; - merge(&mut acc.inner, &other.inner); + acc.inner + .merge(&other.inner) + .expect("both operands built from one ParamSet, so grid and cell shapes match"); }), footprint: Box::new(move || memory_hydra_hll(&read.borrow())), }); @@ -180,9 +191,9 @@ fn hydra_hll_shards( ) -> Result<(HydraHll, Vec), BuildError> { let mut parts: Vec = Vec::new(); for shard in partition(items, shards) { - let mut sketch = build_hydra_hll(params)?; + let mut sketch = build_hydra_hll(params, label_columns(items))?; for v in shard { - update(&mut sketch.inner, &v.0, &v.1.data_input()); + update(&mut sketch.inner, &v.0, &v.1.data_input(), "hydra-hll"); } parts.push(sketch); } diff --git a/sketch-bench/src/wrappers/hydra_kll/mod.rs b/sketch-bench/src/wrappers/hydra_kll/mod.rs index 46b919b7..70dd0de0 100644 --- a/sketch-bench/src/wrappers/hydra_kll/mod.rs +++ b/sketch-bench/src/wrappers/hydra_kll/mod.rs @@ -8,7 +8,7 @@ pub mod polars; pub mod sketchlib; pub(crate) use super::hydra_shared::{ - check_grid, grid_overhead_bytes, labels, merge, new_hydra, query, update, + check_grid, grid_overhead_bytes, label_columns, labels, new_hydra, query, update, }; // Level count and decay of an `asap_sketchlib::KLL`. Both are private constants @@ -53,11 +53,14 @@ mod tests { use crate::params::SketchParams; fn built_kll() -> HydraKll { - build_hydra_kll(&ParamSet::of(&HydraKllParams { - rows: 3, - cols: 64, - cell_k: 200, - })) + build_hydra_kll( + &ParamSet::of(&HydraKllParams { + rows: 3, + cols: 64, + cell_k: 200, + }), + 2, + ) .expect("canonical dimensions build") } @@ -70,12 +73,13 @@ mod tests { &mut sketch.inner, &r.0, &asap_sketchlib::DataInput::F64(r.1), + "hydra-kll", ); } #[test] fn canonical_params_build() { - assert!(build_hydra_kll(&ParamSet::of(&HydraKllParams::canonical())).is_ok()); + assert!(build_hydra_kll(&ParamSet::of(&HydraKllParams::canonical()), 2).is_ok()); } /// The statistic is ordered and taken inside a group, so the median of one @@ -135,7 +139,7 @@ mod tests { cols: 64, cell_k: 0, }); - let Err(err) = build_hydra_kll(&bad) else { + let Err(err) = build_hydra_kll(&bad, 2) else { panic!("a zero cell_k must be refused, not built"); }; assert!( diff --git a/sketch-bench/src/wrappers/hydra_kll/sketchlib.rs b/sketch-bench/src/wrappers/hydra_kll/sketchlib.rs index 159baa90..f46062df 100644 --- a/sketch-bench/src/wrappers/hydra_kll/sketchlib.rs +++ b/sketch-bench/src/wrappers/hydra_kll/sketchlib.rs @@ -19,7 +19,8 @@ pub struct HydraKll { params: HydraKllParams, } -pub fn build_hydra_kll(config: &ParamSet) -> Result { +/// `label_columns`: the key columns every record carries. +pub fn build_hydra_kll(config: &ParamSet, label_columns: usize) -> Result { let p: HydraKllParams = config.parse()?; check_grid(p.rows, p.cols, "hydra-kll")?; // The cell is the same `asap_sketchlib::KLL` the `kll-*` rows hold, and it @@ -35,7 +36,7 @@ pub fn build_hydra_kll(config: &ParamSet) -> Result { } let cell = HydraCounter::KLL(KLL::init_kll(p.cell_k as i32)); Ok(HydraKll { - inner: new_hydra(p.rows, p.cols, cell), + inner: new_hydra(p.rows, p.cols, label_columns, cell, "hydra-kll")?, params: p, }) } @@ -46,7 +47,7 @@ impl HydraKll { /// answers the inverse question. #[inline] pub fn estimate_subpop_quantile(&self, labels: &[&str], phi: f64) -> f64 { - query(&self.inner, labels, &HydraQuery::Quantile(phi)) + query(&self.inner, labels, &HydraQuery::Quantile(phi), "hydra-kll") } } @@ -68,11 +69,11 @@ pub fn insert_hydra_kll( let mut out = Vec::with_capacity(passes); for _ in 0..passes { // Built here, so calling the closure is the insert and nothing else. - let mut sketch = build_hydra_kll(params)?; + let mut sketch = build_hydra_kll(params, label_columns(&items))?; let items = items.clone(); out.push(Box::new(move || { for v in items.iter() { - update(&mut sketch.inner, &v.0, &v.1.data_input()); + update(&mut sketch.inner, &v.0, &v.1.data_input(), "hydra-kll"); } memory_hydra_kll(&sketch) }) as Pass); @@ -87,7 +88,10 @@ pub fn insert_step_hydra_kll( ) -> Result, BuildError> { let mut out = Vec::with_capacity(passes); for _ in 0..passes { - let sketch: Shared<_> = Rc::new(RefCell::new(build_hydra_kll(params)?)); + let sketch: Shared<_> = Rc::new(RefCell::new(build_hydra_kll( + params, + label_columns(&items), + )?)); let (driven, read) = (sketch.clone(), sketch); let stream = items.clone(); out.push(StepPass { @@ -95,7 +99,7 @@ pub fn insert_step_hydra_kll( step: Box::new(move |i| { let sketch = &mut *driven.borrow_mut(); let v = &stream[i]; - update(&mut sketch.inner, &v.0, &v.1.data_input()); + update(&mut sketch.inner, &v.0, &v.1.data_input(), "hydra-kll"); }), footprint: Box::new(move || memory_hydra_kll(&read.borrow())), }); @@ -126,7 +130,10 @@ pub fn merge_query_hydra_kll( // Built, fed and folded here: the closure below asks, and only asks. let (mut sketch, rest) = hydra_kll_shards(params, &items, shards)?; for other in rest.iter() { - merge(&mut sketch.inner, &other.inner); + sketch + .inner + .merge(&other.inner) + .expect("both operands built from one ParamSet, so grid and cell shapes match"); } let probes = probes.clone(); out.push(Box::new(move || { @@ -152,7 +159,9 @@ pub fn merge_hydra_kll( let (mut acc, rest) = hydra_kll_shards(params, &items, shards)?; out.push(Box::new(move || { for other in rest.iter() { - merge(&mut acc.inner, &other.inner); + acc.inner + .merge(&other.inner) + .expect("both operands built from one ParamSet, so grid and cell shapes match"); } memory_hydra_kll(&acc) }) as Pass); @@ -176,7 +185,9 @@ pub fn merge_step_hydra_kll( step: Box::new(move |i| { let acc = &mut *driven.borrow_mut(); let other = &rest[i]; - merge(&mut acc.inner, &other.inner); + acc.inner + .merge(&other.inner) + .expect("both operands built from one ParamSet, so grid and cell shapes match"); }), footprint: Box::new(move || memory_hydra_kll(&read.borrow())), }); @@ -194,9 +205,9 @@ fn hydra_kll_shards( ) -> Result<(HydraKll, Vec), BuildError> { let mut parts: Vec = Vec::new(); for shard in partition(items, shards) { - let mut sketch = build_hydra_kll(params)?; + let mut sketch = build_hydra_kll(params, label_columns(items))?; for v in shard { - update(&mut sketch.inner, &v.0, &v.1.data_input()); + update(&mut sketch.inner, &v.0, &v.1.data_input(), "hydra-kll"); } parts.push(sketch); } diff --git a/sketch-bench/src/wrappers/hydra_shared.rs b/sketch-bench/src/wrappers/hydra_shared.rs index aa47d265..d2df81a3 100644 --- a/sketch-bench/src/wrappers/hydra_shared.rs +++ b/sketch-bench/src/wrappers/hydra_shared.rs @@ -10,57 +10,58 @@ pub(crate) fn labels(group: &[String]) -> Vec<&str> { group.iter().map(String::as_str).collect() } -/// The schema a grid holds until its first record names the label columns: -/// asap_sketchlib 0.3 fixes a Hydra's key columns at construction, and the -/// wrappers learn them from the stream. -const UNSET: &str = "__label_columns_unset__"; - -/// A grid whose key columns the first [`update`] sets. -pub(crate) fn new_hydra(rows: usize, cols: usize, cell: HydraCounter) -> Hydra { - Hydra::with_schema(rows, cols, [UNSET], cell).expect("one label column is a valid schema") +/// The label columns of a `;`-joined record stream: its first record's, as +/// every record of one table carries the same columns. An empty label is a +/// column of its own. +pub(crate) fn label_columns(items: &[(String, V)]) -> usize { + items.first().map_or(1, |(key, _)| key.split(';').count()) } -fn unset(h: &Hydra) -> bool { - h.schema() == [UNSET] +/// A grid over `label_columns` key columns, as asap_sketchlib 0.3 fixes +/// them at construction. +pub(crate) fn new_hydra( + rows: usize, + cols: usize, + label_columns: usize, + cell: HydraCounter, + variant: &str, +) -> Result { + if label_columns == 0 { + return Err(BuildError(format!( + "{variant}: a record needs at least one label column" + ))); + } + let schema = (0..label_columns).map(|i| format!("label{i}")); + Hydra::with_schema(rows, cols, schema, cell).map_err(|e| BuildError(format!("{variant}: {e}"))) } -/// Records one `;`-joined record: one label value per column, positionally. -pub(crate) fn update(h: &mut Hydra, key: &str, value: &DataInput) { - let parts: Vec<&str> = key.split(';').filter(|s| !s.is_empty()).collect(); - if unset(h) { - let schema = (0..parts.len()).map(|i| format!("label{i}")); - *h = Hydra::with_schema(h.row_num, h.col_num, schema, h.type_to_clone.clone()) - .expect("a record names at least one label"); +/// Records one `;`-joined record, one value per key column in place. A +/// record of another width is refused. +pub(crate) fn update(h: &mut Hydra, key: &str, value: &DataInput, variant: &str) { + let parts: Vec<&str> = key.split(';').collect(); + if let Err(e) = h.update(&parts, value, None) { + panic!( + "{variant}: record {key:?} has {} label(s), the grid {}: {e}", + parts.len(), + h.schema().len() + ); } - h.update(&parts, value, None) - .expect("every record carries one value per label column"); } /// Asks `query` of the subpopulation `group` constrains: its values are the -/// leading label columns' (the scored subpopulations group by column 0), the -/// rest unconstrained. An empty grid answers 0. -pub(crate) fn query(h: &Hydra, group: &[&str], query: &HydraQuery) -> f64 { - if unset(h) { - return 0.0; +/// leading key columns' (the scored subpopulations group by column 0), the +/// rest unconstrained. A probe wider than the grid is refused. +pub(crate) fn query(h: &Hydra, group: &[&str], query: &HydraQuery, variant: &str) -> f64 { + let width = h.schema().len(); + if group.len() > width { + panic!( + "{variant}: probe {group:?} names {} label(s), the grid {width}", + group.len() + ); } - let mut key: Vec> = group.iter().map(|v| Some(*v)).collect(); - key.resize(h.schema().len(), None); + let key: Vec> = (0..width).map(|i| group.get(i).copied()).collect(); h.query_key(&key, query) - .expect("a probe constrains the leading label columns") -} - -/// Folds `other` into `acc`; a shard that saw no record (still unset) adds -/// nothing. -pub(crate) fn merge(acc: &mut Hydra, other: &Hydra) { - if unset(other) { - return; - } - if unset(acc) { - *acc = other.clone(); - return; - } - acc.merge(other) - .expect("both operands built from one ParamSet, so grid and cell shapes match"); + .unwrap_or_else(|e| panic!("{variant}: probe {group:?}: {e}")) } /// outer grid is the one shape they have in common. diff --git a/sketch-bench/src/wrappers/hydra_univmon/mod.rs b/sketch-bench/src/wrappers/hydra_univmon/mod.rs index db63a39b..181375ee 100644 --- a/sketch-bench/src/wrappers/hydra_univmon/mod.rs +++ b/sketch-bench/src/wrappers/hydra_univmon/mod.rs @@ -8,7 +8,7 @@ pub mod polars; pub mod sketchlib; pub(crate) use super::hydra_shared::{ - check_grid, grid_overhead_bytes, labels, merge, new_hydra, query, update, + check_grid, grid_overhead_bytes, label_columns, labels, new_hydra, query, update, }; #[cfg(test)] @@ -20,14 +20,17 @@ mod tests { use crate::params::SketchParams; fn built() -> HydraUnivmon { - build_hydra_univmon(&ParamSet::of(&HydraUnivmonParams { - rows: 2, - cols: 16, - cell_heap_size: 32, - cell_sketch_row: 5, - cell_sketch_col: 256, - cell_layer_size: 4, - })) + build_hydra_univmon( + &ParamSet::of(&HydraUnivmonParams { + rows: 2, + cols: 16, + cell_heap_size: 32, + cell_sketch_row: 5, + cell_sketch_col: 256, + cell_layer_size: 4, + }), + 2, + ) .expect("canonical dimensions build") } @@ -40,12 +43,13 @@ mod tests { &mut sketch.inner, &r.0, &asap_sketchlib::DataInput::I64(r.1), + "hydra-univmon", ); } #[test] fn canonical_params_build() { - assert!(build_hydra_univmon(&ParamSet::of(&HydraUnivmonParams::canonical())).is_ok()); + assert!(build_hydra_univmon(&ParamSet::of(&HydraUnivmonParams::canonical()), 2).is_ok()); } #[test] @@ -109,7 +113,9 @@ mod tests { for _ in 0..4 { fed(&mut right, &record("a;x", 10)); } - merge(&mut left.inner, &right.inner); + left.inner + .merge(&right.inner) + .expect("both operands built from one ParamSet, so shapes match"); let est = left.estimate_subpop_l1_norm(&["a"]); assert!( (est - 7.0).abs() < 0.5, @@ -127,7 +133,7 @@ mod tests { cell_sketch_col: 0, cell_layer_size: 4, }); - let Err(err) = build_hydra_univmon(&bad) else { + let Err(err) = build_hydra_univmon(&bad, 2) else { panic!("a zero dimension must be refused, not built"); }; let err = err.to_string(); diff --git a/sketch-bench/src/wrappers/hydra_univmon/sketchlib.rs b/sketch-bench/src/wrappers/hydra_univmon/sketchlib.rs index e856ce6e..f7f2e385 100644 --- a/sketch-bench/src/wrappers/hydra_univmon/sketchlib.rs +++ b/sketch-bench/src/wrappers/hydra_univmon/sketchlib.rs @@ -18,7 +18,11 @@ pub struct HydraUnivmon { params: HydraUnivmonParams, } -pub fn build_hydra_univmon(config: &ParamSet) -> Result { +/// `label_columns`: the key columns every record carries. +pub fn build_hydra_univmon( + config: &ParamSet, + label_columns: usize, +) -> Result { let p: HydraUnivmonParams = config.parse()?; check_grid(p.rows, p.cols, "hydra-univmon")?; for (name, v) in [ @@ -38,7 +42,7 @@ pub fn build_hydra_univmon(config: &ParamSet) -> Result Result f64 { - query(&self.inner, labels, &HydraQuery::Cardinality) + query( + &self.inner, + labels, + &HydraQuery::Cardinality, + "hydra-univmon", + ) } #[inline] pub fn estimate_subpop_l1_norm(&self, labels: &[&str]) -> f64 { - query(&self.inner, labels, &HydraQuery::L1Norm) + query(&self.inner, labels, &HydraQuery::L1Norm, "hydra-univmon") } #[inline] pub fn estimate_subpop_l2_norm(&self, labels: &[&str]) -> f64 { - query(&self.inner, labels, &HydraQuery::L2Norm) + query(&self.inner, labels, &HydraQuery::L2Norm, "hydra-univmon") } #[inline] pub fn estimate_subpop_entropy(&self, labels: &[&str]) -> f64 { - query(&self.inner, labels, &HydraQuery::Entropy) + query(&self.inner, labels, &HydraQuery::Entropy, "hydra-univmon") } } @@ -81,11 +90,11 @@ pub fn insert_hydra_univmon( let mut out = Vec::with_capacity(passes); for _ in 0..passes { // Built here, so calling the closure is the insert and nothing else. - let mut sketch = build_hydra_univmon(params)?; + let mut sketch = build_hydra_univmon(params, label_columns(&items))?; let items = items.clone(); out.push(Box::new(move || { for v in items.iter() { - update(&mut sketch.inner, &v.0, &v.1.data_input()); + update(&mut sketch.inner, &v.0, &v.1.data_input(), "hydra-univmon"); } memory_hydra_univmon(&sketch) }) as Pass); @@ -100,7 +109,10 @@ pub fn insert_step_hydra_univmon( ) -> Result, BuildError> { let mut out = Vec::with_capacity(passes); for _ in 0..passes { - let sketch: Shared<_> = Rc::new(RefCell::new(build_hydra_univmon(params)?)); + let sketch: Shared<_> = Rc::new(RefCell::new(build_hydra_univmon( + params, + label_columns(&items), + )?)); let (driven, read) = (sketch.clone(), sketch); let stream = items.clone(); out.push(StepPass { @@ -108,7 +120,7 @@ pub fn insert_step_hydra_univmon( step: Box::new(move |i| { let sketch = &mut *driven.borrow_mut(); let v = &stream[i]; - update(&mut sketch.inner, &v.0, &v.1.data_input()); + update(&mut sketch.inner, &v.0, &v.1.data_input(), "hydra-univmon"); }), footprint: Box::new(move || memory_hydra_univmon(&read.borrow())), }); @@ -129,7 +141,10 @@ fn asked_hydra_univmon( // Built, fed and folded here: the closure below asks, and only asks. let (mut sketch, rest) = hydra_univmon_shards(params, &items, shards)?; for other in rest.iter() { - merge(&mut sketch.inner, &other.inner); + sketch + .inner + .merge(&other.inner) + .expect("both operands built from one ParamSet, so grid and cell shapes match"); } let probes = probes.clone(); out.push(Box::new(move || { @@ -295,7 +310,9 @@ pub fn merge_hydra_univmon( let (mut acc, rest) = hydra_univmon_shards(params, &items, shards)?; out.push(Box::new(move || { for other in rest.iter() { - merge(&mut acc.inner, &other.inner); + acc.inner + .merge(&other.inner) + .expect("both operands built from one ParamSet, so grid and cell shapes match"); } memory_hydra_univmon(&acc) }) as Pass); @@ -319,7 +336,9 @@ pub fn merge_step_hydra_univmon( step: Box::new(move |i| { let acc = &mut *driven.borrow_mut(); let other = &rest[i]; - merge(&mut acc.inner, &other.inner); + acc.inner + .merge(&other.inner) + .expect("both operands built from one ParamSet, so grid and cell shapes match"); }), footprint: Box::new(move || memory_hydra_univmon(&read.borrow())), }); @@ -337,9 +356,9 @@ fn hydra_univmon_shards( ) -> Result<(HydraUnivmon, Vec), BuildError> { let mut parts: Vec = Vec::new(); for shard in partition(items, shards) { - let mut sketch = build_hydra_univmon(params)?; + let mut sketch = build_hydra_univmon(params, label_columns(items))?; for v in shard { - update(&mut sketch.inner, &v.0, &v.1.data_input()); + update(&mut sketch.inner, &v.0, &v.1.data_input(), "hydra-univmon"); } parts.push(sketch); } From cdacb2431cdb6b5b16d0d3c482ed5340d0432628 Mon Sep 17 00:00:00 2001 From: zz_y Date: Wed, 7 Oct 2026 20:51:12 +0000 Subject: [PATCH 3/3] top-k memory counts 0.3's heap index; one asap_sketchlib pin; Hydra width checked at build From the second review of #183: - aqpbm_core::hh_heap_bytes(capacity, item_bytes): what 0.3's HHHeap holds per resident, the HHItem, its u64 digest (slots) and its share of the position index (hashbrown buckets at 7/8 load, power of two, each a u64 digest, a SmallVec<[usize; 2]> and a control byte). cms_heap, cs_heap, UnivMon and aqpbm-planeval use it in place of heap x HHItem. - aqpbm-planeval takes the workspace asap_sketchlib; stale 0.2.2 notes fixed (planeval Cargo.toml, hydra_kll). - build_hydra_* check every record's label width and return a BuildError naming the variant and both widths; the in-closure panic is a backstop. - polars_shared says its baseline keeps 0.2.2's any-column subset keys. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- aqpbm-core/src/heap_footprint.rs | 42 +++++++++++++++++++ aqpbm-core/src/lib.rs | 2 + aqpbm-planeval/Cargo.toml | 4 +- aqpbm-planeval/src/handle.rs | 18 ++------ sketch-bench/src/wrappers/cms_heap/mod.rs | 25 ++++++++++- .../src/wrappers/cms_heap/sketchlib.rs | 4 +- sketch-bench/src/wrappers/cs_heap.rs | 3 +- sketch-bench/src/wrappers/hydra_cms/mod.rs | 18 ++++++++ .../src/wrappers/hydra_cms/sketchlib.rs | 6 +-- .../src/wrappers/hydra_cs/sketchlib.rs | 10 +++-- .../src/wrappers/hydra_hll/sketchlib.rs | 6 +-- sketch-bench/src/wrappers/hydra_kll/mod.rs | 3 +- .../src/wrappers/hydra_kll/sketchlib.rs | 6 +-- sketch-bench/src/wrappers/hydra_shared.rs | 30 +++++++------ .../src/wrappers/hydra_univmon/sketchlib.rs | 6 +-- sketch-bench/src/wrappers/mod.rs | 10 +++++ sketch-bench/src/wrappers/polars_shared.rs | 11 ++--- sketch-bench/src/wrappers/univmon/mod.rs | 2 +- .../src/wrappers/univmon/sketchlib.rs | 3 +- 19 files changed, 148 insertions(+), 61 deletions(-) create mode 100644 aqpbm-core/src/heap_footprint.rs diff --git a/aqpbm-core/src/heap_footprint.rs b/aqpbm-core/src/heap_footprint.rs new file mode 100644 index 00000000..489819c4 --- /dev/null +++ b/aqpbm-core/src/heap_footprint.rs @@ -0,0 +1,42 @@ +//! What asap_sketchlib 0.3's `HHHeap` (behind `CMSHeap`, `CSHeap` and +//! UnivMon's layers) holds for its residents: the heap array of `HHItem`s, a +//! parallel digest column (`slots: Vec`), and a position index +//! `HashMap>` that hashbrown sizes in power-of-two +//! buckets at 7/8 load. The residents' own key bytes, for string keys, are the +//! caller's to add. + +/// One index bucket: the `u64` digest, the inline `SmallVec<[usize; 2]>` +/// (two positions plus its length word) and hashbrown's control byte. +pub const HH_HEAP_INDEX_ENTRY_BYTES: usize = 8 + 3 * std::mem::size_of::() + 1; + +/// Buckets hashbrown allocates for `capacity` entries: at 7/8 load, rounded +/// up to a power of two. +pub fn hash_buckets(capacity: usize) -> usize { + if capacity == 0 { + return 0; + } + (capacity.div_ceil(7) * 8).next_power_of_two() +} + +/// Bytes an `HHHeap` holding `capacity` residents keeps, given the size of +/// one `HHItem`: the item, its digest, and its share of the index. +pub fn hh_heap_bytes(capacity: usize, item_bytes: usize) -> usize { + capacity * (item_bytes + std::mem::size_of::()) + + hash_buckets(capacity) * HH_HEAP_INDEX_ENTRY_BYTES +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_resident_costs_more_than_its_item() { + let item = 40; + for (small, large) in [(32, 128), (128, 2048)] { + let grown = hh_heap_bytes(large, item) - hh_heap_bytes(small, item); + assert!(grown > (large - small) * item, "{small}->{large}: {grown}"); + } + assert_eq!(hash_buckets(32), 64); + assert_eq!(hh_heap_bytes(0, item), 0); + } +} diff --git a/aqpbm-core/src/lib.rs b/aqpbm-core/src/lib.rs index 8792fc47..b104f323 100644 --- a/aqpbm-core/src/lib.rs +++ b/aqpbm-core/src/lib.rs @@ -7,6 +7,7 @@ pub mod atomic_costs; pub mod benchmark_result; pub mod erp; pub mod error; +pub mod heap_footprint; pub mod measure; pub mod metrics; @@ -31,6 +32,7 @@ pub use erp::{ erp_artifact, erp_record, ErpArtifact, ErpRecord, ErpResourceProfile, ERP_SCHEMA_VERSION, }; pub use error::RunError; +pub use heap_footprint::{hash_buckets, hh_heap_bytes, HH_HEAP_INDEX_ENTRY_BYTES}; pub use measure::{ measure, record_calls, runs_for, MeasureConfig, Measurement, Pass, Report, RunOutcome, MIN_MERGE_SHARDS, diff --git a/aqpbm-planeval/Cargo.toml b/aqpbm-planeval/Cargo.toml index 114abb5c..4908a6a3 100644 --- a/aqpbm-planeval/Cargo.toml +++ b/aqpbm-planeval/Cargo.toml @@ -19,9 +19,7 @@ asap-types = { git = "https://github.com/ProjectASAP/ASAPPlanner", rev = "3c3133 asap-aware-mapping = { git = "https://github.com/ProjectASAP/ASAPPlanner", rev = "3c31338d6fa28e31acaf0a11626a05f4d04df9b0" } asap-frontend-promql = { git = "https://github.com/ProjectASAP/ASAPPlanner", rev = "3c31338d6fa28e31acaf0a11626a05f4d04df9b0" } -# 0.3.0, not the workspace pin (0.2.2): cdf_cached/quantile_cached do not -# exist before 0.3.0 and a 101-point probe grid re-sorts on every call there. -asap_sketchlib = { version = "0.3.0", features = ["experimental"] } +asap_sketchlib.workspace = true aqpbm-core = { workspace = true, features = ["hdrhist"] } aqpbm-datagen.workspace = true diff --git a/aqpbm-planeval/src/handle.rs b/aqpbm-planeval/src/handle.rs index adcb789c..3f2f526e 100644 --- a/aqpbm-planeval/src/handle.rs +++ b/aqpbm-planeval/src/handle.rs @@ -816,8 +816,6 @@ impl SummaryHandle for CsHeapHandle { const SKETCHLIB_PREALLOCATED_SLOTS: usize = 1024; -const SKETCHLIB_HEAP_INDEX_ENTRY_BYTES: usize = 8 + 24 + 1; - fn grown_capacity(reserved: usize, len: usize) -> usize { let mut capacity = reserved.max(1); while capacity < len { @@ -829,14 +827,6 @@ fn grown_capacity(reserved: usize, len: usize) -> usize { capacity } -fn hash_buckets(capacity: usize) -> usize { - if capacity == 0 { - return 0; - } - let wanted = capacity.div_ceil(7) * 8; - wanted.next_power_of_two() -} - fn heap_bytes(heap: &HHHeap, heap_size: usize) -> usize { let residents = heap.heap(); let capacity = grown_capacity(heap_size.min(SKETCHLIB_PREALLOCATED_SLOTS), residents.len()); @@ -848,10 +838,7 @@ fn heap_bytes(heap: &HHHeap, heap_size: usize) -> usize { _ => 0, }) .sum(); - capacity * std::mem::size_of::() - + capacity * std::mem::size_of::() - + hash_buckets(capacity) * SKETCHLIB_HEAP_INDEX_ENTRY_BYTES - + keys + aqpbm_core::hh_heap_bytes(capacity, std::mem::size_of::()) + keys } fn heap_topk(node: PostAsapNodeId, heap: &HHHeap, k: usize) -> Result { @@ -1225,7 +1212,8 @@ mod tests { let items = heap_size as usize * std::mem::size_of::(); let digests = heap_size as usize * std::mem::size_of::(); - let index = hash_buckets(heap_size as usize) * SKETCHLIB_HEAP_INDEX_ENTRY_BYTES; + let index = + aqpbm_core::hash_buckets(heap_size as usize) * aqpbm_core::HH_HEAP_INDEX_ENTRY_BYTES; let keys: usize = (0..heap_size as usize).map(|_| "series-000".len()).sum(); assert!( held >= items + digests + index, diff --git a/sketch-bench/src/wrappers/cms_heap/mod.rs b/sketch-bench/src/wrappers/cms_heap/mod.rs index e61736f5..2fdb2253 100644 --- a/sketch-bench/src/wrappers/cms_heap/mod.rs +++ b/sketch-bench/src/wrappers/cms_heap/mod.rs @@ -70,7 +70,7 @@ mod tests { } /// Footprint is `rows * cols` counters at the real width plus a full heap - /// of `heap` `HHItem`s, as UnivMon counts its heaps (#146). + /// of `heap` residents: items, digests and the position index (#146). #[test] fn footprint_is_counters_plus_heap() { let p = ParamSet::of(&CmsHeapParams { @@ -78,7 +78,7 @@ mod tests { cols: 2048, heap: Some(128), }); - let heap = 128 * std::mem::size_of::(); + let heap = crate::wrappers::hh_heap_footprint(128); let fast = build_cms_heap_lib_vector2d_fast(&p).expect("5x2048 is a valid shape"); assert_eq!( memory_cms_heap_lib_vector2d_fast(&fast), @@ -91,6 +91,27 @@ mod tests { ); } + /// A resident costs more than its `HHItem`: its digest and its share of + /// the position index too. + #[test] + fn the_footprint_grows_by_more_than_an_item_per_resident() { + let at = |heap| { + let p = ParamSet::of(&CmsHeapParams { + rows: 3, + cols: 256, + heap: Some(heap), + }); + memory_cms_heap_lib_vector2d_fast(&build_cms_heap_lib_vector2d_fast(&p).unwrap()) + }; + let item = std::mem::size_of::(); + for (small, large) in [(32, 128), (512, 2048)] { + assert!( + at(large) - at(small) > (large - small) * item, + "{small} -> {large}" + ); + } + } + /// A heap smaller than the `k` it answers can't answer, and is refused. #[test] fn a_heap_below_k_is_refused() { diff --git a/sketch-bench/src/wrappers/cms_heap/sketchlib.rs b/sketch-bench/src/wrappers/cms_heap/sketchlib.rs index 7d29d951..0cdb446b 100644 --- a/sketch-bench/src/wrappers/cms_heap/sketchlib.rs +++ b/sketch-bench/src/wrappers/cms_heap/sketchlib.rs @@ -80,7 +80,7 @@ pub fn build_cms_heap_lib_vector2d_fast( /// UnivMon counts its heaps so the TopK rows compare like for like. pub fn memory_cms_heap_lib_vector2d_fast(sketch: &CmsHeapLibVector2dFast) -> usize { sketch.rows * sketch.cols * std::mem::size_of::() - + sketch.heap * std::mem::size_of::() + + crate::wrappers::hh_heap_footprint(sketch.heap) } // ---------- asap_sketchlib: Vector2D + RegularPath ---------- @@ -109,7 +109,7 @@ pub fn build_cms_heap_lib_vector2d_regular( /// As [`memory_cms_heap_lib_vector2d_fast`]. pub fn memory_cms_heap_lib_vector2d_regular(sketch: &CmsHeapLibVector2dRegular) -> usize { sketch.rows * sketch.cols * std::mem::size_of::() - + sketch.heap * std::mem::size_of::() + + crate::wrappers::hh_heap_footprint(sketch.heap) } // ---------- insert / insert_step (FastPath) ---------- diff --git a/sketch-bench/src/wrappers/cs_heap.rs b/sketch-bench/src/wrappers/cs_heap.rs index 2a0df763..ccd43cdc 100644 --- a/sketch-bench/src/wrappers/cs_heap.rs +++ b/sketch-bench/src/wrappers/cs_heap.rs @@ -9,7 +9,6 @@ use crate::params::{CsHeapParams, ParamSet}; use crate::wrappers::cms_heap::sketchlib::{heap_capacity, top_k, TopkAnswer}; use crate::wrappers::frequency_value::FrequencyValue; use crate::wrappers::{require_positive, BuildError, Pass, QueryPass, Shared, StepPass}; -use asap_sketchlib::input::HHItem; use asap_sketchlib::{heap_item_to_sketch_input, CSHeap, FastPath, Vector2D}; use std::cell::RefCell; use std::rc::Rc; @@ -39,7 +38,7 @@ pub fn build_cs_heap_lib_vector2d_fast( /// Counter matrix plus a full heap, as `cms_heap` counts it. pub fn memory_cs_heap_lib_vector2d_fast(sketch: &CsHeapLibVector2dFast) -> usize { sketch.rows * sketch.cols * std::mem::size_of::() - + sketch.heap * std::mem::size_of::() + + crate::wrappers::hh_heap_footprint(sketch.heap) } pub fn insert_cs_heap_lib_vector2d_fast( diff --git a/sketch-bench/src/wrappers/hydra_cms/mod.rs b/sketch-bench/src/wrappers/hydra_cms/mod.rs index 995ef25b..6a01f62c 100644 --- a/sketch-bench/src/wrappers/hydra_cms/mod.rs +++ b/sketch-bench/src/wrappers/hydra_cms/mod.rs @@ -102,6 +102,24 @@ mod tests { fed(&mut built(), &record("a;x;z", 10)); } + /// A stream of mixed widths is refused at build, naming the variant and + /// both widths, before any record is timed. + #[test] + fn a_stream_of_mixed_widths_is_a_build_error() { + let params = ParamSet::of(&HydraCmsParams::canonical()); + let items = std::rc::Rc::new(vec![record("a;x", 1), record("a;x;z", 1)]); + let Err(err) = insert_hydra_cms::(¶ms, items, 1) else { + panic!("mixed widths must not build"); + }; + assert!( + err.0.contains("hydra-cms") + && err.0.contains("3 label(s)") + && err.0.contains("first 2"), + "{}", + err.0 + ); + } + /// An empty label is a value in its own column: it doesn't shift the /// labels after it. #[test] diff --git a/sketch-bench/src/wrappers/hydra_cms/sketchlib.rs b/sketch-bench/src/wrappers/hydra_cms/sketchlib.rs index a9a42e29..dc3a629d 100644 --- a/sketch-bench/src/wrappers/hydra_cms/sketchlib.rs +++ b/sketch-bench/src/wrappers/hydra_cms/sketchlib.rs @@ -65,7 +65,7 @@ pub fn insert_hydra_cms( let mut out = Vec::with_capacity(passes); for _ in 0..passes { // Built here, so calling the closure is the insert and nothing else. - let mut sketch = build_hydra_cms(params, label_columns(&items))?; + let mut sketch = build_hydra_cms(params, label_columns(&items, "hydra-cms")?)?; let items = items.clone(); out.push(Box::new(move || { for v in items.iter() { @@ -86,7 +86,7 @@ pub fn insert_step_hydra_cms( for _ in 0..passes { let sketch: Shared<_> = Rc::new(RefCell::new(build_hydra_cms( params, - label_columns(&items), + label_columns(&items, "hydra-cms")?, )?)); let (driven, read) = (sketch.clone(), sketch); let stream = items.clone(); @@ -201,7 +201,7 @@ fn hydra_cms_shards( ) -> Result<(HydraCms, Vec), BuildError> { let mut parts: Vec = Vec::new(); for shard in partition(items, shards) { - let mut sketch = build_hydra_cms(params, label_columns(items))?; + let mut sketch = build_hydra_cms(params, label_columns(items, "hydra-cms")?)?; for v in shard { update(&mut sketch.inner, &v.0, &v.1.data_input(), "hydra-cms"); } diff --git a/sketch-bench/src/wrappers/hydra_cs/sketchlib.rs b/sketch-bench/src/wrappers/hydra_cs/sketchlib.rs index 1ae832bf..554a3808 100644 --- a/sketch-bench/src/wrappers/hydra_cs/sketchlib.rs +++ b/sketch-bench/src/wrappers/hydra_cs/sketchlib.rs @@ -65,7 +65,7 @@ pub fn insert_hydra_cs( let mut out = Vec::with_capacity(passes); for _ in 0..passes { // Built here, so calling the closure is the insert and nothing else. - let mut sketch = build_hydra_cs(params, label_columns(&items))?; + let mut sketch = build_hydra_cs(params, label_columns(&items, "hydra-cs")?)?; let items = items.clone(); out.push(Box::new(move || { for v in items.iter() { @@ -84,8 +84,10 @@ pub fn insert_step_hydra_cs( ) -> Result, BuildError> { let mut out = Vec::with_capacity(passes); for _ in 0..passes { - let sketch: Shared<_> = - Rc::new(RefCell::new(build_hydra_cs(params, label_columns(&items))?)); + let sketch: Shared<_> = Rc::new(RefCell::new(build_hydra_cs( + params, + label_columns(&items, "hydra-cs")?, + )?)); let (driven, read) = (sketch.clone(), sketch); let stream = items.clone(); out.push(StepPass { @@ -199,7 +201,7 @@ fn hydra_cs_shards( ) -> Result<(HydraCs, Vec), BuildError> { let mut parts: Vec = Vec::new(); for shard in partition(items, shards) { - let mut sketch = build_hydra_cs(params, label_columns(items))?; + let mut sketch = build_hydra_cs(params, label_columns(items, "hydra-cs")?)?; for v in shard { update(&mut sketch.inner, &v.0, &v.1.data_input(), "hydra-cs"); } diff --git a/sketch-bench/src/wrappers/hydra_hll/sketchlib.rs b/sketch-bench/src/wrappers/hydra_hll/sketchlib.rs index 4e40da4e..fc4815c4 100644 --- a/sketch-bench/src/wrappers/hydra_hll/sketchlib.rs +++ b/sketch-bench/src/wrappers/hydra_hll/sketchlib.rs @@ -55,7 +55,7 @@ pub fn insert_hydra_hll( let mut out = Vec::with_capacity(passes); for _ in 0..passes { // Built here, so calling the closure is the insert and nothing else. - let mut sketch = build_hydra_hll(params, label_columns(&items))?; + let mut sketch = build_hydra_hll(params, label_columns(&items, "hydra-hll")?)?; let items = items.clone(); out.push(Box::new(move || { for v in items.iter() { @@ -76,7 +76,7 @@ pub fn insert_step_hydra_hll( for _ in 0..passes { let sketch: Shared<_> = Rc::new(RefCell::new(build_hydra_hll( params, - label_columns(&items), + label_columns(&items, "hydra-hll")?, )?)); let (driven, read) = (sketch.clone(), sketch); let stream = items.clone(); @@ -191,7 +191,7 @@ fn hydra_hll_shards( ) -> Result<(HydraHll, Vec), BuildError> { let mut parts: Vec = Vec::new(); for shard in partition(items, shards) { - let mut sketch = build_hydra_hll(params, label_columns(items))?; + let mut sketch = build_hydra_hll(params, label_columns(items, "hydra-hll")?)?; for v in shard { update(&mut sketch.inner, &v.0, &v.1.data_input(), "hydra-hll"); } diff --git a/sketch-bench/src/wrappers/hydra_kll/mod.rs b/sketch-bench/src/wrappers/hydra_kll/mod.rs index 70dd0de0..206d4452 100644 --- a/sketch-bench/src/wrappers/hydra_kll/mod.rs +++ b/sketch-bench/src/wrappers/hydra_kll/mod.rs @@ -28,7 +28,8 @@ const KLL_MAX_CACHEABLE_K: usize = crate::wrappers::kll::LIB_K_MAX as usize; /// Retained slots one KLL cell allocates at construction — `KLL::init` boxes a /// slice of this length once and never grows it. A line-for-line copy of the -/// library's private `compute_max_capacity`, so a claim about 0.2.2, not a bound. +/// library's private `compute_max_capacity` (unchanged from 0.2.2 to 0.3.0), so +/// a claim about the pinned version, not a bound. fn kll_cell_slots(k: u32) -> usize { // `init_internal` normalises before sizing: `m` floors `k`, and `k` is // capped. Reproduced so an out-of-range `k` reports the footprint the diff --git a/sketch-bench/src/wrappers/hydra_kll/sketchlib.rs b/sketch-bench/src/wrappers/hydra_kll/sketchlib.rs index f46062df..1c5060ae 100644 --- a/sketch-bench/src/wrappers/hydra_kll/sketchlib.rs +++ b/sketch-bench/src/wrappers/hydra_kll/sketchlib.rs @@ -69,7 +69,7 @@ pub fn insert_hydra_kll( let mut out = Vec::with_capacity(passes); for _ in 0..passes { // Built here, so calling the closure is the insert and nothing else. - let mut sketch = build_hydra_kll(params, label_columns(&items))?; + let mut sketch = build_hydra_kll(params, label_columns(&items, "hydra-kll")?)?; let items = items.clone(); out.push(Box::new(move || { for v in items.iter() { @@ -90,7 +90,7 @@ pub fn insert_step_hydra_kll( for _ in 0..passes { let sketch: Shared<_> = Rc::new(RefCell::new(build_hydra_kll( params, - label_columns(&items), + label_columns(&items, "hydra-kll")?, )?)); let (driven, read) = (sketch.clone(), sketch); let stream = items.clone(); @@ -205,7 +205,7 @@ fn hydra_kll_shards( ) -> Result<(HydraKll, Vec), BuildError> { let mut parts: Vec = Vec::new(); for shard in partition(items, shards) { - let mut sketch = build_hydra_kll(params, label_columns(items))?; + let mut sketch = build_hydra_kll(params, label_columns(items, "hydra-kll")?)?; for v in shard { update(&mut sketch.inner, &v.0, &v.1.data_input(), "hydra-kll"); } diff --git a/sketch-bench/src/wrappers/hydra_shared.rs b/sketch-bench/src/wrappers/hydra_shared.rs index d2df81a3..0521e338 100644 --- a/sketch-bench/src/wrappers/hydra_shared.rs +++ b/sketch-bench/src/wrappers/hydra_shared.rs @@ -10,11 +10,22 @@ pub(crate) fn labels(group: &[String]) -> Vec<&str> { group.iter().map(String::as_str).collect() } -/// The label columns of a `;`-joined record stream: its first record's, as -/// every record of one table carries the same columns. An empty label is a -/// column of its own. -pub(crate) fn label_columns(items: &[(String, V)]) -> usize { - items.first().map_or(1, |(key, _)| key.split(';').count()) +/// The label columns of a `;`-joined record stream, which every record must +/// share: a record of another width is a [`BuildError`] naming `variant` and +/// both widths. An empty label is a column of its own. +pub(crate) fn label_columns(items: &[(String, V)], variant: &str) -> Result { + let width = |key: &str| key.split(';').count(); + let Some((first, _)) = items.first() else { + return Ok(1); + }; + let columns = width(first); + match items.iter().find(|(key, _)| width(key) != columns) { + Some((key, _)) => Err(BuildError(format!( + "{variant}: record {key:?} has {} label(s), the stream's first {columns}", + width(key) + ))), + None => Ok(columns), + } } /// A grid over `label_columns` key columns, as asap_sketchlib 0.3 fixes @@ -26,17 +37,12 @@ pub(crate) fn new_hydra( cell: HydraCounter, variant: &str, ) -> Result { - if label_columns == 0 { - return Err(BuildError(format!( - "{variant}: a record needs at least one label column" - ))); - } let schema = (0..label_columns).map(|i| format!("label{i}")); Hydra::with_schema(rows, cols, schema, cell).map_err(|e| BuildError(format!("{variant}: {e}"))) } -/// Records one `;`-joined record, one value per key column in place. A -/// record of another width is refused. +/// Records one `;`-joined record, one value per key column in place. The +/// build already refused a stream of mixed widths; this is the backstop. pub(crate) fn update(h: &mut Hydra, key: &str, value: &DataInput, variant: &str) { let parts: Vec<&str> = key.split(';').collect(); if let Err(e) = h.update(&parts, value, None) { diff --git a/sketch-bench/src/wrappers/hydra_univmon/sketchlib.rs b/sketch-bench/src/wrappers/hydra_univmon/sketchlib.rs index f7f2e385..11c689fa 100644 --- a/sketch-bench/src/wrappers/hydra_univmon/sketchlib.rs +++ b/sketch-bench/src/wrappers/hydra_univmon/sketchlib.rs @@ -90,7 +90,7 @@ pub fn insert_hydra_univmon( let mut out = Vec::with_capacity(passes); for _ in 0..passes { // Built here, so calling the closure is the insert and nothing else. - let mut sketch = build_hydra_univmon(params, label_columns(&items))?; + let mut sketch = build_hydra_univmon(params, label_columns(&items, "hydra-univmon")?)?; let items = items.clone(); out.push(Box::new(move || { for v in items.iter() { @@ -111,7 +111,7 @@ pub fn insert_step_hydra_univmon( for _ in 0..passes { let sketch: Shared<_> = Rc::new(RefCell::new(build_hydra_univmon( params, - label_columns(&items), + label_columns(&items, "hydra-univmon")?, )?)); let (driven, read) = (sketch.clone(), sketch); let stream = items.clone(); @@ -356,7 +356,7 @@ fn hydra_univmon_shards( ) -> Result<(HydraUnivmon, Vec), BuildError> { let mut parts: Vec = Vec::new(); for shard in partition(items, shards) { - let mut sketch = build_hydra_univmon(params, label_columns(items))?; + let mut sketch = build_hydra_univmon(params, label_columns(items, "hydra-univmon")?)?; for v in shard { update(&mut sketch.inner, &v.0, &v.1.data_input(), "hydra-univmon"); } diff --git a/sketch-bench/src/wrappers/mod.rs b/sketch-bench/src/wrappers/mod.rs index f2c7b616..39006635 100644 --- a/sketch-bench/src/wrappers/mod.rs +++ b/sketch-bench/src/wrappers/mod.rs @@ -222,3 +222,13 @@ pub(crate) fn require_resolved_shape( } Ok(()) } + +/// Bytes a top-k heap of `capacity` residents holds in asap_sketchlib 0.3: +/// the `HHItem` array, the digest column and the position index +/// ([`aqpbm_core::hh_heap_bytes`]). Integer keys own no further bytes. +pub fn hh_heap_footprint(capacity: usize) -> usize { + aqpbm_core::hh_heap_bytes( + capacity, + std::mem::size_of::(), + ) +} diff --git a/sketch-bench/src/wrappers/polars_shared.rs b/sketch-bench/src/wrappers/polars_shared.rs index 8e49e097..dcf6344e 100644 --- a/sketch-bench/src/wrappers/polars_shared.rs +++ b/sketch-bench/src/wrappers/polars_shared.rs @@ -262,9 +262,10 @@ impl PolarsQuantileCore { } } -/// The `;`-joined key of one label subset, in column order. This is the format -/// `Hydra::update` builds internally, reproduced so the baseline and the sketch -/// answer to the same key. +/// The `;`-joined key of one label subset, in column order: the subset key +/// asap_sketchlib 0.2.2's `Hydra::update` built, so the baseline matches a +/// value in any label column. 0.3.0's Hydra keys a subset by column, so the +/// two differ when label columns share a value domain. pub fn subset_key(parts: &[&str], mask: usize) -> String { let mut out = String::new(); for (j, part) in parts.iter().enumerate() { @@ -279,8 +280,8 @@ pub fn subset_key(parts: &[&str], mask: usize) -> String { } /// Expand one record into `(subset_key, value)` rows, one per non-empty subset -/// of its labels. Empty label parts are dropped, matching the library's -/// `split(';').filter(|s| !s.is_empty())`. +/// of its labels. Empty label parts are dropped, as asap_sketchlib 0.2.2's +/// Hydra did (0.3.0's keeps them in their column). pub fn fan_out(key: &str, value: &V, keys: &mut Vec, values: &mut Vec) { let parts: Vec<&str> = key.split(';').filter(|s| !s.is_empty()).collect(); for mask in 1..(1usize << parts.len()) { diff --git a/sketch-bench/src/wrappers/univmon/mod.rs b/sketch-bench/src/wrappers/univmon/mod.rs index 77efdd8c..3aec0464 100644 --- a/sketch-bench/src/wrappers/univmon/mod.rs +++ b/sketch-bench/src/wrappers/univmon/mod.rs @@ -137,7 +137,7 @@ mod tests { fn lib_footprint_is_the_layers_times_a_layer() { let sketch = build_univmon_lib(&small()).expect("canonical dimensions build"); let counters = (3 * 1024 + 3) * std::mem::size_of::(); - let heap = 1000 * std::mem::size_of::(); + let heap = crate::wrappers::hh_heap_footprint(1000); assert_eq!(memory_univmon_lib(&sketch), 4 * (counters + heap)); } diff --git a/sketch-bench/src/wrappers/univmon/sketchlib.rs b/sketch-bench/src/wrappers/univmon/sketchlib.rs index 0a8d44ab..42bd4a8b 100644 --- a/sketch-bench/src/wrappers/univmon/sketchlib.rs +++ b/sketch-bench/src/wrappers/univmon/sketchlib.rs @@ -2,7 +2,6 @@ use super::*; use crate::params::ParamSet; use crate::wrappers::partition; use crate::wrappers::{BuildError, Pass, QueryPass, Shared, StepPass}; -use asap_sketchlib::input::HHItem; use asap_sketchlib::UnivMon; use std::cell::RefCell; use std::rc::Rc; @@ -51,7 +50,7 @@ impl UnivMonLib { pub fn memory_univmon_lib(sketch: &UnivMonLib) -> usize { let p = &sketch.params; let counters = (p.sketch_row * p.sketch_col + p.sketch_row) * std::mem::size_of::(); - let heap = p.heap_size * std::mem::size_of::(); + let heap = crate::wrappers::hh_heap_footprint(p.heap_size); p.layer_size * (counters + heap) }