diff --git a/datafusion/core/tests/dataframe/dataframe_functions.rs b/datafusion/core/tests/dataframe/dataframe_functions.rs index 4177fbebc6c3a..366e093787d56 100644 --- a/datafusion/core/tests/dataframe/dataframe_functions.rs +++ b/datafusion/core/tests/dataframe/dataframe_functions.rs @@ -19,7 +19,9 @@ use datafusion_common::test_util::batches_to_string; use datafusion_common::{DFSchema, ScalarValue}; use datafusion_expr::expr::Alias; use datafusion_expr::{ExprSchemable, LogicalPlanBuilder, table_scan}; -use datafusion_functions_aggregate::expr_fn::{approx_median, approx_percentile_cont}; +use datafusion_functions_aggregate::expr_fn::{ + approx_median, approx_percentile_cont, approx_top_k, +}; use datafusion_functions_nested::map::map; use insta::assert_snapshot; @@ -396,6 +398,27 @@ async fn test_fn_approx_median() -> Result<()> { Ok(()) } +#[tokio::test] +async fn test_fn_approx_top_k() -> Result<()> { + // Column b has values [1, 10, 10, 100] -- 10 appears twice, others once. + let expr = approx_top_k(col("b"), lit(1)); + + let df = create_test_table().await?; + let batches = df.aggregate(vec![], vec![expr]).unwrap().collect().await?; + + assert_snapshot!( + batches_to_string(&batches), + @r" + +-------------------------------+ + | approx_top_k(test.b,Int32(1)) | + +-------------------------------+ + | [{value: 10, count: 2}] | + +-------------------------------+ + "); + + Ok(()) +} + #[tokio::test] async fn test_fn_approx_percentile_cont() -> Result<()> { let expr = approx_percentile_cont(col("b").sort(true, false), lit(0.5), None); diff --git a/datafusion/functions-aggregate/Cargo.toml b/datafusion/functions-aggregate/Cargo.toml index 4cb08941e9014..60b923ff78d7b 100644 --- a/datafusion/functions-aggregate/Cargo.toml +++ b/datafusion/functions-aggregate/Cargo.toml @@ -69,6 +69,10 @@ name = "min_max_bytes" name = "approx_distinct" harness = false +[[bench]] +name = "approx_top_k" +harness = false + [[bench]] name = "first_last" harness = false diff --git a/datafusion/functions-aggregate/benches/approx_top_k.rs b/datafusion/functions-aggregate/benches/approx_top_k.rs new file mode 100644 index 0000000000000..0e59230d46a25 --- /dev/null +++ b/datafusion/functions-aggregate/benches/approx_top_k.rs @@ -0,0 +1,303 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership +// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements + +use std::hint::black_box; +use std::sync::Arc; + +use arrow::array::{ArrayRef, StringArray}; +use arrow::datatypes::{DataType, Field, Schema}; +use criterion::measurement::WallTime; +use criterion::{ + BatchSize, BenchmarkGroup, Criterion, Throughput, criterion_group, criterion_main, +}; +use datafusion_expr::function::AccumulatorArgs; +use datafusion_expr::{Accumulator, AggregateUDFImpl, EmitTo, GroupsAccumulator}; +use datafusion_functions_aggregate::approx_top_k::ApproxTopK; +use datafusion_physical_expr::expressions::{col, lit}; + +const ROWS: usize = 100_000; +const GROUPS: usize = 25_000; +const CHURN_GROUPS: usize = 1_000; + +fn with_accumulator_args( + data_type: DataType, + k: i64, + build: impl FnOnce(&ApproxTopK, AccumulatorArgs<'_>) -> T, +) -> T { + let schema = Arc::new(Schema::new(vec![Field::new( + "value", + data_type.clone(), + true, + )])); + let exprs = [col("value", &schema).unwrap(), lit(k)]; + let expr_fields = exprs + .iter() + .map(|expr| expr.return_field(&schema).unwrap()) + .collect::>(); + let function = ApproxTopK::new(); + let return_type = function.return_type(&[data_type, DataType::Int64]).unwrap(); + build( + &function, + AccumulatorArgs { + return_field: Arc::new(Field::new("result", return_type, true)), + schema: &schema, + expr_fields: &expr_fields, + ignore_nulls: false, + order_bys: &[], + is_reversed: false, + name: "approx_top_k(value, k)", + is_distinct: false, + exprs: &exprs, + }, + ) +} + +fn prepare_accumulator(data_type: DataType, k: i64) -> Box { + with_accumulator_args(data_type, k, |f, args| f.accumulator(args).unwrap()) +} + +fn prepare_groups_accumulator(data_type: DataType, k: i64) -> Box { + with_accumulator_args(data_type, k, |f, args| { + f.create_groups_accumulator(args).unwrap() + }) +} + +fn high_cardinality_values(offset: usize) -> ArrayRef { + Arc::new(StringArray::from_iter_values( + (offset..offset + ROWS).map(|row| format!("value_{row:08}")), + )) +} + +/// Skewed workload like top URL paths or top error codes: 90% of rows come +/// from 300 hot values (heavily skewed toward the first few) and 10% are +/// distinct tail values. At `k=1000` and `k=10000` all hot values fit in the +/// summary (~90% hits); at `k=10` (capacity 30) the tracked values cover +/// roughly 42% of rows. +fn skewed_values() -> ArrayRef { + const HOT_VALUES: f64 = 300.0; + let mut rng = 0x9e37_79b9_7f4a_7c15u64; + Arc::new(StringArray::from_iter_values((0..ROWS).map(|row| { + rng = rng + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1_442_695_040_888_963_407); + let random = rng >> 11; + if random.is_multiple_of(10) { + format!("value_{:08}", 1_000 + row) + } else { + let uniform = (random >> 4) as f64 / (1u64 << 49) as f64; + let hot = (uniform * uniform * uniform * HOT_VALUES) as usize; + format!("value_{hot:08}") + } + }))) +} + +fn bench_update_and_evaluate( + group: &mut BenchmarkGroup<'_, WallTime>, + values: &ArrayRef, + k: i64, +) { + group.bench_function(format!("update and evaluate utf8 k={k}"), |b| { + b.iter_batched( + || prepare_accumulator(DataType::Utf8, k), + |mut accumulator| { + accumulator + .update_batch(std::slice::from_ref(values)) + .unwrap(); + let result = accumulator.evaluate().unwrap(); + black_box((result, accumulator)) + }, + BatchSize::PerIteration, + ); + }); +} + +fn bench_grouped( + group: &mut BenchmarkGroup<'_, WallTime>, + values: &ArrayRef, + total_groups: usize, + k: i64, +) { + let groups: Vec = (0..ROWS).map(|row| row % total_groups).collect(); + group.bench_function(format!("utf8 {total_groups} groups k={k}"), |b| { + b.iter_batched( + || prepare_groups_accumulator(DataType::Utf8, k), + |mut accumulator| { + accumulator + .update_batch( + std::slice::from_ref(values), + &groups, + None, + total_groups, + ) + .unwrap(); + let result = accumulator.evaluate(EmitTo::All).unwrap(); + black_box((result, accumulator)) + }, + BatchSize::PerIteration, + ); + }); +} + +fn approx_top_k_benchmark(c: &mut Criterion) { + let values = high_cardinality_values(0); + let other_values = high_cardinality_values(ROWS / 2); + let mut group = c.benchmark_group("approx_top_k_high_cardinality"); + group.sample_size(10); + group.throughput(Throughput::Elements(ROWS as u64)); + for k in [10, 1_000, 10_000] { + bench_update_and_evaluate(&mut group, &values, k); + group.bench_function(format!("update only utf8 k={k}"), |b| { + b.iter_batched( + || prepare_accumulator(DataType::Utf8, k), + |mut accumulator| { + accumulator + .update_batch(std::slice::from_ref(&values)) + .unwrap(); + black_box(accumulator) + }, + BatchSize::PerIteration, + ); + }); + } + group.finish(); + + let mut group = c.benchmark_group("approx_top_k_grouped"); + group.sample_size(10); + group.throughput(Throughput::Elements(ROWS as u64)); + for (total_groups, k) in [ + (ROWS, 10), + (GROUPS, 10), + (CHURN_GROUPS, 10), + (CHURN_GROUPS, 10_000), + ] { + bench_grouped(&mut group, &values, total_groups, k); + } + // Final stage after partial aggregation was skipped: one state per row. + let groups: Vec = (0..ROWS).map(|row| row % CHURN_GROUPS).collect(); + for k in [10, 10_000] { + let states = prepare_groups_accumulator(DataType::Utf8, k) + .convert_to_state(std::slice::from_ref(&values), None) + .unwrap(); + group.bench_function( + format!("merge converted utf8 {CHURN_GROUPS} groups k={k}"), + |b| { + b.iter_batched( + || prepare_groups_accumulator(DataType::Utf8, k), + |mut accumulator| { + accumulator + .merge_batch(&states, &groups, CHURN_GROUPS) + .unwrap(); + let result = accumulator.evaluate(EmitTo::All).unwrap(); + black_box((result, accumulator)) + }, + BatchSize::PerIteration, + ); + }, + ); + } + group.finish(); + + let skewed = skewed_values(); + let mut group = c.benchmark_group("approx_top_k_skewed"); + group.sample_size(10); + group.throughput(Throughput::Elements(ROWS as u64)); + for k in [10, 1_000, 10_000] { + bench_update_and_evaluate(&mut group, &skewed, k); + } + for (total_groups, k) in [(GROUPS, 10), (CHURN_GROUPS, 10), (CHURN_GROUPS, 10_000)] { + bench_grouped(&mut group, &skewed, total_groups, k); + } + group.finish(); + + let mut group = c.benchmark_group("approx_top_k_state"); + group.sample_size(10); + let converter = prepare_groups_accumulator(DataType::Utf8, 10); + group.bench_function("convert_to_state utf8", |b| { + b.iter_batched( + || (), + |_| { + converter + .convert_to_state(std::slice::from_ref(&values), None) + .unwrap() + }, + BatchSize::PerIteration, + ); + }); + for k in [1_000, 10_000] { + let populated = |input: &ArrayRef| { + let mut accumulator = prepare_accumulator(DataType::Utf8, k); + accumulator + .update_batch(std::slice::from_ref(input)) + .unwrap(); + accumulator + }; + let mut accumulator = populated(&values); + group.bench_function(format!("state utf8 k={k}"), |b| { + b.iter_batched( + || (), + |_| accumulator.state().unwrap(), + BatchSize::PerIteration, + ); + }); + + let state = populated(&other_values) + .state() + .unwrap() + .iter() + .map(|state| state.to_array().unwrap()) + .collect::>(); + group.bench_function(format!("merge state into nonempty utf8 k={k}"), |b| { + b.iter_batched( + || populated(&values), + |mut accumulator| { + accumulator.merge_batch(&state).unwrap(); + black_box(accumulator) + }, + BatchSize::PerIteration, + ); + }); + } + for (total_groups, k) in [(GROUPS, 10), (CHURN_GROUPS, 10)] { + let groups: Vec = (0..ROWS).map(|row| row % total_groups).collect(); + let state_groups: Vec = (0..total_groups).collect(); + let populated = || { + let mut accumulator = prepare_groups_accumulator(DataType::Utf8, k); + accumulator + .update_batch(std::slice::from_ref(&values), &groups, None, total_groups) + .unwrap(); + accumulator + }; + group.bench_function(format!("state utf8 {total_groups} groups k={k}"), |b| { + b.iter_batched( + populated, + |mut accumulator| { + let state = accumulator.state(EmitTo::All).unwrap(); + black_box((state, accumulator)) + }, + BatchSize::PerIteration, + ); + }); + + let state = populated().state(EmitTo::All).unwrap(); + group.bench_function( + format!("merge state utf8 {total_groups} groups k={k}"), + |b| { + b.iter_batched( + || prepare_groups_accumulator(DataType::Utf8, k), + |mut accumulator| { + accumulator + .merge_batch(&state, &state_groups, total_groups) + .unwrap(); + black_box(accumulator) + }, + BatchSize::PerIteration, + ); + }, + ); + } + group.finish(); +} + +criterion_group!(benches, approx_top_k_benchmark); +criterion_main!(benches); diff --git a/datafusion/functions-aggregate/src/approx_top_k.rs b/datafusion/functions-aggregate/src/approx_top_k.rs new file mode 100644 index 0000000000000..5289415224b06 --- /dev/null +++ b/datafusion/functions-aggregate/src/approx_top_k.rs @@ -0,0 +1,3399 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership +// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements + +//! Approximate top-k aggregate function using the Filtered Space-Saving algorithm. +//! +//! This implements a distributed-friendly approximate top-k aggregation using +//! the Filtered Space-Saving algorithm. The algorithm maintains a fixed-size summary +//! of counters plus an alpha map (filter) that estimates unmonitored items' +//! frequencies. +//! +//! Usage: `approx_top_k(column, k)` +//! - `column`: The column to find the most frequent values from +//! - `k`: The number of top elements to return (required, literal integer) +//! +//! Returns: `List, count: UInt64 }>` ranked by +//! estimated count, then by error, then by the value's encoded bytes so that +//! ties are deterministic (see `Counter` for the exact ordering). +//! +//! `count` is an *upper bound* on the true frequency: each counter also tracks +//! an `error` such that the true frequency lies in `[count - error, count]`. +//! A value tracked since it was first seen has `error == 0`; a value that +//! starts being tracked later (first seen after the summary filled up, or +//! evicted and seen again) inherits its filter bucket's estimate as `error`, +//! and merging full summaries may add an omission bound. +//! The `error` is used internally to break estimated-count ties but is not +//! exposed in the output. +//! +//! Algorithm references: +//! - Filtered Space-Saving: Homem, Carvalho. "Finding top-k elements in data +//! streams" (Information Sciences, 2010), +//! . Section 8 / equation (24) +//! gives the alpha map sizing used by `ALPHA_MAP_ELEMENTS_PER_COUNTER`. +//! - Parallel Space Saving: +//! - Space-Saving: Metwally, Agrawal, El Abbadi. "Efficient Computation of Frequent +//! and Top-k Elements in Data Streams" (ICDT 2005) + +use std::cmp::{Ordering, max, min}; +use std::hash::BuildHasher; +use std::mem::size_of; +use std::sync::Arc; + +use arrow::array::{ + Array, ArrayRef, AsArray, BinaryArray, BinaryViewArray, BinaryViewBuilder, + BooleanArray, BooleanBufferBuilder, Date32Array, Date64Array, Decimal32Array, + Decimal64Array, Decimal128Array, Decimal256Array, FixedSizeBinaryArray, Float32Array, + Float64Array, GenericByteArray, Int8Array, Int16Array, Int32Array, Int64Array, + LargeBinaryArray, LargeStringArray, ListArray, NullArray, OffsetSizeTrait, + PrimitiveArray, StringArray, StringViewArray, StringViewBuilder, StructArray, + Time32MillisecondArray, Time32SecondArray, Time64MicrosecondArray, + Time64NanosecondArray, TimestampMicrosecondArray, TimestampMillisecondArray, + TimestampNanosecondArray, TimestampSecondArray, UInt8Array, UInt16Array, UInt32Array, + UInt64Array, new_empty_array, +}; +use arrow::buffer::{NullBuffer, OffsetBuffer}; +use arrow::datatypes::{ + BinaryType, ByteArrayType, DataType, Date32Type, Date64Type, Decimal32Type, + Decimal64Type, Decimal128Type, Decimal256Type, Field, FieldRef, Fields, Float32Type, + Float64Type, Int8Type, Int16Type, Int32Type, Int64Type, LargeBinaryType, + LargeUtf8Type, Time32MillisecondType, Time32SecondType, Time64MicrosecondType, + Time64NanosecondType, TimeUnit, TimestampMicrosecondType, TimestampMillisecondType, + TimestampNanosecondType, TimestampSecondType, UInt8Type, UInt16Type, UInt32Type, + UInt64Type, Utf8Type, i256, +}; +use hashbrown::hash_table::Entry; +use hashbrown::{HashMap, HashTable}; + +use datafusion_common::float_semantics::normalize_float; +use datafusion_common::hash_utils::QualityRandomState; +use datafusion_common::types::{ + logical_boolean, logical_date, logical_float32, logical_float64, logical_string, +}; +use datafusion_common::{ + Result, ScalarValue, exec_datafusion_err, exec_err, internal_datafusion_err, + internal_err, not_impl_err, plan_datafusion_err, plan_err, resources_datafusion_err, +}; +use datafusion_expr::function::{AccumulatorArgs, StateFieldsArgs}; +use datafusion_expr::utils::{AggregateOrderSensitivity, format_state_name}; +use datafusion_expr::{ + Accumulator, AggregateUDFImpl, Coercion, DistinctHandling, Documentation, EmitTo, + GroupsAccumulator, Signature, TypeSignature, TypeSignatureClass, Volatility, +}; +use datafusion_functions_aggregate_common::aggregate::groups_accumulator::nulls::filter_to_nulls; +use datafusion_macros::user_doc; + +use crate::utils::get_scalar_value; + +make_udaf_expr_and_func!( + ApproxTopK, + approx_top_k, + expression k, + "Returns the approximate most frequent (top-k) values and their counts.", + approx_top_k_udaf +); + +// --------------------------------------------------------------------------- +// Algorithm constants +// --------------------------------------------------------------------------- + +/// Suggested constant from Homem & Carvalho, "Finding top-k elements in data +/// streams", section 8, equation (24). Determines the size of the alpha map +/// relative to the capacity. +const ALPHA_MAP_ELEMENTS_PER_COUNTER: usize = 6; + +/// Maximum allowed value for k in `approx_top_k(column, k)`. +const APPROX_TOP_K_MAX_K: usize = 10_000; + +/// Capacity multiplier for internal tracking. +/// +/// We track more items internally than k to improve accuracy. +/// If user asks for top-5, we internally track top `5 * 3 = 15` items. +const CAPACITY_MULTIPLIER: usize = 3; + +/// Fixed high-quality hash state used for both counter lookup and alpha buckets. +/// +/// The meaning of a filter `slot` in the intermediate state depends on `k`, +/// [`CAPACITY_MULTIPLIER`], [`ALPHA_MAP_ELEMENTS_PER_COUNTER`], and this seed. +/// None of them are stored in the state, so all partial summaries being merged +/// must come from the same configuration. +const APPROX_TOP_K_HASH_STATE: QualityRandomState = QualityRandomState::with_seed(0); + +// --------------------------------------------------------------------------- +// SpaceSavingSummary (core algorithm) +// --------------------------------------------------------------------------- + +/// Counter entry in the Filtered Space-Saving summary. +/// +/// Each entry tracks an item, its estimated count, and the error bound. +/// The algorithm guarantees that the true count lies within `[count - error, count]`. +/// +/// [`Ord`] ranks counters *best first*, so sorting a slice of counters yields +/// them in the order they should be reported. The ordering from the original +/// Filtered Space-Saving algorithm is: +/// +/// 1. Higher estimated `count` first. +/// 2. Then lower `error`. +/// 3. Then `item` bytes ascending. This last key only exists to make the +/// ordering *total*, which keeps `Ord` consistent with the derived [`Eq`] and +/// makes the reported top-k deterministic when counts tie. +#[derive(Debug, PartialEq, Eq)] +struct Counter { + /// The encoded bytes of the tracked value (see [`for_each_encoded_value`]). + item: Vec, + /// Hash of the item (cached to avoid recomputation). + hash: u64, + /// The estimated frequency count (may overestimate due to eviction handling). + count: u64, + /// The maximum possible overestimation (error bound). + error: u64, +} + +impl Ord for Counter { + fn cmp(&self, other: &Self) -> Ordering { + // Reversed on count so sorting places the best counter first. + other + .count + .cmp(&self.count) + .then_with(|| self.error.cmp(&other.error)) + .then_with(|| self.item.cmp(&other.item)) + } +} + +impl PartialOrd for Counter { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +/// The Filtered Space-Saving filter: one `alpha` cell per hash bucket, holding +/// an upper bound on the frequency of any unmonitored item in that bucket. +/// +/// The map starts empty (all cells read as zero) and stays sparse until enough +/// cells are populated for a dense `Vec` to use less memory, so summaries that +/// never filter or evict an item pay nothing for it. +#[derive(Debug, PartialEq, Eq)] +enum AlphaMap { + Empty, + Sparse(HashMap), + Dense(Vec), +} + +impl AlphaMap { + fn dense_threshold(slots: usize) -> usize { + max(8, slots / 4) + } + + /// Build a map directly from validated, non-zero `(slot, alpha)` pairs, + /// choosing the same representation incremental insertion would reach. + fn from_nonzero(slots: &[u32], alphas: &[u64], total_slots: usize) -> Result { + if slots.is_empty() { + Ok(Self::Empty) + } else if slots.len() >= Self::dense_threshold(total_slots) { + let mut dense = Vec::new(); + dense.try_reserve_exact(total_slots).map_err(|e| { + resources_datafusion_err!( + "approx_top_k: unable to allocate filter map: {e}" + ) + })?; + dense.resize(total_slots, 0); + for (&slot, &alpha) in slots.iter().zip(alphas) { + dense[slot as usize] = alpha; + } + Ok(Self::Dense(dense)) + } else { + let mut sparse = HashMap::new(); + sparse.try_reserve(slots.len()).map_err(|e| { + resources_datafusion_err!( + "approx_top_k: unable to allocate filter map: {e}" + ) + })?; + for (&slot, &alpha) in slots.iter().zip(alphas) { + sparse.insert(slot as usize, alpha); + } + Ok(Self::Sparse(sparse)) + } + } + + fn is_empty(&self) -> bool { + matches!(self, Self::Empty) + } + + fn get(&self, slot: usize) -> u64 { + match self { + Self::Empty => 0, + Self::Sparse(values) => values.get(&slot).copied().unwrap_or(0), + Self::Dense(values) => values[slot], + } + } + + /// Mutable access to the cell for `slot`, creating it if needed. `slots` + /// is the total number of cells, used to pick the representation. + fn cell_mut(&mut self, slot: usize, slots: usize) -> &mut u64 { + if let Self::Sparse(values) = self + && values.len() + 1 >= Self::dense_threshold(slots) + && !values.contains_key(&slot) + { + let mut dense = vec![0; slots]; + for (&slot, &value) in values.iter() { + dense[slot] = value; + } + *self = Self::Dense(dense); + } + if self.is_empty() { + *self = Self::Sparse(HashMap::new()); + } + match self { + Self::Empty => unreachable!("replaced above"), + Self::Sparse(values) => values.entry(slot).or_default(), + Self::Dense(values) => &mut values[slot], + } + } + + fn add(&mut self, slot: usize, increment: u64, slots: usize) { + if increment == 0 { + return; + } + let cell = self.cell_mut(slot, slots); + *cell = cell.saturating_add(increment); + } + + fn set(&mut self, slot: usize, value: u64, slots: usize) { + debug_assert_ne!(value, 0); + *self.cell_mut(slot, slots) = value; + } + + fn for_each(&self, mut visit: impl FnMut(usize, u64)) { + match self { + Self::Empty => {} + Self::Sparse(values) => { + for (&slot, &value) in values { + visit(slot, value); + } + } + Self::Dense(values) => { + for (slot, &value) in values.iter().enumerate() { + if value != 0 { + visit(slot, value); + } + } + } + } + } + + #[cfg(test)] + fn sorted_entries(&self) -> Vec<(usize, u64)> { + let mut entries = Vec::new(); + self.for_each(|slot, value| entries.push((slot, value))); + entries.sort_unstable_by_key(|&(slot, _)| slot); + entries + } + + /// Appends the non-zero cells to `slots` and `alphas` in slot order and + /// returns how many there are. + fn append_nonzero(&self, slots: &mut Vec, alphas: &mut Vec) -> usize { + let start = slots.len(); + match self { + Self::Empty => {} + Self::Sparse(values) => { + let mut entries: Vec<_> = values.iter().collect(); + entries.sort_unstable_by_key(|&(&slot, _)| slot); + slots.extend(entries.iter().map(|&(&slot, _)| slot as u32)); + alphas.extend(entries.iter().map(|&(_, &alpha)| alpha)); + } + Self::Dense(values) => { + // Every cell is written and only the non-zero ones are kept, + // because a branch per cell mispredicts on partly populated + // maps. The extra element takes the writes after the last + // non-zero cell. + let len = values.iter().filter(|&&alpha| alpha != 0).count(); + slots.resize(start + len + 1, 0); + alphas.resize(start + len + 1, 0); + let (out_slots, out_alphas) = (&mut slots[start..], &mut alphas[start..]); + let mut next = 0; + for (slot, &alpha) in values.iter().enumerate() { + out_slots[next] = slot as u32; + out_alphas[next] = alpha; + next += usize::from(alpha != 0); + } + slots.truncate(start + len); + alphas.truncate(start + len); + } + } + slots.len() - start + } + + fn allocation_size(&self) -> usize { + match self { + Self::Empty => 0, + Self::Sparse(values) => values.allocation_size(), + Self::Dense(values) => values.capacity() * size_of::(), + } + } +} + +/// Filtered Space-Saving algorithm summary for approximate top-k / heavy hitters. +/// +/// Uses a [`HashTable`] that stores `(hash, index)` tuples for O(1) counter +/// lookups without duplicating the key bytes. The actual item data lives in +/// `counters[index].item`. An [`AlphaMap`] estimates the frequencies of filtered +/// and evicted items. +/// +/// All heap buffers grow on demand. Nothing is pre-allocated from `k`, because +/// under `GROUP BY` there is one summary per group: eagerly sizing the alpha +/// map from `k` would cost +/// `next_power_of_two(k * CAPACITY_MULTIPLIER * ALPHA_MAP_ELEMENTS_PER_COUNTER) * 8` +/// bytes for every group, including singleton groups that never evict anything. +#[derive(Debug)] +struct SpaceSavingSummary { + counters: Vec, + /// Maps `(cached_hash, counter_index)`. Lookups use the cached hash for + /// the fast path and fall back to byte equality via the `counters` vec. + counter_map: HashTable<(u64, usize)>, + /// Counter indices in a min-heap ordered with the least desirable counter + /// at the root. Counter storage stays stable so hash-table indices remain + /// valid while heap entries move. + min_heap: Vec, + /// Reverse mapping from counter index to its position in `min_heap`. + heap_positions: Vec, + /// Frequency estimate for unmonitored items, indexed by `hash & (len - 1)`. + /// + /// Sparse until enough buckets are populated for a dense representation to + /// use less memory. An empty map reads as all-zero alphas. + alpha_map: AlphaMap, + /// Maximum number of counters (`k * CAPACITY_MULTIPLIER`). + requested_capacity: usize, + /// Running total of heap bytes owned by counter item `Vec`s. + /// Updated on push / evict / merge so that `size()` is O(1). + item_heap_bytes: usize, +} + +impl SpaceSavingSummary { + fn compute_alpha_map_size(capacity: usize) -> usize { + capacity + .saturating_mul(ALPHA_MAP_ELEMENTS_PER_COUNTER) + .next_power_of_two() + } + + /// Fixed high-quality hash for item bytes. + fn hash_item(item: &[u8]) -> u64 { + APPROX_TOP_K_HASH_STATE.hash_one(item) + } + + /// Create an empty summary that will track up to `capacity` counters. + /// + /// No heap allocation happens here; see the note on [`SpaceSavingSummary`]. + fn new(capacity: usize) -> Self { + debug_assert!( + capacity > 0, + "approx_top_k summary capacity must be positive" + ); + Self { + counters: Vec::new(), + counter_map: HashTable::new(), + min_heap: Vec::new(), + heap_positions: Vec::new(), + alpha_map: AlphaMap::Empty, + requested_capacity: capacity, + item_heap_bytes: 0, + } + } + + /// Read the alpha (historical evicted frequency) for `hash`. + /// + /// Returns 0 while the alpha map is still unallocated, which is the correct + /// value: nothing has been filtered or evicted yet. + fn alpha_for(&self, hash: u64) -> u64 { + self.alpha_map.get(self.alpha_slot(hash)) + } + + fn alpha_slots(&self) -> usize { + Self::compute_alpha_map_size(self.requested_capacity) + } + + fn alpha_slot(&self, hash: u64) -> usize { + (hash as usize) & (self.alpha_slots() - 1) + } + + fn add_alpha(&mut self, hash: u64, increment: u64) { + let slots = self.alpha_slots(); + let slot = self.alpha_slot(hash); + self.alpha_map.add(slot, increment, slots); + } + + /// Raise the filter bucket of `hash` to at least `count`, the estimate of a + /// value that stops being tracked (evicted, or dropped by a merge). + /// + /// Filtered Space-Saving assigns the evicted count. Within one stream a + /// bucket never exceeds the minimum tracked count, so taking the maximum is + /// the same; after merges a bucket can exceed it, and the maximum keeps the + /// bucket an upper bound for every untracked value in it. + fn raise_alpha(&mut self, hash: u64, count: u64) { + let slots = self.alpha_slots(); + let slot = self.alpha_slot(hash); + if count > self.alpha_map.get(slot) { + self.alpha_map.set(slot, count, slots); + } + } + + fn is_empty(&self) -> bool { + self.counters.is_empty() + } + + /// Whether every count is exact. A summary that never filled up has not + /// filtered or evicted anything, so its alpha map is all zero + /// ([`StateRows`] rejects states that violate this). + fn is_exact(&self) -> bool { + self.counters.len() < self.requested_capacity + } + + #[cfg(test)] + fn len(&self) -> usize { + self.counters.len() + } + + /// Find a counter by item bytes, using the pre-computed hash for fast + /// lookup and falling back to byte equality for collision resolution. + fn find_counter_idx(&self, item: &[u8], hash: u64) -> Option { + self.counter_map + .find(hash, |&(h, idx)| { + h == hash && self.counters[idx].item == item + }) + .map(|&(_, idx)| idx) + } + + /// Process one stream item using the original Filtered Space-Saving update. + fn add(&mut self, item: &[u8]) { + self.add_weighted(item, Self::hash_item(item), 1, 0); + } + + /// Filtered Space-Saving update for `count` occurrences of `item` whose + /// estimate already carries `error`. [`Self::add`] is the unit case. + #[inline] + fn add_weighted(&mut self, item: &[u8], hash: u64, count: u64, error: u64) { + // Fast path: item already tracked. + if let Some(idx) = self.find_counter_idx(item, hash) { + let counter = &mut self.counters[idx]; + counter.count = counter.count.saturating_add(count); + counter.error = counter.error.saturating_add(error); + self.repair_heap(idx); + return; + } + + // Below capacity: add directly. + if self.counters.len() < self.requested_capacity { + self.push_counter(item, hash, count, error); + return; + } + + // Filter an unmonitored item until its bucket estimate reaches the + // minimum tracked estimate. This is the defining admission rule of the + // original Filtered Space-Saving algorithm. + let alpha = self.alpha_for(hash); + let min_idx = self.min_heap[0]; + let min_count = self.counters[min_idx].count; + if alpha.saturating_add(count) < min_count { + self.add_alpha(hash, count); + return; + } + + let victim_hash = self.counters[min_idx].hash; + self.raise_alpha(victim_hash, min_count); + // Read alpha after recording the victim. When both values hash to the + // same bucket, this ordering is required by the original algorithm. + let admission_alpha = self.alpha_for(hash); + self.replace_min_counter( + item, + hash, + admission_alpha.saturating_add(count), + admission_alpha.saturating_add(error), + ); + } + + fn try_reserve_counters(&mut self, additional: usize) -> Result<()> { + let error = + |e| resources_datafusion_err!("approx_top_k: unable to grow counters: {e}"); + self.counters.try_reserve_exact(additional).map_err(error)?; + self.min_heap.try_reserve_exact(additional).map_err(error)?; + self.heap_positions + .try_reserve_exact(additional) + .map_err(error)?; + self.counter_map + .try_reserve(additional, |&(hash, _)| hash) + .map_err(|e| { + resources_datafusion_err!("approx_top_k: unable to grow counter map: {e}") + }) + } + + fn push_counter(&mut self, item: &[u8], hash: u64, count: u64, error: u64) { + self.push_owned_counter(Counter { + item: item.to_vec(), + hash, + count, + error, + }); + } + + fn push_owned_counter(&mut self, counter: Counter) { + let idx = self.counters.len(); + self.item_heap_bytes = + self.item_heap_bytes.saturating_add(counter.item.capacity()); + self.counter_map + .insert_unique(counter.hash, (counter.hash, idx), |&(h, _)| h); + self.counters.push(counter); + let heap_pos = self.min_heap.len(); + self.min_heap.push(idx); + self.heap_positions.push(heap_pos); + self.sift_up(heap_pos); + } + + fn replace_min_counter(&mut self, item: &[u8], hash: u64, count: u64, error: u64) { + let idx = self.min_heap[0]; + let old_hash = self.counters[idx].hash; + self.counter_map + .find_entry(old_hash, |&(_, counter_idx)| counter_idx == idx) + .expect("counter map must contain the minimum counter") + .remove(); + + let old_capacity = self.counters[idx].item.capacity(); + if old_capacity > max(1_024, item.len().saturating_mul(4)) { + self.counters[idx].item = item.to_vec(); + } else { + self.counters[idx].item.clear(); + self.counters[idx].item.extend_from_slice(item); + } + let new_capacity = self.counters[idx].item.capacity(); + self.item_heap_bytes = self + .item_heap_bytes + .saturating_sub(old_capacity) + .saturating_add(new_capacity); + self.counters[idx].hash = hash; + self.counters[idx].count = count; + self.counters[idx].error = error; + self.counter_map + .insert_unique(hash, (hash, idx), |&(h, _)| h); + self.sift_down(0); + } + + fn counter_is_worse(&self, left: usize, right: usize) -> bool { + self.counters[left] > self.counters[right] + } + + fn swap_heap_entries(&mut self, left: usize, right: usize) { + self.min_heap.swap(left, right); + self.heap_positions[self.min_heap[left]] = left; + self.heap_positions[self.min_heap[right]] = right; + } + + fn sift_up(&mut self, mut pos: usize) { + while pos != 0 { + let parent = (pos - 1) / 2; + if !self.counter_is_worse(self.min_heap[pos], self.min_heap[parent]) { + break; + } + self.swap_heap_entries(pos, parent); + pos = parent; + } + } + + fn sift_down(&mut self, mut pos: usize) { + loop { + let left = pos * 2 + 1; + if left >= self.min_heap.len() { + break; + } + let right = left + 1; + let mut worst = left; + if right < self.min_heap.len() + && self.counter_is_worse(self.min_heap[right], self.min_heap[left]) + { + worst = right; + } + if !self.counter_is_worse(self.min_heap[worst], self.min_heap[pos]) { + break; + } + self.swap_heap_entries(pos, worst); + pos = worst; + } + } + + fn repair_heap(&mut self, counter_idx: usize) { + let pos = self.heap_positions[counter_idx]; + if pos != 0 && self.counter_is_worse(counter_idx, self.min_heap[(pos - 1) / 2]) { + self.sift_up(pos); + } else { + self.sift_down(pos); + } + } + + fn rebuild_min_heap(&mut self) { + self.min_heap.clear(); + self.heap_positions.clear(); + self.min_heap.extend(0..self.counters.len()); + self.heap_positions.extend(0..self.counters.len()); + for pos in (0..self.min_heap.len() / 2).rev() { + self.sift_down(pos); + } + } + + /// Reduce candidates produced by a distributed merge. Streaming updates + /// never exceed capacity; merge is the only operation requiring reduction. + fn reduce_to_requested_capacity(&mut self) { + let k = self.requested_capacity; + if k >= self.counters.len() { + self.rebuild_min_heap(); + return; + } + + self.counters.select_nth_unstable(k - 1); + let alpha_slots = self.alpha_slots(); + let mask = alpha_slots - 1; + let mut released = 0usize; + for counter in &self.counters[k..] { + let slot = (counter.hash as usize) & mask; + if counter.count > self.alpha_map.get(slot) { + self.alpha_map.set(slot, counter.count, alpha_slots); + } + released = released.saturating_add(counter.item.capacity()); + } + self.item_heap_bytes = self.item_heap_bytes.saturating_sub(released); + self.counters.truncate(k); + self.rebuild_counter_map(); + self.rebuild_min_heap(); + } + + /// Rebuild the `counter_map` from the current `counters` vec. + fn rebuild_counter_map(&mut self) { + self.counter_map.clear(); + for (idx, counter) in self.counters.iter().enumerate() { + self.counter_map.insert_unique( + counter.hash, + (counter.hash, idx), + |&(h, _)| h, + ); + } + } + + #[cfg(test)] + fn get(&self, item: &[u8]) -> Option<(u64, u64)> { + self.find_counter_idx(item, Self::hash_item(item)) + .map(|idx| (self.counters[idx].count, self.counters[idx].error)) + } + + /// Borrow the `n` highest-ranked counters, sorted best-first. + /// + /// Because [`Counter`]'s ordering is total, the result is deterministic even + /// when counts and errors tie. + fn ranked_counters(&self, n: usize) -> Vec<&Counter> { + if n == 0 || self.counters.is_empty() { + return Vec::new(); + } + + let mut ranked: Vec<&Counter> = self.counters.iter().collect(); + let keep = min(ranked.len(), n); + + if keep < ranked.len() { + ranked.select_nth_unstable(keep - 1); + ranked.truncate(keep); + } + + ranked.sort_unstable(); + ranked + } + + /// Consume this summary and return up to `n` highest-ranked counters in + /// [`Counter`] order, sorting in place without allocating an extra `Vec`. + fn into_ranked_counters(mut self, n: usize) -> Vec { + let keep = min(self.counters.len(), n); + if keep == 0 { + return Vec::new(); + } + if keep < self.counters.len() { + self.counters.select_nth_unstable(keep - 1); + self.counters.truncate(keep); + } + self.counters.sort_unstable(); + self.counters + } + + /// Get the top-k items as `(item, count, error)` in [`Counter`] order. + #[cfg(test)] + fn top_k(&self, k: usize) -> Vec<(&[u8], u64, u64)> { + self.ranked_counters(k) + .into_iter() + .map(|c| (c.item.as_slice(), c.count, c.error)) + .collect() + } + + /// Merge another summary. + /// + /// An exact summary is just a multiset of observations, so it is folded + /// into the other one with [`Self::add_weighted`]. (Single-value state + /// rows, such as those produced by [`GroupsAccumulator::convert_to_state`], + /// go directly to `add_weighted` without building a summary.) + /// + /// Two full summaries are merged with the Parallel Space-Saving + /// reduce-and-combine algorithm from , + /// using each summary's Filtered Space-Saving alphas as omission bounds. + fn merge(&mut self, mut other: SpaceSavingSummary) -> Result<()> { + if other.is_empty() { + return Ok(()); + } + + if self.is_empty() { + *self = other; + return Ok(()); + } + + if self.is_exact() && !other.is_exact() { + std::mem::swap(self, &mut other); + } + if other.is_exact() { + // Best first, so that if this summary fills up, the values that + // keep exact counts are the most frequent ones. + other.counters.sort_unstable(); + for counter in &other.counters { + self.add_weighted( + &counter.item, + counter.hash, + counter.count, + counter.error, + ); + } + return Ok(()); + } + + // Both summaries are full. Reserve space for unmatched counters from + // `other` before mutating `self` so an allocation failure leaves `self` + // intact. Only `counters` grows; `counter_map` and `min_heap` are + // rebuilt after truncation back to `requested_capacity`. + let unmatched = other + .counters + .iter() + .filter(|counter| { + self.find_counter_idx(&counter.item, counter.hash).is_none() + }) + .count(); + if unmatched > 0 { + self.counters.try_reserve_exact(unmatched).map_err(|e| { + resources_datafusion_err!("approx_top_k: unable to grow counters: {e}") + })?; + } + + // A value that one summary does not track occurred in its input at most + // as often as the alpha of the value's bucket there, so that alpha is + // added as the omission bound. Common values combine directly. + for counter in &mut self.counters { + let (count, error) = match other.find_counter_idx(&counter.item, counter.hash) + { + Some(idx) => (other.counters[idx].count, other.counters[idx].error), + None => { + let bound = other.alpha_for(counter.hash); + (bound, bound) + } + }; + counter.count = counter.count.saturating_add(count); + counter.error = counter.error.saturating_add(error); + } + + // Add the values only `other` tracks, bounded by this summary's alphas + // (read before the alpha maps are combined below). + if unmatched > 0 { + for mut other_counter in other.counters { + if self + .find_counter_idx(&other_counter.item, other_counter.hash) + .is_none() + { + let bound = self.alpha_for(other_counter.hash); + other_counter.count = other_counter.count.saturating_add(bound); + other_counter.error = other_counter.error.saturating_add(bound); + self.item_heap_bytes = self + .item_heap_bytes + .saturating_add(other_counter.item.capacity()); + self.counters.push(other_counter); + } + } + } + + // Alpha buckets represent disjoint input partitions, so combine them + // additively. An unallocated map is the all-zero map. + if !other.alpha_map.is_empty() { + let alpha_slots = self.alpha_slots(); + other.alpha_map.for_each(|slot, other_alpha| { + self.alpha_map.add(slot, other_alpha, alpha_slots); + }); + } + + self.reduce_to_requested_capacity(); + Ok(()) + } + + /// Approximate heap bytes owned by this summary. O(1) thanks to + /// incremental `item_heap_bytes` tracking. + fn heap_size(&self) -> usize { + self.counters.capacity() * size_of::() + + self.min_heap.capacity() * size_of::() + + self.heap_positions.capacity() * size_of::() + + self.item_heap_bytes + + self.counter_map.allocation_size() + + self.alpha_map.allocation_size() + } +} + +// --------------------------------------------------------------------------- +// Intermediate state +// --------------------------------------------------------------------------- + +/// Fields of each `{value, count, error}` struct in the `counters` state +/// column, one per tracked value. +fn counter_struct_fields(value_type: DataType) -> Fields { + Fields::from(vec![ + // Nullable because `convert_to_state` reuses the input column directly + // and leaves nulls inside null state rows; non-null state rows must not + // contain null values. + Field::new("value", value_type, true), + Field::new("count", DataType::UInt64, false), + Field::new("error", DataType::UInt64, false), + ]) +} + +/// Fields of each `{slot, alpha}` struct in the `alpha` state column, one per +/// non-zero filter bucket. +fn alpha_struct_fields() -> Fields { + Fields::from(vec![ + Field::new("slot", DataType::UInt32, false), + Field::new("alpha", DataType::UInt64, false), + ]) +} + +/// Non-nullable list element field for a state column of structs, so Arrow +/// rejects struct-level nulls in list entries. +fn state_list_field(fields: Fields) -> FieldRef { + Arc::new(Field::new_list_field(DataType::Struct(fields), false)) +} + +fn map_offset_overflow( + result: std::result::Result, +) -> Result { + result.map_err(|e| { + exec_datafusion_err!("approx_top_k: array exceeds offset capacity: {e}") + }) +} + +fn offsets_from_lengths( + lengths: impl IntoIterator, +) -> Result> { + map_offset_overflow(OffsetBuffer::try_from_lengths(lengths)) +} + +fn corrupt_state(detail: impl std::fmt::Display) -> Result { + exec_err!("approx_top_k: corrupt intermediate state ({detail})") +} + +/// Builds the intermediate state columns, one row per summary. +/// +/// Copies encoded value bytes into an owned buffer as rows are pushed so +/// [`ApproxTopKGroupsAccumulator::state`] can drop each group's summary before +/// moving to the next one. +#[derive(Default)] +struct StateBuilder { + values: EncodedValues, + counts: Vec, + errors: Vec, + counter_lengths: Vec, + slots: Vec, + alphas: Vec, + alpha_lengths: Vec, +} + +impl StateBuilder { + fn with_row_capacity(rows: usize) -> Self { + Self { + counter_lengths: Vec::with_capacity(rows), + alpha_lengths: Vec::with_capacity(rows), + ..Self::default() + } + } + + fn for_summary(summary: &SpaceSavingSummary) -> Self { + let len = summary.counters.len(); + let bytes = summary.counters.iter().map(|c| c.item.len()).sum(); + Self { + values: EncodedValues::with_capacity(len, bytes), + counts: Vec::with_capacity(len), + errors: Vec::with_capacity(len), + counter_lengths: Vec::with_capacity(1), + alpha_lengths: Vec::with_capacity(1), + ..Self::default() + } + } + + fn push_row(&mut self, counters: &[Counter], alpha: &AlphaMap) { + self.counter_lengths.push(counters.len()); + for counter in counters { + self.values.push(&counter.item); + self.counts.push(counter.count); + self.errors.push(counter.error); + } + let buckets = alpha.append_nonzero(&mut self.slots, &mut self.alphas); + self.alpha_lengths.push(buckets); + } + + fn push_summary(&mut self, summary: &SpaceSavingSummary) { + self.push_row(&summary.counters, &summary.alpha_map); + } + + fn push_group(&mut self, group: &GroupSummary) { + match group { + GroupSummary::Empty => self.push_row(&[], &AlphaMap::Empty), + GroupSummary::Singleton(counter) => { + self.push_row(std::slice::from_ref(counter), &AlphaMap::Empty) + } + GroupSummary::Full(summary) => self.push_summary(summary), + } + } + + fn finish(self, value_type: &DataType) -> Result> { + let counter_fields = counter_struct_fields(value_type.clone()); + let alpha_fields = alpha_struct_fields(); + let counters = StructArray::try_new( + counter_fields.clone(), + vec![ + self.values.into_array(value_type)?, + Arc::new(UInt64Array::from(self.counts)), + Arc::new(UInt64Array::from(self.errors)), + ], + None, + )?; + let alpha = StructArray::try_new( + alpha_fields.clone(), + vec![ + Arc::new(UInt32Array::from(self.slots)), + Arc::new(UInt64Array::from(self.alphas)), + ], + None, + )?; + Ok(vec![ + Arc::new(ListArray::try_new( + state_list_field(counter_fields), + offsets_from_lengths(self.counter_lengths)?, + Arc::new(counters), + None, + )?), + Arc::new(ListArray::try_new( + state_list_field(alpha_fields), + offsets_from_lengths(self.alpha_lengths)?, + Arc::new(alpha), + None, + )?), + ]) + } +} + +/// One non-empty row of the intermediate state. +enum StateRow<'a> { + /// A summary of a single value, applied without building a + /// [`SpaceSavingSummary`]. Every non-null row of + /// [`GroupsAccumulator::convert_to_state`] has this form. + /// + /// Single-value rows can skip reading `alpha` because `capacity` is at + /// least [`CAPACITY_MULTIPLIER`] (3), so a row with one value is never full + /// and [`StateRows::try_new`] rejects any filter buckets on non-full rows. + Single { + item: &'a [u8], + count: u64, + error: u64, + }, + Summary(SpaceSavingSummary), +} + +/// The intermediate state passed to [`Accumulator::merge_batch`] or +/// [`GroupsAccumulator::merge_batch`], validated against the receiving +/// accumulator. +struct StateRows<'a> { + counters: &'a ListArray, + alpha: &'a ListArray, + capacity: usize, +} + +impl<'a> StateRows<'a> { + fn try_new( + states: &'a [ArrayRef], + value_type: &DataType, + capacity: usize, + ) -> Result { + debug_assert!(capacity > 1, "approx_top_k capacity must exceed 1"); + let [counters, alpha] = states else { + return internal_err!( + "approx_top_k expects 2 state columns, got {}", + states.len() + ); + }; + let counters_type = + DataType::List(state_list_field(counter_struct_fields(value_type.clone()))); + let alpha_type = DataType::List(state_list_field(alpha_struct_fields())); + if counters.data_type() != &counters_type || alpha.data_type() != &alpha_type { + return internal_err!( + "approx_top_k state has types {} and {}, expected {counters_type} and {alpha_type}", + counters.data_type(), + alpha.data_type() + ); + } + let (counters, alpha) = (counters.as_list::(), alpha.as_list::()); + if counters.len() != alpha.len() { + return corrupt_state(format_args!( + "state columns have {} and {} rows", + counters.len(), + alpha.len() + )); + } + for row in 0..counters.len() { + if counters.is_null(row) { + if alpha.is_valid(row) && alpha.value_length(row) != 0 { + return corrupt_state("filter buckets in a null summary"); + } + continue; + } + if alpha.is_null(row) { + return corrupt_state("missing filter buckets"); + } + let len = counters.value_length(row) as usize; + if len > capacity { + return corrupt_state(format_args!( + "{len} values exceed capacity {capacity}" + )); + } + if len < capacity && alpha.value_length(row) != 0 { + return corrupt_state("filter buckets in a summary that is not full"); + } + } + Ok(Self { + counters, + alpha, + capacity, + }) + } + + /// Calls `visit` for each non-null, non-empty row, in row order. + fn for_each( + &self, + mut visit: impl FnMut(usize, StateRow<'_>) -> Result<()>, + ) -> Result<()> { + let offsets = self.counters.value_offsets(); + let start = offsets[0] as usize; + let end = offsets[self.counters.len()] as usize; + // The arrays can be slices, so only visit the values their rows cover. + let entries = self.counters.values().as_struct().slice(start, end - start); + let counts = entries.column(1).as_primitive::(); + let errors = entries.column(2).as_primitive::(); + let alpha_offsets = self.alpha.value_offsets(); + let alpha_entries = self.alpha.values().as_struct(); + let alpha_slots = alpha_entries + .column(0) + .as_primitive::() + .values(); + let alpha_values = alpha_entries + .column(1) + .as_primitive::() + .values(); + let mut row = 0; + // Collects the counters of a row with more than one, until its last. + let mut pending = SpaceSavingSummary::new(self.capacity); + for_each_encoded_value(entries.column(0), |local, item| { + let offset = start + local; + while offsets[row + 1] as usize <= offset { + row += 1; + } + if self.counters.is_null(row) { + return Ok(()); + } + let Some(item) = item else { + return corrupt_state("null value"); + }; + let (count, error) = (counts.value(local), errors.value(local)); + if count == 0 || error > count { + return corrupt_state(format_args!( + "invalid count/error interval {count}/{error}" + )); + } + let row_end = offsets[row + 1] as usize; + let row_len = row_end - offsets[row] as usize; + if row_len == 1 && self.capacity > 1 { + return visit(row, StateRow::Single { item, count, error }); + } + + if pending.is_empty() { + pending.try_reserve_counters(row_len)?; + } + let hash = SpaceSavingSummary::hash_item(item); + let idx = pending.counters.len(); + match pending.counter_map.entry( + hash, + |&(h, existing)| h == hash && pending.counters[existing].item == item, + |&(h, _)| h, + ) { + Entry::Occupied(_) => return corrupt_state("duplicate value"), + Entry::Vacant(slot) => { + slot.insert((hash, idx)); + } + } + let item = item.to_vec(); + pending.item_heap_bytes = + pending.item_heap_bytes.saturating_add(item.capacity()); + pending.counters.push(Counter { + item, + hash, + count, + error, + }); + if offset + 1 < row_end { + return Ok(()); + } + let mut summary = + std::mem::replace(&mut pending, SpaceSavingSummary::new(self.capacity)); + summary.rebuild_min_heap(); + if row_len == self.capacity { + let (alpha_start, alpha_end) = + (alpha_offsets[row] as usize, alpha_offsets[row + 1] as usize); + summary.alpha_map = read_alpha( + &alpha_slots[alpha_start..alpha_end], + &alpha_values[alpha_start..alpha_end], + summary.alpha_slots(), + )?; + } + visit(row, StateRow::Summary(summary)) + }) + } +} + +fn read_alpha(slots: &[u32], alphas: &[u64], slot_count: usize) -> Result { + if slots.is_empty() { + return Ok(AlphaMap::Empty); + } + // Stored in strictly increasing slot order so duplicates can be + // rejected in a single pass. + let mut previous = None; + for (&slot, &alpha) in slots.iter().zip(alphas) { + let slot = slot as usize; + if slot >= slot_count || alpha == 0 || previous.is_some_and(|p| slot <= p) { + return corrupt_state(format_args!("invalid filter bucket {slot}")); + } + previous = Some(slot); + } + AlphaMap::from_nonzero(slots, alphas, slot_count) +} + +// --------------------------------------------------------------------------- +// ApproxTopK UDAF struct +// --------------------------------------------------------------------------- + +/// Approximate top-k UDAF using the Filtered Space-Saving algorithm. +#[user_doc( + doc_section(label = "Approximate Functions"), + description = r#"Returns the approximate most frequent (top-k) values with their estimated counts as a list of `{value, count}` structs. Values are ranked by estimated count, with lower-error estimates preferred when counts tie. + +Because the aggregate uses bounded memory, `count` is an upper-bound estimate. It is exact for a value that has been tracked since it was first seen. A value that starts being tracked later, because it was first seen after the summary filled up or because it was evicted and seen again, starts from an estimate of how often it may already have occurred, and distributed merging may add an omission bound from partitions where that value was not tracked. Values whose frequency is far from the top-k boundary are the ones reported reliably; ties and near-ties may be resolved arbitrarily. + +NULL values are skipped; an empty or all-NULL input returns an empty list `[]`. For float columns, -0.0 and +0.0 are treated as the same value, while different NaN representations are tracked separately. + +Supported input types are strings, binary (including fixed-size binary), booleans, integers, 32- and 64-bit floats, decimals, dates, times, and timestamps. `value` has the same type as `expression`, except that dictionary-encoded inputs are returned as their value type."#, + syntax_example = "approx_top_k(expression, k)", + sql_example = r#"```sql +> SELECT approx_top_k(column_name, 3) FROM table_name; ++-----------------------------------------------------------------------------+ +| approx_top_k(column_name,Int64(3)) | ++-----------------------------------------------------------------------------+ +| [{value: foo, count: 3}, {value: bar, count: 2}, {value: baz, count: 1}] | ++-----------------------------------------------------------------------------+ +```"#, + standard_argument(name = "expression",), + argument( + name = "k", + description = "The number of top elements to return. Must be a literal integer between 1 and 10,000." + ) +)] +#[derive(Debug, PartialEq, Eq, Hash)] +pub struct ApproxTopK { + signature: Signature, +} + +impl Default for ApproxTopK { + fn default() -> Self { + Self::new() + } +} + +impl ApproxTopK { + /// Creates a new [`ApproxTopK`] aggregate function. + pub fn new() -> Self { + let with_integer_k = |value| { + TypeSignature::Coercible(vec![ + Coercion::new_exact(value), + Coercion::new_exact(TypeSignatureClass::Integer), + ]) + }; + let variants = vec![ + with_integer_k(TypeSignatureClass::Native(logical_string())), + with_integer_k(TypeSignatureClass::Binary), + with_integer_k(TypeSignatureClass::Native(logical_boolean())), + with_integer_k(TypeSignatureClass::Integer), + with_integer_k(TypeSignatureClass::Native(logical_float32())), + with_integer_k(TypeSignatureClass::Native(logical_float64())), + with_integer_k(TypeSignatureClass::Decimal), + with_integer_k(TypeSignatureClass::Native(logical_date())), + with_integer_k(TypeSignatureClass::Time), + with_integer_k(TypeSignatureClass::Timestamp), + ]; + + Self { + signature: Signature::one_of(variants, Volatility::Immutable), + } + } +} + +/// Evaluate and validate the constant `k` argument. +fn get_approx_top_k_k(args: &AccumulatorArgs) -> Result { + let [_, k_expr] = args.exprs else { + return internal_err!( + "approx_top_k expects 2 arguments, got {}", + args.exprs.len() + ); + }; + let k_value = get_scalar_value(k_expr).map_err(|_| { + plan_datafusion_err!( + "approx_top_k requires k to be a literal integer, got {k_expr}" + ) + })?; + // Widen to i128 so every signed and unsigned integer type shares the range + // check below. + let k = match k_value { + ScalarValue::Int8(Some(v)) => i128::from(v), + ScalarValue::Int16(Some(v)) => i128::from(v), + ScalarValue::Int32(Some(v)) => i128::from(v), + ScalarValue::Int64(Some(v)) => i128::from(v), + ScalarValue::UInt8(Some(v)) => i128::from(v), + ScalarValue::UInt16(Some(v)) => i128::from(v), + ScalarValue::UInt32(Some(v)) => i128::from(v), + ScalarValue::UInt64(Some(v)) => i128::from(v), + other => { + return plan_err!( + "approx_top_k requires k to be a literal integer, got {other}" + ); + } + }; + match usize::try_from(k) { + Ok(k) if (1..=APPROX_TOP_K_MAX_K).contains(&k) => Ok(k), + _ => plan_err!( + "approx_top_k requires k to be between 1 and {APPROX_TOP_K_MAX_K}, got {k}" + ), + } +} + +/// Fields of each `{value, count}` struct in the result list. +fn result_struct_fields(value_type: DataType) -> Fields { + Fields::from(vec![ + Field::new("value", value_type, true), + Field::new("count", DataType::UInt64, false), + ]) +} + +/// Field of the result `List`. +fn result_list_field(value_type: DataType) -> FieldRef { + Arc::new(Field::new_list_field( + DataType::Struct(result_struct_fields(value_type)), + true, + )) +} + +fn accumulator_params(args: &AccumulatorArgs) -> Result<(usize, DataType)> { + if args.is_distinct { + return not_impl_err!("approx_top_k does not support DISTINCT"); + } + let k = get_approx_top_k_k(args)?; + let data_type = args.expr_fields[0].data_type().clone(); + Ok((k, data_type)) +} + +impl AggregateUDFImpl for ApproxTopK { + fn name(&self) -> &str { + "approx_top_k" + } + + fn signature(&self) -> &Signature { + &self.signature + } + + fn return_type(&self, arg_types: &[DataType]) -> Result { + let Some(value_type) = arg_types.first() else { + return internal_err!("approx_top_k expects 2 arguments, got none"); + }; + // The signature matches on logical types, so it also accepts physical + // encodings (such as run-end encoding) that the sketch cannot store. + if !is_supported_value_type(value_type) { + return plan_err!("approx_top_k does not support input type {value_type}"); + } + Ok(DataType::List(result_list_field(value_type.clone()))) + } + + fn state_fields(&self, args: StateFieldsArgs) -> Result> { + let Some(value_field) = args.input_fields.first() else { + return internal_err!("approx_top_k expects 2 arguments, got none"); + }; + let value_type = value_field.data_type().clone(); + Ok(vec![ + Arc::new(Field::new( + format_state_name(args.name, "counters"), + DataType::List(state_list_field(counter_struct_fields(value_type))), + true, + )), + Arc::new(Field::new( + format_state_name(args.name, "alpha"), + DataType::List(state_list_field(alpha_struct_fields())), + true, + )), + ]) + } + + fn accumulator(&self, args: AccumulatorArgs) -> Result> { + let (k, data_type) = accumulator_params(&args)?; + Ok(Box::new(ApproxTopKAccumulator::new_with_data_type( + k, data_type, + ))) + } + + fn groups_accumulator_supported(&self, args: AccumulatorArgs) -> bool { + !args.is_distinct + } + + fn create_groups_accumulator( + &self, + args: AccumulatorArgs, + ) -> Result> { + let (k, data_type) = accumulator_params(&args)?; + Ok(Box::new(ApproxTopKGroupsAccumulator::new(k, data_type))) + } + + fn distinct_handling(&self) -> DistinctHandling { + DistinctHandling::Unsupported + } + + fn order_sensitivity(&self) -> AggregateOrderSensitivity { + AggregateOrderSensitivity::Insensitive + } + + /// An empty list, matching what [`Accumulator::evaluate`] returns for an + /// empty input. Used for empty window frames and decorrelated subqueries. + fn default_value(&self, data_type: &DataType) -> Result { + let DataType::List(field) = data_type else { + return internal_err!("approx_top_k must return a List, got {data_type}"); + }; + let list = ListArray::try_new( + Arc::clone(field), + OffsetBuffer::new_zeroed(1), + new_empty_array(field.data_type()), + None, + )?; + Ok(ScalarValue::List(Arc::new(list))) + } + + fn documentation(&self) -> Option<&Documentation> { + self.doc() + } +} + +// --------------------------------------------------------------------------- +// Accumulator +// --------------------------------------------------------------------------- + +/// Accumulator for `approx_top_k` using the Filtered Space-Saving algorithm. +#[derive(Debug)] +struct ApproxTopKAccumulator { + summary: SpaceSavingSummary, + k: usize, + /// The data type of the input column. + input_data_type: DataType, +} + +impl ApproxTopKAccumulator { + fn new_with_data_type(k: usize, input_data_type: DataType) -> Self { + let capacity = k * CAPACITY_MULTIPLIER; + Self { + summary: SpaceSavingSummary::new(capacity), + k, + input_data_type, + } + } +} + +/// Packed encoded values collected before building an Arrow value array. +/// +/// Storing the bytes contiguously lets byte arrays move the buffer straight +/// into Arrow without a second copy, and decouples the builder from the +/// lifetime of the summaries it read from. +#[derive(Default)] +struct EncodedValues { + bytes: Vec, + lengths: Vec, +} + +impl EncodedValues { + fn with_capacity(len: usize, byte_capacity: usize) -> Self { + Self { + bytes: Vec::with_capacity(byte_capacity), + lengths: Vec::with_capacity(len), + } + } + + fn push(&mut self, value: &[u8]) { + self.bytes.extend_from_slice(value); + self.lengths.push(value.len()); + } + + fn len(&self) -> usize { + self.lengths.len() + } + + fn iter(&self) -> impl Iterator { + let mut offset = 0; + self.lengths.iter().map(move |&len| { + let value = &self.bytes[offset..offset + len]; + offset += len; + value + }) + } + + /// Decode the collected values into an Arrow array of `data_type`. + /// + /// Every pushed value must have been encoded by [`for_each_encoded_value`] + /// for the same type. + fn into_array(self, data_type: &DataType) -> Result { + macro_rules! primitive { + ($arrow_type:ty, $native:ty) => {{ + const WIDTH: usize = size_of::<$native>(); + let mut values = Vec::with_capacity(self.len()); + for bytes in self.iter() { + let array = <[u8; WIDTH]>::try_from(bytes).map_err(|_| { + internal_datafusion_err!( + "approx_top_k: expected {WIDTH}-byte {data_type} value, got {} bytes", + bytes.len() + ) + })?; + values.push(<$native>::from_le_bytes(array)); + } + Arc::new( + PrimitiveArray::<$arrow_type>::new(values.into(), None) + .with_data_type(data_type.clone()), + ) as ArrayRef + }}; + } + + fn byte_array(values: EncodedValues) -> Result { + let offsets = offsets_from_lengths::(values.lengths)?; + Ok(Arc::new(GenericByteArray::::try_new( + offsets, + values.bytes.into(), + None, + )?)) + } + + let array = match data_type { + DataType::Null => Arc::new(NullArray::new(self.len())) as ArrayRef, + DataType::Boolean => { + let mut builder = BooleanBufferBuilder::new(self.len()); + for bytes in self.iter() { + match bytes { + [0] => builder.append(false), + [1] => builder.append(true), + _ => { + return internal_err!( + "approx_top_k: invalid encoded boolean value" + ); + } + } + } + Arc::new(BooleanArray::new(builder.finish(), None)) + } + DataType::Utf8 => byte_array::(self)?, + DataType::LargeUtf8 => byte_array::(self)?, + DataType::Utf8View => { + let mut builder = StringViewBuilder::with_capacity(self.len()); + for bytes in self.iter() { + let value = std::str::from_utf8(bytes).map_err(|_| { + internal_datafusion_err!( + "approx_top_k: encoded value is invalid UTF-8" + ) + })?; + builder.try_append_value(value)?; + } + Arc::new(builder.finish()) + } + DataType::Binary => byte_array::(self)?, + DataType::LargeBinary => byte_array::(self)?, + DataType::BinaryView => { + let mut builder = BinaryViewBuilder::with_capacity(self.len()); + for bytes in self.iter() { + builder.try_append_value(bytes)?; + } + Arc::new(builder.finish()) + } + DataType::FixedSizeBinary(size) => { + let width = usize::try_from(*size).map_err(|_| { + internal_datafusion_err!( + "approx_top_k: invalid FixedSizeBinary width {size}" + ) + })?; + if let Some(&actual) = self.lengths.iter().find(|&&len| len != width) { + return internal_err!( + "approx_top_k: expected {width}-byte {data_type} value, got {actual} bytes" + ); + } + Arc::new(FixedSizeBinaryArray::try_new_with_len( + *size, + self.bytes.into(), + None, + self.lengths.len(), + )?) + } + DataType::Int8 => primitive!(Int8Type, i8), + DataType::Int16 => primitive!(Int16Type, i16), + DataType::Int32 => primitive!(Int32Type, i32), + DataType::Int64 => primitive!(Int64Type, i64), + DataType::UInt8 => primitive!(UInt8Type, u8), + DataType::UInt16 => primitive!(UInt16Type, u16), + DataType::UInt32 => primitive!(UInt32Type, u32), + DataType::UInt64 => primitive!(UInt64Type, u64), + DataType::Float32 => primitive!(Float32Type, f32), + DataType::Float64 => primitive!(Float64Type, f64), + DataType::Decimal32(_, _) => primitive!(Decimal32Type, i32), + DataType::Decimal64(_, _) => primitive!(Decimal64Type, i64), + DataType::Decimal128(_, _) => primitive!(Decimal128Type, i128), + DataType::Decimal256(_, _) => primitive!(Decimal256Type, i256), + DataType::Date32 => primitive!(Date32Type, i32), + DataType::Date64 => primitive!(Date64Type, i64), + DataType::Time32(TimeUnit::Second) => primitive!(Time32SecondType, i32), + DataType::Time32(TimeUnit::Millisecond) => { + primitive!(Time32MillisecondType, i32) + } + DataType::Time64(TimeUnit::Microsecond) => { + primitive!(Time64MicrosecondType, i64) + } + DataType::Time64(TimeUnit::Nanosecond) => { + primitive!(Time64NanosecondType, i64) + } + DataType::Timestamp(TimeUnit::Second, _) => { + primitive!(TimestampSecondType, i64) + } + DataType::Timestamp(TimeUnit::Millisecond, _) => { + primitive!(TimestampMillisecondType, i64) + } + DataType::Timestamp(TimeUnit::Microsecond, _) => { + primitive!(TimestampMicrosecondType, i64) + } + DataType::Timestamp(TimeUnit::Nanosecond, _) => { + primitive!(TimestampNanosecondType, i64) + } + other => { + return internal_err!("approx_top_k: unsupported data type {other}"); + } + }; + Ok(array) + } +} + +/// Build the `List` result with one list per entry in +/// `lengths`, taking values and counts in order from `items` and `counts`. +fn build_result_list( + data_type: &DataType, + items: EncodedValues, + counts: Vec, + lengths: Vec, +) -> Result { + let fields = result_struct_fields(data_type.clone()); + let values = StructArray::try_new( + fields.clone(), + vec![ + items.into_array(data_type)?, + Arc::new(UInt64Array::from(counts)), + ], + None, + )?; + Ok(ListArray::try_new( + Arc::new(Field::new_list_field(DataType::Struct(fields), true)), + offsets_from_lengths(lengths)?, + Arc::new(values), + None, + )?) +} + +/// Whether the sketch can store values of `data_type`, which are the types +/// [`for_each_encoded_value`] and [`EncodedValues::into_array`] support. +fn is_supported_value_type(data_type: &DataType) -> bool { + matches!( + data_type, + DataType::Null + | DataType::Boolean + | DataType::Utf8 + | DataType::LargeUtf8 + | DataType::Utf8View + | DataType::Binary + | DataType::LargeBinary + | DataType::BinaryView + | DataType::FixedSizeBinary(0..) + | DataType::Int8 + | DataType::Int16 + | DataType::Int32 + | DataType::Int64 + | DataType::UInt8 + | DataType::UInt16 + | DataType::UInt32 + | DataType::UInt64 + | DataType::Float32 + | DataType::Float64 + | DataType::Decimal32(_, _) + | DataType::Decimal64(_, _) + | DataType::Decimal128(_, _) + | DataType::Decimal256(_, _) + | DataType::Date32 + | DataType::Date64 + | DataType::Time32(TimeUnit::Second | TimeUnit::Millisecond) + | DataType::Time64(TimeUnit::Microsecond | TimeUnit::Nanosecond) + | DataType::Timestamp(_, _) + ) +} + +/// Visit every row in `data_array` as `None` (null) or `Some(bytes)` in the +/// sketch's canonical encoding. +fn for_each_encoded_value(data_array: &ArrayRef, mut visit: F) -> Result<()> +where + F: FnMut(usize, Option<&[u8]>) -> Result<()>, +{ + macro_rules! visit_array { + ($array_type:ty, |$value:ident| $bytes:expr) => {{ + let Some(arr) = data_array.as_any().downcast_ref::<$array_type>() else { + return internal_err!( + "approx_top_k: failed to downcast array to {}", + stringify!($array_type) + ); + }; + for i in 0..arr.len() { + if arr.is_null(i) { + visit(i, None)?; + } else { + let $value = arr.value(i); + visit(i, Some($bytes))?; + } + } + }}; + } + + macro_rules! visit_le_bytes { + ($array_type:ty) => { + visit_array!($array_type, |v| &v.to_le_bytes()) + }; + } + + macro_rules! visit_bytes { + ($array_type:ty) => { + visit_array!($array_type, |v| v.as_ref()) + }; + } + + match data_array.data_type() { + DataType::Null => { + for row in 0..data_array.len() { + visit(row, None)?; + } + } + DataType::Boolean => visit_array!(BooleanArray, |v| &[u8::from(v)]), + DataType::Utf8 => visit_bytes!(StringArray), + DataType::LargeUtf8 => visit_bytes!(LargeStringArray), + DataType::Utf8View => visit_bytes!(StringViewArray), + DataType::Binary => visit_bytes!(BinaryArray), + DataType::LargeBinary => visit_bytes!(LargeBinaryArray), + DataType::BinaryView => visit_bytes!(BinaryViewArray), + DataType::FixedSizeBinary(_) => visit_bytes!(FixedSizeBinaryArray), + DataType::Int8 => visit_le_bytes!(Int8Array), + DataType::Int16 => visit_le_bytes!(Int16Array), + DataType::Int32 => visit_le_bytes!(Int32Array), + DataType::Int64 => visit_le_bytes!(Int64Array), + DataType::UInt8 => visit_le_bytes!(UInt8Array), + DataType::UInt16 => visit_le_bytes!(UInt16Array), + DataType::UInt32 => visit_le_bytes!(UInt32Array), + DataType::UInt64 => visit_le_bytes!(UInt64Array), + DataType::Float32 => { + visit_array!(Float32Array, |v| &normalize_float(v).to_le_bytes()) + } + DataType::Float64 => { + visit_array!(Float64Array, |v| &normalize_float(v).to_le_bytes()) + } + DataType::Decimal32(_, _) => visit_le_bytes!(Decimal32Array), + DataType::Decimal64(_, _) => visit_le_bytes!(Decimal64Array), + DataType::Decimal128(_, _) => visit_le_bytes!(Decimal128Array), + DataType::Decimal256(_, _) => visit_le_bytes!(Decimal256Array), + DataType::Date32 => visit_le_bytes!(Date32Array), + DataType::Date64 => visit_le_bytes!(Date64Array), + DataType::Time32(TimeUnit::Second) => visit_le_bytes!(Time32SecondArray), + DataType::Time32(TimeUnit::Millisecond) => { + visit_le_bytes!(Time32MillisecondArray) + } + DataType::Time64(TimeUnit::Microsecond) => { + visit_le_bytes!(Time64MicrosecondArray) + } + DataType::Time64(TimeUnit::Nanosecond) => visit_le_bytes!(Time64NanosecondArray), + DataType::Timestamp(unit, _) => match unit { + TimeUnit::Second => visit_le_bytes!(TimestampSecondArray), + TimeUnit::Millisecond => visit_le_bytes!(TimestampMillisecondArray), + TimeUnit::Microsecond => visit_le_bytes!(TimestampMicrosecondArray), + TimeUnit::Nanosecond => visit_le_bytes!(TimestampNanosecondArray), + }, + other => return internal_err!("approx_top_k: unsupported data type {other}"), + } + Ok(()) +} + +impl Accumulator for ApproxTopKAccumulator { + fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> { + if values.is_empty() { + return Ok(()); + } + for_each_encoded_value(&values[0], |_, bytes| { + if let Some(bytes) = bytes { + self.summary.add(bytes); + } + Ok(()) + }) + } + + fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> { + let capacity = self.summary.requested_capacity; + StateRows::try_new(states, &self.input_data_type, capacity)?.for_each( + |_, state| match state { + StateRow::Single { item, count, error } => { + let hash = SpaceSavingSummary::hash_item(item); + self.summary.add_weighted(item, hash, count, error); + Ok(()) + } + StateRow::Summary(summary) => self.summary.merge(summary), + }, + ) + } + + fn evaluate(&mut self) -> Result { + let ranked = self.summary.ranked_counters(self.k); + let total_bytes = ranked.iter().map(|c| c.item.len()).sum(); + let mut items = EncodedValues::with_capacity(ranked.len(), total_bytes); + let mut counts = Vec::with_capacity(ranked.len()); + for counter in ranked { + items.push(&counter.item); + counts.push(counter.count); + } + let lengths = vec![items.len()]; + let list = build_result_list(&self.input_data_type, items, counts, lengths)?; + Ok(ScalarValue::List(Arc::new(list))) + } + + fn state(&mut self) -> Result> { + let mut state = StateBuilder::for_summary(&self.summary); + state.push_summary(&self.summary); + state + .finish(&self.input_data_type)? + .iter() + .map(|column| ScalarValue::try_from_array(column, 0)) + .collect() + } + + fn size(&self) -> usize { + size_of::() + self.summary.heap_size() + } +} + +#[derive(Debug)] +enum GroupSummary { + Empty, + Singleton(Counter), + Full(Box), +} + +impl GroupSummary { + fn heap_size(&self) -> usize { + match self { + Self::Empty => 0, + Self::Singleton(counter) => counter.item.capacity(), + Self::Full(summary) => size_of::() + summary.heap_size(), + } + } + + fn add(&mut self, item: &[u8], capacity: usize) { + self.add_weighted(item, 1, 0, capacity); + } + + fn summary_mut(&mut self, capacity: usize) -> &mut SpaceSavingSummary { + if !matches!(self, Self::Full(_)) { + let mut summary = SpaceSavingSummary::new(capacity); + if let Self::Singleton(counter) = std::mem::replace(self, Self::Empty) { + summary.push_owned_counter(counter); + } + *self = Self::Full(Box::new(summary)); + } + let Self::Full(summary) = self else { + unreachable!("replaced above") + }; + summary + } + + /// See [`SpaceSavingSummary::add_weighted`]. + fn add_weighted(&mut self, item: &[u8], count: u64, error: u64, capacity: usize) { + let hash = SpaceSavingSummary::hash_item(item); + match self { + Self::Empty => { + *self = Self::Singleton(Counter { + item: item.to_vec(), + hash, + count, + error, + }); + } + Self::Singleton(counter) if counter.hash == hash && counter.item == item => { + counter.count = counter.count.saturating_add(count); + counter.error = counter.error.saturating_add(error); + } + _ => self + .summary_mut(capacity) + .add_weighted(item, hash, count, error), + } + } + + fn merge(&mut self, other: SpaceSavingSummary, capacity: usize) -> Result<()> { + if other.is_empty() { + return Ok(()); + } + if matches!(self, Self::Empty) { + *self = Self::Full(Box::new(other)); + return Ok(()); + } + self.summary_mut(capacity).merge(other) + } +} + +#[derive(Debug)] +struct ApproxTopKGroupsAccumulator { + summaries: Vec, + allocated_bytes: usize, + k: usize, + input_data_type: DataType, +} + +impl ApproxTopKGroupsAccumulator { + fn new(k: usize, input_data_type: DataType) -> Self { + Self { + summaries: vec![], + allocated_bytes: 0, + k, + input_data_type, + } + } + + fn capacity(&self) -> usize { + self.k * CAPACITY_MULTIPLIER + } + + fn ensure_groups(&mut self, total_num_groups: usize) { + if total_num_groups > self.summaries.len() { + self.summaries + .resize_with(total_num_groups, || GroupSummary::Empty); + } + } + + fn update_allocated_bytes(&mut self, before: usize, after: usize) { + if after >= before { + self.allocated_bytes = self.allocated_bytes.saturating_add(after - before); + } else { + self.allocated_bytes = self.allocated_bytes.saturating_sub(before - after); + } + } + + fn take_groups(&mut self, emit_to: EmitTo) -> Vec { + let groups = emit_to.take_needed(&mut self.summaries); + match emit_to { + EmitTo::All => { + debug_assert_eq!( + self.allocated_bytes, + groups.iter().map(GroupSummary::heap_size).sum::() + ); + self.allocated_bytes = 0; + } + EmitTo::First(_) => { + let freed = groups.iter().map(GroupSummary::heap_size).sum(); + self.allocated_bytes = self.allocated_bytes.saturating_sub(freed); + } + } + groups + } +} + +impl GroupsAccumulator for ApproxTopKGroupsAccumulator { + fn update_batch( + &mut self, + values: &[ArrayRef], + group_indices: &[usize], + opt_filter: Option<&BooleanArray>, + total_num_groups: usize, + ) -> Result<()> { + self.ensure_groups(total_num_groups); + let capacity = self.capacity(); + for_each_encoded_value(&values[0], |row, item| { + let included = + opt_filter.is_none_or(|filter| filter.is_valid(row) && filter.value(row)); + if included && let Some(item) = item { + let group = group_indices[row]; + let before = self.summaries[group].heap_size(); + self.summaries[group].add(item, capacity); + let after = self.summaries[group].heap_size(); + self.update_allocated_bytes(before, after); + } + Ok(()) + }) + } + + fn merge_batch( + &mut self, + values: &[ArrayRef], + group_indices: &[usize], + total_num_groups: usize, + ) -> Result<()> { + self.ensure_groups(total_num_groups); + let capacity = self.capacity(); + StateRows::try_new(values, &self.input_data_type, capacity)?.for_each( + |row, state| { + let group = group_indices[row]; + let before = self.summaries[group].heap_size(); + let result = match state { + StateRow::Single { item, count, error } => { + self.summaries[group].add_weighted(item, count, error, capacity); + Ok(()) + } + StateRow::Summary(summary) => { + self.summaries[group].merge(summary, capacity) + } + }; + let after = self.summaries[group].heap_size(); + self.update_allocated_bytes(before, after); + result + }, + ) + } + + fn evaluate(&mut self, emit_to: EmitTo) -> Result { + let groups = self.take_groups(emit_to); + let total_items: usize = groups + .iter() + .map(|group| match group { + GroupSummary::Empty => 0, + GroupSummary::Singleton(_) => usize::from(self.k != 0), + GroupSummary::Full(summary) => min(summary.counters.len(), self.k), + }) + .sum(); + let mut lengths = Vec::with_capacity(groups.len()); + let mut items = EncodedValues::with_capacity(total_items, 0); + let mut counts = Vec::with_capacity(total_items); + for group in groups { + match group { + GroupSummary::Empty => lengths.push(0), + GroupSummary::Singleton(counter) if self.k != 0 => { + lengths.push(1); + items.push(&counter.item); + counts.push(counter.count); + } + GroupSummary::Singleton(_) => lengths.push(0), + GroupSummary::Full(summary) => { + let ranked = summary.into_ranked_counters(self.k); + lengths.push(ranked.len()); + for counter in ranked { + items.push(&counter.item); + counts.push(counter.count); + } + } + } + } + let list = build_result_list(&self.input_data_type, items, counts, lengths)?; + Ok(Arc::new(list)) + } + + fn state(&mut self, emit_to: EmitTo) -> Result> { + let groups = self.take_groups(emit_to); + let mut state = StateBuilder::with_row_capacity(groups.len()); + for group in groups { + state.push_group(&group); + } + state.finish(&self.input_data_type) + } + + fn convert_to_state( + &self, + values: &[ArrayRef], + opt_filter: Option<&BooleanArray>, + ) -> Result> { + let input = &values[0]; + let rows = input.len(); + let counter_fields = counter_struct_fields(self.input_data_type.clone()); + let alpha_fields = alpha_struct_fields(); + // Each row becomes a summary of its value seen once. The input array is + // used as the values without copying it; null and filtered rows are + // null states. + let counters = StructArray::try_new( + counter_fields.clone(), + vec![ + Arc::clone(input), + Arc::new(UInt64Array::from_value(1, rows)), + Arc::new(UInt64Array::from_value(0, rows)), + ], + None, + )?; + let nulls = NullBuffer::union( + opt_filter.map(filter_to_nulls).as_ref(), + input.logical_nulls().as_ref(), + ); + let counters = ListArray::try_new( + state_list_field(counter_fields), + map_offset_overflow(OffsetBuffer::try_from_repeated_length(1, rows))?, + Arc::new(counters), + nulls, + )?; + let alpha = ListArray::try_new( + state_list_field(alpha_fields.clone()), + map_offset_overflow(OffsetBuffer::try_new_zeroed(rows))?, + new_empty_array(&DataType::Struct(alpha_fields)), + None, + )?; + Ok(vec![Arc::new(counters), Arc::new(alpha)]) + } + + fn size(&self) -> usize { + self.summaries.capacity() * size_of::() + self.allocated_bytes + } +} + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_space_saving_basic() { + let mut summary = SpaceSavingSummary::new(3); + + summary.add(b"apple"); + summary.add(b"apple"); + summary.add(b"apple"); + summary.add(b"banana"); + summary.add(b"banana"); + summary.add(b"cherry"); + + let (count, error) = summary.get(b"apple").unwrap(); + assert_eq!(count, 3); + assert_eq!(error, 0); + + let (count, error) = summary.get(b"banana").unwrap(); + assert_eq!(count, 2); + assert_eq!(error, 0); + + let (count, error) = summary.get(b"cherry").unwrap(); + assert_eq!(count, 1); + assert_eq!(error, 0); + + let top = summary.top_k(3); + assert_eq!(top.len(), 3); + assert_eq!(top[0].0, b"apple"); + assert_eq!(top[0].1, 3); + assert_eq!(top[1].0, b"banana"); + assert_eq!(top[1].1, 2); + assert_eq!(top[2].0, b"cherry"); + assert_eq!(top[2].1, 1); + } + + #[test] + fn test_space_saving_eviction() { + let mut summary = SpaceSavingSummary::new(2); + + for _ in 0..100 { + summary.add(b"frequent"); + } + + // Distinct values exercise filtering, eviction, and key-buffer reuse. + for i in 0..63u64 { + let item = format!("rare_{i}"); + summary.add(item.as_bytes()); + } + + assert_eq!(summary.len(), 2); + + // The dominant item is retained with an exact count: it was never + // evicted, so it carries no error. + let (count, error) = summary.get(b"frequent").unwrap(); + assert_eq!(count, 100); + assert_eq!(error, 0); + + // Exactly one rare candidate survives alongside it. + let survivors: Vec = (0..63u64) + .map(|i| format!("rare_{i}")) + .filter(|item| summary.get(item.as_bytes()).is_some()) + .collect(); + assert_eq!(survivors.len(), 1); + + // Eviction is what allocates the alpha map. + assert!(!summary.alpha_map.is_empty()); + } + + /// The filter must reject weak candidates and admit one once its bucket + /// estimate reaches the minimum tracked frequency. + #[test] + fn test_alpha_filter_controls_admission() { + let mut summary = SpaceSavingSummary::new(2); + for _ in 0..3 { + summary.add(b"a"); + summary.add(b"b"); + } + + let candidate = b"candidate"; + let candidate_hash = SpaceSavingSummary::hash_item(candidate); + summary.add(candidate); + assert!(summary.get(candidate).is_none()); + assert_eq!(summary.alpha_for(candidate_hash), 1); + + summary.add(candidate); + assert!(summary.get(candidate).is_none()); + assert_eq!(summary.alpha_for(candidate_hash), 2); + + summary.add(candidate); + assert_eq!(summary.get(candidate), Some((3, 2))); + assert_eq!(summary.len(), 2); + } + + #[test] + fn test_same_bucket_replacement_uses_evicted_estimate() { + let mut summary = SpaceSavingSummary::new(1); + for _ in 0..3 { + summary.add(b"victim"); + } + + let victim_slot = summary.alpha_slot(SpaceSavingSummary::hash_item(b"victim")); + let candidate = (0..1_000_000u64) + .map(|i| format!("candidate_{i}")) + .find(|candidate| { + summary.alpha_slot(SpaceSavingSummary::hash_item(candidate.as_bytes())) + == victim_slot + }) + .expect("should find an item in the victim's alpha bucket"); + + summary.add(candidate.as_bytes()); + summary.add(candidate.as_bytes()); + assert!(summary.get(candidate.as_bytes()).is_none()); + + summary.add(candidate.as_bytes()); + // The victim assignment changes alpha from 2 to 3 before insertion. + assert_eq!(summary.get(candidate.as_bytes()), Some((4, 3))); + assert_eq!( + summary.alpha_for(SpaceSavingSummary::hash_item(b"victim")), + 3 + ); + } + + /// Once eviction has happened the reported counts are genuine upper-bound + /// estimates rather than exact frequencies. + #[test] + fn test_counts_are_upper_bounds_after_eviction() { + const TRUE_FREQUENCY: u64 = 3; + let mut summary = SpaceSavingSummary::new(2); + + for i in 0..64u64 { + for _ in 0..TRUE_FREQUENCY { + summary.add(format!("filler_{i}").as_bytes()); + } + } + + let top = summary.top_k(8); + assert!( + top.iter().any(|&(_, _, error)| error > 0), + "expected at least one inflated estimate, got {top:?}" + ); + + for &(item, count, error) in &top { + let name = String::from_utf8_lossy(item); + assert!( + count >= TRUE_FREQUENCY, + "{name}: count {count} is below the true frequency" + ); + assert!( + count.saturating_sub(error) <= TRUE_FREQUENCY, + "{name}: lower bound {} exceeds the true frequency", + count - error + ); + } + + // Counts must be non-increasing, which is what the documented ordering + // promises. + for pair in top.windows(2) { + assert!(pair[0].1 >= pair[1].1, "counts are not descending: {top:?}"); + } + } + + /// The intermediate state of `summary`, as [`Accumulator::state`] builds it. + fn state_of(summary: &SpaceSavingSummary) -> Vec { + let mut state = StateBuilder::default(); + state.push_summary(summary); + state.finish(&DataType::Utf8).unwrap() + } + + /// Decode a one-row intermediate state into a summary through + /// [`Accumulator::merge_batch`]. + fn summary_from_state(state: &[ArrayRef], k: usize) -> Result { + let mut acc = ApproxTopKAccumulator::new_with_data_type(k, DataType::Utf8); + acc.merge_batch(state)?; + Ok(acc.summary) + } + + fn accumulator_state(acc: &mut ApproxTopKAccumulator) -> Vec { + let state = acc.state().unwrap(); + state + .iter() + .map(|column| column.to_array().unwrap()) + .collect() + } + + /// One state row: `(value, count, error)` counters and `(slot, alpha)` + /// filter buckets. + type StateRowParts<'a> = (Vec<(Option<&'a str>, u64, u64)>, Vec<(u32, u64)>); + + fn utf8_state(rows: &[StateRowParts]) -> Vec { + let counters: Vec<_> = rows.iter().flat_map(|(c, _)| c.iter().copied()).collect(); + let buckets: Vec<_> = rows.iter().flat_map(|(_, a)| a.iter().copied()).collect(); + let counter_fields = counter_struct_fields(DataType::Utf8); + let alpha_fields = alpha_struct_fields(); + let counters = StructArray::try_new( + counter_fields.clone(), + vec![ + Arc::new(StringArray::from_iter(counters.iter().map(|c| c.0))), + Arc::new(UInt64Array::from_iter_values(counters.iter().map(|c| c.1))), + Arc::new(UInt64Array::from_iter_values(counters.iter().map(|c| c.2))), + ], + None, + ) + .unwrap(); + let buckets = StructArray::try_new( + alpha_fields.clone(), + vec![ + Arc::new(UInt32Array::from_iter_values(buckets.iter().map(|b| b.0))), + Arc::new(UInt64Array::from_iter_values(buckets.iter().map(|b| b.1))), + ], + None, + ) + .unwrap(); + vec![ + Arc::new(ListArray::new( + state_list_field(counter_fields), + OffsetBuffer::from_lengths(rows.iter().map(|(c, _)| c.len())), + Arc::new(counters), + None, + )), + Arc::new(ListArray::new( + state_list_field(alpha_fields), + OffsetBuffer::from_lengths(rows.iter().map(|(_, a)| a.len())), + Arc::new(buckets), + None, + )), + ] + } + + /// Whether [`Accumulator::merge_batch`] and [`GroupsAccumulator::merge_batch`] + /// accept `state` for an accumulator with k = 1, i.e. capacity 3. + fn merge_results(value_type: &DataType, state: &[ArrayRef]) -> (bool, bool) { + let rows = state.first().map_or(0, |column| column.len()); + let mut acc = ApproxTopKAccumulator::new_with_data_type(1, value_type.clone()); + let mut groups = ApproxTopKGroupsAccumulator::new(1, value_type.clone()); + ( + acc.merge_batch(state).is_ok(), + groups.merge_batch(state, &vec![0; rows], 1).is_ok(), + ) + } + + #[test] + fn test_merge_batch_rejects_invalid_states() { + let full = || vec![(Some("a"), 5, 0), (Some("b"), 3, 1), (Some("c"), 2, 1)]; + let slots = SpaceSavingSummary::compute_alpha_map_size(3) as u32; + let cases: Vec<(&str, Vec, bool)> = vec![ + ("one value", vec![(vec![(Some("a"), 2, 1)], vec![])], true), + ( + "exact summary", + vec![(vec![(Some("a"), 2, 0), (Some("b"), 1, 0)], vec![])], + true, + ), + ("full summary", vec![(full(), vec![(0, 1), (5, 2)])], true), + ("zero count", vec![(vec![(Some("a"), 0, 0)], vec![])], false), + ( + "zero count in a summary", + vec![(vec![(Some("a"), 1, 0), (Some("b"), 0, 0)], vec![])], + false, + ), + ( + "error above count", + vec![(vec![(Some("a"), 1, 2)], vec![])], + false, + ), + ( + "duplicate value", + vec![(vec![(Some("a"), 1, 0), (Some("a"), 1, 0)], vec![])], + false, + ), + ("null value", vec![(vec![(None, 1, 0)], vec![])], false), + ( + "more values than the capacity", + vec![( + vec![ + (Some("a"), 1, 0), + (Some("b"), 1, 0), + (Some("c"), 1, 0), + (Some("d"), 1, 0), + ], + vec![], + )], + false, + ), + ( + "filter bucket in a summary that is not full", + vec![(vec![(Some("a"), 1, 0)], vec![(0, 1)])], + false, + ), + ( + "bucket out of range", + vec![(full(), vec![(slots, 1)])], + false, + ), + ("zero bucket", vec![(full(), vec![(0, 0)])], false), + ( + "unsorted buckets", + vec![(full(), vec![(5, 1), (0, 1)])], + false, + ), + ( + "duplicate buckets", + vec![(full(), vec![(5, 1), (5, 1)])], + false, + ), + ]; + for (name, rows, valid) in cases { + assert_eq!( + merge_results(&DataType::Utf8, &utf8_state(&rows)), + (valid, valid), + "{name}" + ); + } + + let one_value = || vec![(vec![(Some("a"), 1, 0)], vec![])]; + let mut uneven = utf8_state(&one_value()); + uneven[1] = Arc::clone(&utf8_state(&[one_value(), one_value()].concat())[1]); + assert_eq!(merge_results(&DataType::Utf8, &uneven), (false, false)); + let state = utf8_state(&one_value()); + assert_eq!(merge_results(&DataType::Utf8, &state[..1]), (false, false)); + + // Null alpha row next to a valid counters row. + let mut null_alpha = utf8_state(&[(full(), vec![(0, 1)])]); + null_alpha[1] = Arc::new(ListArray::new_null( + state_list_field(alpha_struct_fields()), + 1, + )); + assert_eq!(merge_results(&DataType::Utf8, &null_alpha), (false, false)); + + // Null counters row next to non-empty filter buckets. + let mut null_counters_with_alpha = utf8_state(&[(full(), vec![(0, 1)])]); + null_counters_with_alpha[0] = Arc::new(ListArray::new_null( + state_list_field(counter_struct_fields(DataType::Utf8)), + 1, + )); + assert_eq!( + merge_results(&DataType::Utf8, &null_counters_with_alpha), + (false, false) + ); + + // Null counters row whose underlying entries are invalid must be skipped + // without corrupting subsequent rows. + let corrupt_then_valid = utf8_state(&[ + ( + vec![ + (None, 0, 5), + (Some("x"), 0, 1), + (Some("y"), 1, 0), + (Some("z"), 1, 0), + ], + vec![], + ), + (vec![(Some("a"), 2, 0), (Some("b"), 1, 0)], vec![]), + ]); + let counters_with_null = corrupt_then_valid[0].as_list::(); + let masked_counters: ArrayRef = Arc::new(ListArray::new( + state_list_field(counter_struct_fields(DataType::Utf8)), + counters_with_null.offsets().clone(), + Arc::clone(counters_with_null.values()), + Some(NullBuffer::from(vec![false, true])), + )); + assert_eq!( + merge_results( + &DataType::Utf8, + &[masked_counters, Arc::clone(&corrupt_then_valid[1])], + ), + (true, true) + ); + + // DataType::Null with a non-null counters row containing an entry. + let null_type_fields = counter_struct_fields(DataType::Null); + let null_type_entries = StructArray::try_new( + null_type_fields.clone(), + vec![ + Arc::new(NullArray::new(1)), + Arc::new(UInt64Array::from(vec![1])), + Arc::new(UInt64Array::from(vec![0])), + ], + None, + ) + .unwrap(); + let null_type_state: Vec = vec![ + Arc::new(ListArray::new( + state_list_field(null_type_fields), + OffsetBuffer::from_lengths([1]), + Arc::new(null_type_entries), + None, + )), + Arc::new(ListArray::new( + state_list_field(alpha_struct_fields()), + OffsetBuffer::new_zeroed(1), + new_empty_array(&DataType::Struct(alpha_struct_fields())), + None, + )), + ]; + assert_eq!( + merge_results(&DataType::Null, &null_type_state), + (false, false) + ); + + // Nullable list item field must be rejected by the schema check. + let nullable_item_counters: ArrayRef = Arc::new(ListArray::new( + Arc::new(Field::new_list_field( + DataType::Struct(counter_struct_fields(DataType::Utf8)), + true, + )), + state[0].as_list::().offsets().clone(), + Arc::clone(state[0].as_list::().values()), + None, + )); + assert_eq!( + merge_results( + &DataType::Utf8, + &[nullable_item_counters, Arc::clone(&state[1])], + ), + (false, false) + ); + + // Duplicate +0.0 and -0.0 in a single Float64 state row. + let float_fields = counter_struct_fields(DataType::Float64); + let float_entries = StructArray::try_new( + float_fields.clone(), + vec![ + Arc::new(Float64Array::from(vec![0.0, -0.0])), + Arc::new(UInt64Array::from(vec![1, 1])), + Arc::new(UInt64Array::from(vec![0, 0])), + ], + None, + ) + .unwrap(); + let dup_zero_state: Vec = vec![ + Arc::new(ListArray::new( + state_list_field(float_fields), + OffsetBuffer::from_lengths([2]), + Arc::new(float_entries), + None, + )), + Arc::new(ListArray::new( + state_list_field(alpha_struct_fields()), + OffsetBuffer::new_zeroed(1), + new_empty_array(&DataType::Struct(alpha_struct_fields())), + None, + )), + ]; + assert_eq!( + merge_results(&DataType::Float64, &dup_zero_state), + (false, false) + ); + + // A state of another value type. + assert_eq!(merge_results(&DataType::Binary, &state), (false, false)); + let mut partial = + ApproxTopKAccumulator::new_with_data_type(1, DataType::FixedSizeBinary(2)); + let values: ArrayRef = Arc::new( + FixedSizeBinaryArray::try_from_iter([[1u8, 2]].into_iter()).unwrap(), + ); + partial.update_batch(&[values]).unwrap(); + let state = accumulator_state(&mut partial); + assert_eq!( + merge_results(&DataType::FixedSizeBinary(2), &state), + (true, true) + ); + assert_eq!( + merge_results(&DataType::FixedSizeBinary(3), &state), + (false, false) + ); + } + + /// State arrays can be slices; merging must read only the sliced rows and + /// preserve both counters and filter buckets across every group shape. + #[test] + fn test_merge_batch_reads_only_the_rows_of_sliced_states() { + let values: ArrayRef = Arc::new(StringArray::from(vec![ + Some("a"), + Some("b"), + None, + Some("c"), + Some("d"), + ])); + let filter = BooleanArray::from(vec![ + Some(true), + Some(true), + Some(true), + None, + Some(true), + ]); + let states = ApproxTopKGroupsAccumulator::new(1, DataType::Utf8) + .convert_to_state(&[values], Some(&filter)) + .unwrap(); + let sliced: Vec = + states.iter().map(|state| state.slice(1, 3)).collect(); + let mut acc = ApproxTopKAccumulator::new_with_data_type(3, DataType::Utf8); + acc.merge_batch(&sliced).unwrap(); + assert_eq!( + extract_top_k_results(&acc.evaluate().unwrap()), + vec![("b".to_string(), 1)] + ); + + // 0-row states and 0-length slices with non-zero offset. + let empty_slice: Vec = + states.iter().map(|state| state.slice(2, 0)).collect(); + let mut empty_acc = ApproxTopKAccumulator::new_with_data_type(1, DataType::Utf8); + empty_acc.merge_batch(&empty_slice).unwrap(); + assert!(extract_top_k_results(&empty_acc.evaluate().unwrap()).is_empty()); + let mut empty_groups = ApproxTopKGroupsAccumulator::new(1, DataType::Utf8); + empty_groups.merge_batch(&empty_slice, &[], 0).unwrap(); + assert_eq!(empty_groups.evaluate(EmitTo::All).unwrap().len(), 0); + + // Groups: 0 filler (so slice(1, 5) has non-zero offsets), 1 empty, + // 2 singleton, 3 exact, 4 full sparse, 5 full dense. + let mut raw_values = Vec::new(); + let mut raw_groups = Vec::new(); + for i in 0..5 { + raw_values.push(format!("filler_{i}")); + raw_groups.push(0); + } + for value in ["solo", "solo"] { + raw_values.push(value.to_string()); + raw_groups.push(2); + } + for value in ["x", "x", "y"] { + raw_values.push(value.to_string()); + raw_groups.push(3); + } + for i in 0..8 { + raw_values.push(format!("item_{i}")); + raw_groups.push(4); + } + for i in 0..1_000 { + raw_values.push(format!("item_{i}")); + raw_groups.push(5); + } + let values: ArrayRef = Arc::new(StringArray::from(raw_values)); + let mut acc = ApproxTopKGroupsAccumulator::new(1, DataType::Utf8); + acc.update_batch(&[values], &raw_groups, None, 6).unwrap(); + + assert!(matches!(acc.summaries[1], GroupSummary::Empty)); + assert!(matches!(acc.summaries[2], GroupSummary::Singleton(_))); + assert!(matches!( + &acc.summaries[3], + GroupSummary::Full(s) if s.is_exact() && matches!(s.alpha_map, AlphaMap::Empty) + )); + assert!(matches!( + &acc.summaries[4], + GroupSummary::Full(s) if matches!(s.alpha_map, AlphaMap::Sparse(_)) + )); + assert!(matches!( + &acc.summaries[5], + GroupSummary::Full(s) if matches!(s.alpha_map, AlphaMap::Dense(_)) + )); + + let state = acc.state(EmitTo::All).unwrap(); + let sliced: Vec = state.iter().map(|col| col.slice(1, 5)).collect(); + let mut merged = ApproxTopKGroupsAccumulator::new(1, DataType::Utf8); + merged.merge_batch(&sliced, &[0, 1, 2, 3, 4], 5).unwrap(); + let restated = merged.state(EmitTo::All).unwrap(); + assert_eq!(restated, sliced); + + // Also test ListArrays whose child StructArrays are themselves sliced. + let counters_list = state[0].as_list::(); + let alpha_list = state[1].as_list::(); + let c_start = counters_list.value_offsets()[1] as usize; + let c_len = counters_list.value_offsets()[6] as usize - c_start; + let a_start = alpha_list.value_offsets()[1] as usize; + let a_len = alpha_list.value_offsets()[6] as usize - a_start; + let child_sliced: Vec = vec![ + Arc::new(ListArray::new( + state_list_field(counter_struct_fields(DataType::Utf8)), + OffsetBuffer::from_lengths( + (1..6).map(|r| counters_list.value_length(r) as usize), + ), + counters_list.values().slice(c_start, c_len), + None, + )), + Arc::new(ListArray::new( + state_list_field(alpha_struct_fields()), + OffsetBuffer::from_lengths( + (1..6).map(|r| alpha_list.value_length(r) as usize), + ), + alpha_list.values().slice(a_start, a_len), + None, + )), + ]; + let mut merged_child = ApproxTopKGroupsAccumulator::new(1, DataType::Utf8); + merged_child + .merge_batch(&child_sliced, &[0, 1, 2, 3, 4], 5) + .unwrap(); + assert_eq!(merged_child.state(EmitTo::All).unwrap(), sliced); + } + + #[test] + fn test_space_saving_merge() { + let mut summary1 = SpaceSavingSummary::new(4); + let mut summary2 = SpaceSavingSummary::new(4); + + summary1.add(b"apple"); + summary1.add(b"apple"); + summary2.add(b"apple"); + summary2.add(b"banana"); + + summary1.merge(summary2).unwrap(); + + let (count, _) = summary1.get(b"apple").unwrap(); + assert_eq!(count, 3); + + let (count, _) = summary1.get(b"banana").unwrap(); + assert_eq!(count, 1); + } + + #[test] + fn test_merge_common_exact_counter_keeps_zero_error() { + let mut left = SpaceSavingSummary::new(3); + let mut right = SpaceSavingSummary::new(3); + for _ in 0..100 { + left.add(b"shared"); + } + left.add(b"left_a"); + left.add(b"left_b"); + for _ in 0..99 { + right.add(b"shared"); + } + right.add(b"right_a"); + right.add(b"right_b"); + + left.merge(right).unwrap(); + assert_eq!(left.get(b"shared"), Some((199, 0))); + } + + #[test] + fn test_merge_common_counter_saturates_without_losing_count() { + let mut left = SpaceSavingSummary::new(1); + left.push_owned_counter(Counter { + item: b"shared".to_vec(), + hash: SpaceSavingSummary::hash_item(b"shared"), + count: u64::MAX - 5, + error: 0, + }); + + let mut right = SpaceSavingSummary::new(1); + right.push_owned_counter(Counter { + item: b"shared".to_vec(), + hash: SpaceSavingSummary::hash_item(b"shared"), + count: 10, + error: 0, + }); + right.raise_alpha(SpaceSavingSummary::hash_item(b"evicted"), 100); + + left.merge(right).unwrap(); + assert_eq!(left.get(b"shared"), Some((u64::MAX, 0))); + } + + /// An item can be frequent overall while being evicted from one partition + /// because that partition happened to see mostly other traffic. The merge + /// must still report it with an upper bound of its total count, and must + /// not report a lower bound above the true total. + #[test] + fn test_merge_recovers_item_evicted_from_one_partition() { + let mut evicting = SpaceSavingSummary::new(2); + evicting.add(b"shared"); + for i in 0..64u64 { + for _ in 0..4 { + evicting.add(format!("noise_{i}").as_bytes()); + } + } + assert!( + evicting.get(b"shared").is_none(), + "a single occurrence should lose to the count-4 noise" + ); + + // More occurrences than the 257 values the other partition saw, so no + // estimate there can outrank it. This partition is filled too, so the + // summaries are combined with Parallel Space-Saving rather than by + // folding in an exact summary. + let mut keeping = SpaceSavingSummary::new(2); + for _ in 0..300 { + keeping.add(b"shared"); + } + keeping.add(b"keeping_other"); + assert!(!keeping.is_exact()); + + keeping.merge(evicting).unwrap(); + + let (count, error) = keeping + .get(b"shared") + .expect("merge must keep an item that survived in one partition"); + + // True total across both partitions is 1 + 300 = 301. + const TRUE_TOTAL: u64 = 301; + assert!( + count >= TRUE_TOTAL, + "count {count} is not an upper bound of the true total" + ); + assert!( + count.saturating_sub(error) <= TRUE_TOTAL, + "lower bound {} exceeds the true total", + count - error + ); + } + + /// Merging single-value summaries gives the same summary as accumulating + /// the rows directly, including the filter state once values start being + /// evicted. + #[test] + fn test_merging_singletons_matches_stream_updates() { + let mut streamed = SpaceSavingSummary::new(6); + let mut merged = SpaceSavingSummary::new(6); + for i in 0..2_000u64 { + let item = format!("item_{}", (i * i) % 97); + streamed.add(item.as_bytes()); + let mut singleton = SpaceSavingSummary::new(6); + singleton.add(item.as_bytes()); + merged.merge(singleton).unwrap(); + } + + assert!( + !streamed.alpha_map.is_empty(), + "the stream must evict values" + ); + assert_eq!(merged.top_k(6), streamed.top_k(6)); + assert_eq!( + merged.alpha_map.sorted_entries(), + streamed.alpha_map.sorted_entries() + ); + } + + /// An exact summary is folded into a full one regardless of which side of + /// the merge it is on, using the filter bucket of each folded value. + #[test] + fn test_merge_folds_exact_summary_on_either_side() { + let full = || { + let mut summary = SpaceSavingSummary::new(3); + for i in 0..50u64 { + summary.add(format!("noise_{}", i % 7).as_bytes()); + } + summary + }; + let exact = || { + let mut summary = SpaceSavingSummary::new(3); + for _ in 0..100 { + summary.add(b"heavy"); + } + summary.add(b"light"); + summary + }; + assert!(!full().is_exact()); + assert!(exact().is_exact()); + + let mut left = full(); + left.merge(exact()).unwrap(); + let mut right = exact(); + right.merge(full()).unwrap(); + + assert_eq!(left.top_k(3), right.top_k(3)); + assert_eq!( + left.alpha_map.sorted_entries(), + right.alpha_map.sorted_entries() + ); + let (item, count, _) = left.top_k(1)[0]; + assert_eq!(item, b"heavy"); + assert!(count >= 100, "count {count} lost exact occurrences"); + } + + /// A value missing from one full summary is bounded by that summary's + /// alpha for the value's bucket, not by its largest alpha anywhere. + #[test] + fn test_merge_bounds_missing_values_by_their_bucket() { + let full = |items: [&[u8]; 3]| { + let mut summary = SpaceSavingSummary::new(3); + for item in items { + for _ in 0..10 { + summary.add(item); + } + } + summary + }; + let mut left = full([b"a", b"b", b"c"]); + let mut right = full([b"x", b"y", b"z"]); + + // A large estimate in a bucket that none of the left values use. + let left_slots: Vec<_> = left + .counters + .iter() + .map(|counter| right.alpha_slot(counter.hash)) + .collect(); + let hot = (0u64..1_000) + .map(|i| SpaceSavingSummary::hash_item(format!("hot_{i}").as_bytes())) + .find(|&hash| !left_slots.contains(&right.alpha_slot(hash))) + .expect("most buckets are unused"); + right.raise_alpha(hot, 1_000); + + left.merge(right).unwrap(); + for item in [b"a", b"b", b"c"] { + assert_eq!(left.get(item), Some((10, 0))); + } + } + + /// Recall check on a skewed stream: the heavy hitters must all be reported. + /// + /// Space-Saving guarantees that any item with frequency above + /// `total / capacity` is retained. Here `capacity` is `k * 3 = 15` and the + /// stream has 6500 items, so the guarantee threshold is ~433 and every item + /// in the true top 5 (frequencies 1000..600) clears it. + #[test] + fn test_skewed_stream_top_k_recall() { + const HEAVY: usize = 10; + const TAIL: usize = 1000; + let k = 5usize; + + let mut stream: Vec = Vec::new(); + for i in 0..HEAVY { + let frequency = (HEAVY - i) * 100; + for _ in 0..frequency { + stream.push(format!("heavy_{i}")); + } + } + for i in 0..TAIL { + stream.push(format!("tail_{i:04}")); + } + + // Interleave deterministically by striding with a prime step coprime to + // the length, so the heavy hitters are spread through the stream rather + // than arriving in convenient runs. + let n = stream.len(); + let step = 7919; + assert_eq!(n, 5500 + TAIL); + + let mut summary = SpaceSavingSummary::new(k * CAPACITY_MULTIPLIER); + for j in 0..n { + summary.add(stream[(j * step) % n].as_bytes()); + } + + let reported: Vec = summary + .top_k(k) + .iter() + .map(|(item, _, _)| String::from_utf8_lossy(item).into_owned()) + .collect(); + let expected: Vec = (0..k).map(|i| format!("heavy_{i}")).collect(); + + assert_eq!(reported, expected, "top-{k} on a skewed stream"); + } + + fn extract_top_k_row(list: &ListArray, row: usize) -> Vec<(String, u64)> { + let values = list.value(row); + let struct_array = values.as_struct(); + let strings = struct_array.column(0).as_string::(); + let counts = struct_array.column(1).as_primitive::(); + (0..struct_array.len()) + .map(|i| (strings.value(i).to_string(), counts.value(i))) + .collect() + } + + fn extract_top_k_results(result: &ScalarValue) -> Vec<(String, u64)> { + let ScalarValue::List(list) = result else { + panic!("Expected ScalarValue::List, got {result:?}"); + }; + extract_top_k_row(list, 0) + } + + #[test] + fn test_accumulator_update_and_evaluate() { + let mut acc = ApproxTopKAccumulator::new_with_data_type(3, DataType::Utf8); + + let values: ArrayRef = Arc::new(StringArray::from(vec![ + "apple", "apple", "apple", "banana", "banana", "cherry", + ])); + + acc.update_batch(&[values]).unwrap(); + + let result = acc.evaluate().unwrap(); + let top_k = extract_top_k_results(&result); + + assert_eq!(top_k.len(), 3); + assert_eq!(top_k[0], ("apple".to_string(), 3)); + assert_eq!(top_k[1], ("banana".to_string(), 2)); + assert_eq!(top_k[2], ("cherry".to_string(), 1)); + } + + #[test] + fn test_distributed_merge_simulation() { + let mut worker1_acc = + ApproxTopKAccumulator::new_with_data_type(3, DataType::Utf8); + let mut worker2_acc = + ApproxTopKAccumulator::new_with_data_type(3, DataType::Utf8); + let mut worker3_acc = + ApproxTopKAccumulator::new_with_data_type(3, DataType::Utf8); + + let values1: ArrayRef = + Arc::new(StringArray::from(vec!["apple", "apple", "apple", "banana"])); + worker1_acc.update_batch(&[values1]).unwrap(); + + let values2: ArrayRef = Arc::new(StringArray::from(vec![ + "apple", "apple", "cherry", "cherry", + ])); + worker2_acc.update_batch(&[values2]).unwrap(); + + let values3: ArrayRef = Arc::new(StringArray::from(vec![ + "banana", "banana", "banana", "durian", + ])); + worker3_acc.update_batch(&[values3]).unwrap(); + + let states = [ + worker1_acc.state().unwrap(), + worker2_acc.state().unwrap(), + worker3_acc.state().unwrap(), + ]; + let stacked: Vec = (0..states[0].len()) + .map(|column| { + ScalarValue::iter_to_array(states.iter().map(|s| s[column].clone())) + .unwrap() + }) + .collect(); + + let mut coord_acc = ApproxTopKAccumulator::new_with_data_type(3, DataType::Utf8); + coord_acc.merge_batch(&stacked).unwrap(); + + let result = coord_acc.evaluate().unwrap(); + let top_k = extract_top_k_results(&result); + + assert!(top_k.len() >= 2); + assert_eq!(top_k[0], ("apple".to_string(), 5)); + assert_eq!(top_k[1], ("banana".to_string(), 4)); + } + + #[test] + fn test_merge_orders_preserve_frequency_intervals() { + use std::collections::HashMap; + + let k = 3; + let capacity = k * CAPACITY_MULTIPLIER; + let mut partitions: Vec<_> = + (0..4).map(|_| SpaceSavingSummary::new(capacity)).collect(); + let mut truth = HashMap::::new(); + let mut rng = 0x1234_5678_9abc_def0u64; + for row in 0..10_000usize { + rng = rng.wrapping_mul(6364136223846793005).wrapping_add(1); + let item = if rng % 10 < 6 { + "hot".to_string() + } else { + format!("tail_{}", rng % 100) + }; + partitions[row % 4].add(item.as_bytes()); + *truth.entry(item).or_default() += 1; + } + + let states: Vec<_> = partitions.iter().map(state_of).collect(); + for order in [[0, 1, 2, 3], [3, 2, 1, 0], [1, 3, 0, 2]] { + let mut merged = SpaceSavingSummary::new(capacity); + for index in order { + let other = summary_from_state(&states[index], k).unwrap(); + merged.merge(other).unwrap(); + } + let top = merged.top_k(3); + assert_eq!(top[0].0, b"hot"); + for &(item, count, error) in &top { + let item = std::str::from_utf8(item).unwrap(); + let true_count = truth[item]; + assert!(count >= true_count, "{item}: {count} < {true_count}"); + assert!( + count.saturating_sub(error) <= true_count, + "{item}: lower bound {} > {true_count}", + count - error + ); + } + } + } + + #[test] + fn test_accumulator_multiple_update_batches() { + let mut acc = ApproxTopKAccumulator::new_with_data_type(2, DataType::Utf8); + + // First batch: a=2, b=1 + let batch1: ArrayRef = Arc::new(StringArray::from(vec!["a", "b", "a"])); + acc.update_batch(&[batch1]).unwrap(); + + // Second batch: b=2, c=1 + let batch2: ArrayRef = Arc::new(StringArray::from(vec!["b", "c", "b"])); + acc.update_batch(&[batch2]).unwrap(); + + // Combined: b=3, a=2, c=1 → top-2 should be b, a + let result = acc.evaluate().unwrap(); + let top_k = extract_top_k_results(&result); + assert_eq!(top_k.len(), 2); + assert_eq!(top_k[0], ("b".to_string(), 3)); + assert_eq!(top_k[1], ("a".to_string(), 2)); + } + + #[test] + fn test_all_supported_physical_types_and_timestamp_metadata() { + assert!(!is_supported_value_type(&DataType::FixedSizeBinary(-1))); + + fn assert_round_trip(input: ArrayRef) { + let data_type = input.data_type().clone(); + assert!(is_supported_value_type(&data_type), "{data_type}"); + let mut partial = + ApproxTopKAccumulator::new_with_data_type(2, data_type.clone()); + partial.update_batch(std::slice::from_ref(&input)).unwrap(); + let state = accumulator_state(&mut partial); + + let mut final_acc = + ApproxTopKAccumulator::new_with_data_type(2, data_type.clone()); + final_acc.merge_batch(&state).unwrap(); + let ScalarValue::List(result) = final_acc.evaluate().unwrap() else { + panic!("expected List result for {data_type}"); + }; + assert_eq!( + result.values().data_type(), + &DataType::Struct(result_struct_fields(data_type.clone())) + ); + let values = result.values().as_struct(); + assert_eq!(values.column(0).data_type(), &data_type); + if data_type != DataType::Null { + assert_eq!(values.len(), 1, "{data_type}"); + assert_eq!(values.column(0).as_ref(), &input.slice(0, 1), "{data_type}"); + assert_eq!( + values.column(1).as_primitive::().value(0), + 2, + "{data_type}" + ); + } + + let mut groups = ApproxTopKGroupsAccumulator::new(2, data_type.clone()); + let converted = groups + .convert_to_state(std::slice::from_ref(&input), None) + .unwrap(); + groups + .merge_batch(&converted, &vec![0; input.len()], 1) + .unwrap(); + assert_eq!( + groups.evaluate(EmitTo::All).unwrap().as_ref(), + result.as_ref(), + "{data_type}" + ); + } + + let binary = b"a".as_slice(); + let long_str = "out_of_line_view_string_longer_than_12_bytes"; + let long_bytes = b"out_of_line_view_binary_longer_than_12_bytes".as_slice(); + let arrays: Vec = vec![ + Arc::new(StringArray::from(vec!["a", "a"])), + Arc::new(StringArray::from(vec!["", ""])), + Arc::new(LargeStringArray::from(vec!["a", "a"])), + Arc::new(StringViewArray::from(vec!["a", "a"])), + Arc::new(StringViewArray::from(vec![long_str, long_str])), + Arc::new(BinaryArray::from(vec![binary, binary])), + Arc::new(BinaryArray::from(vec![b"".as_slice(), b"".as_slice()])), + Arc::new(LargeBinaryArray::from(vec![binary, binary])), + Arc::new(BinaryViewArray::from(vec![binary, binary])), + Arc::new(BinaryViewArray::from(vec![long_bytes, long_bytes])), + Arc::new(Int8Array::from(vec![1, 1])), + Arc::new(Int16Array::from(vec![1, 1])), + Arc::new(Int32Array::from(vec![1, 1])), + Arc::new(Int64Array::from(vec![1, 1])), + Arc::new(UInt8Array::from(vec![1, 1])), + Arc::new(UInt16Array::from(vec![1, 1])), + Arc::new(UInt32Array::from(vec![1, 1])), + Arc::new(UInt64Array::from(vec![1, 1])), + Arc::new(Float32Array::from(vec![1.0, 1.0])), + Arc::new(Float64Array::from(vec![1.0, 1.0])), + Arc::new(Date32Array::from(vec![1, 1])), + Arc::new(Date64Array::from(vec![1, 1])), + Arc::new(TimestampSecondArray::from(vec![1, 1])), + Arc::new(TimestampMillisecondArray::from(vec![1, 1])), + Arc::new(TimestampMicrosecondArray::from(vec![1, 1])), + Arc::new( + TimestampNanosecondArray::from(vec![1, 1]) + .with_timezone("America/New_York"), + ), + Arc::new(NullArray::new(2)), + Arc::new(BooleanArray::from(vec![true, true])), + Arc::new(Time32SecondArray::from(vec![1, 1])), + Arc::new(Time32MillisecondArray::from(vec![1, 1])), + Arc::new(Time64MicrosecondArray::from(vec![1, 1])), + Arc::new(Time64NanosecondArray::from(vec![1, 1])), + Arc::new( + Decimal32Array::from(vec![123, 123]) + .with_precision_and_scale(9, 2) + .unwrap(), + ), + Arc::new( + Decimal64Array::from(vec![123, 123]) + .with_precision_and_scale(18, 2) + .unwrap(), + ), + Arc::new( + Decimal128Array::from(vec![123, 123]) + .with_precision_and_scale(38, 2) + .unwrap(), + ), + Arc::new( + Decimal256Array::from(vec![i256::from(-123), i256::from(-123)]) + .with_precision_and_scale(76, 3) + .unwrap(), + ), + Arc::new( + FixedSizeBinaryArray::try_from_iter([[0u8; 0], [0u8; 0]].into_iter()) + .unwrap(), + ), + Arc::new( + FixedSizeBinaryArray::try_from_iter([[7u8; 16], [7u8; 16]].into_iter()) + .unwrap(), + ), + ]; + for input in arrays { + assert_round_trip(input); + } + } + + #[test] + fn test_float_zero_and_nan_equality() { + let mut left = ApproxTopKAccumulator::new_with_data_type(3, DataType::Float64); + let mut right = ApproxTopKAccumulator::new_with_data_type(3, DataType::Float64); + left.update_batch(&[Arc::new(Float64Array::from(vec![0.0, -0.0]))]) + .unwrap(); + right + .update_batch(&[Arc::new(Float64Array::from(vec![-0.0]))]) + .unwrap(); + left.merge_batch(&accumulator_state(&mut right)).unwrap(); + assert_eq!( + left.summary.get(&0.0f64.to_bits().to_le_bytes()), + Some((3, 0)) + ); + assert!( + left.summary + .get(&(-0.0f64).to_bits().to_le_bytes()) + .is_none() + ); + + let nan1 = f64::from_bits(0x7ff8_0000_0000_0001); + let nan2 = f64::from_bits(0x7ff8_0000_0000_0002); + let mut acc = ApproxTopKAccumulator::new_with_data_type(2, DataType::Float64); + acc.update_batch(&[Arc::new(Float64Array::from(vec![nan1, nan1, nan2]))]) + .unwrap(); + assert_eq!(acc.summary.get(&nan1.to_bits().to_le_bytes()), Some((2, 0))); + assert_eq!(acc.summary.get(&nan2.to_bits().to_le_bytes()), Some((1, 0))); + + // The zero-copy convert_to_state path leaves raw floats in the state + // and normalizes them when merging. + let floats: ArrayRef = Arc::new(Float64Array::from(vec![0.0, -0.0, nan1, nan2])); + let mut groups = ApproxTopKGroupsAccumulator::new(2, DataType::Float64); + let converted = groups.convert_to_state(&[floats], None).unwrap(); + groups.merge_batch(&converted, &[0, 0, 0, 0], 1).unwrap(); + let GroupSummary::Full(summary) = &groups.summaries[0] else { + panic!("expected Full summary"); + }; + assert_eq!(summary.get(&0.0f64.to_bits().to_le_bytes()), Some((2, 0))); + assert!(summary.get(&(-0.0f64).to_bits().to_le_bytes()).is_none()); + assert_eq!(summary.get(&nan1.to_bits().to_le_bytes()), Some((1, 0))); + assert_eq!(summary.get(&nan2.to_bits().to_le_bytes()), Some((1, 0))); + + let f32_nan1 = f32::from_bits(0x7fc0_0001); + let f32_nan2 = f32::from_bits(0x7fc0_0002); + let f32_input: ArrayRef = Arc::new(Float32Array::from(vec![ + 0.0f32, -0.0f32, f32_nan1, f32_nan2, + ])); + let mut f32_groups = ApproxTopKGroupsAccumulator::new(2, DataType::Float32); + let f32_converted = f32_groups.convert_to_state(&[f32_input], None).unwrap(); + f32_groups + .merge_batch(&f32_converted, &[0, 0, 0, 0], 1) + .unwrap(); + let GroupSummary::Full(summary) = &f32_groups.summaries[0] else { + panic!("expected Full summary"); + }; + assert_eq!(summary.get(&0.0f32.to_bits().to_le_bytes()), Some((2, 0))); + assert!(summary.get(&(-0.0f32).to_bits().to_le_bytes()).is_none()); + assert_eq!(summary.get(&f32_nan1.to_bits().to_le_bytes()), Some((1, 0))); + assert_eq!(summary.get(&f32_nan2.to_bits().to_le_bytes()), Some((1, 0))); + } + + #[test] + fn test_state_holds_only_nonzero_filter_buckets() { + let (mut exact, mut sparse, mut dense_with_zeros, mut dense_full) = + (false, false, false, false); + for distinct in [2, 8, 20, 1_000] { + let mut summary = SpaceSavingSummary::new(3); + for i in 0..distinct { + summary.add(format!("item_{i}").as_bytes()); + } + match &summary.alpha_map { + AlphaMap::Empty => exact = true, + AlphaMap::Sparse(_) => sparse = true, + AlphaMap::Dense(cells) if cells.contains(&0) => dense_with_zeros = true, + AlphaMap::Dense(_) => dense_full = true, + } + + let state = state_of(&summary); + let restored = summary_from_state(&state, 1).unwrap(); + assert_eq!(restored.len(), summary.len()); + assert_eq!(restored.top_k(3), summary.top_k(3)); + assert_eq!(restored.alpha_map, summary.alpha_map); + assert_eq!( + state[1].as_list::().value_length(0) as usize, + summary.alpha_map.sorted_entries().len() + ); + } + assert!(exact && sparse && dense_with_zeros && dense_full); + } + + /// Equal counts must not produce arbitrary output order, otherwise results + /// vary run to run and SQL-level tests cannot assert on them. + #[test] + fn test_tied_counts_are_ordered_deterministically() { + let mut summary = SpaceSavingSummary::new(8); + for item in ["delta", "alpha", "charlie", "bravo"] { + summary.add(item.as_bytes()); + } + + let reported: Vec = summary + .top_k(4) + .iter() + .map(|(item, _, _)| String::from_utf8_lossy(item).into_owned()) + .collect(); + assert_eq!(reported, vec!["alpha", "bravo", "charlie", "delta"]); + } + + #[test] + fn test_native_groups_accumulator_update_state_merge_and_filter() { + let assert_allocated_exact = |acc: &ApproxTopKGroupsAccumulator| { + let expected: usize = acc.summaries.iter().map(GroupSummary::heap_size).sum(); + assert_eq!(acc.allocated_bytes, expected); + }; + + let values: ArrayRef = Arc::new(StringArray::from(vec!["a", "x", "a", "y", "b"])); + let filter = BooleanArray::from(vec![ + Some(true), + Some(true), + Some(true), + None, + Some(false), + ]); + let groups = [0, 1, 0, 1, 0]; + let mut partial = ApproxTopKGroupsAccumulator::new(2, DataType::Utf8); + partial + .update_batch(&[values], &groups, Some(&filter), 2) + .unwrap(); + assert!(partial.allocated_bytes > 0); + assert_allocated_exact(&partial); + + let state = partial.state(EmitTo::All).unwrap(); + assert_eq!(partial.allocated_bytes, 0); + assert_eq!(state.len(), 2); + + let mut final_acc = ApproxTopKGroupsAccumulator::new(2, DataType::Utf8); + final_acc.merge_batch(&state, &[0, 1], 2).unwrap(); + assert_allocated_exact(&final_acc); + let result = final_acc.evaluate(EmitTo::All).unwrap(); + let list = result.as_list::(); + assert_eq!(extract_top_k_row(list, 0), vec![("a".to_string(), 2)]); + assert_eq!(extract_top_k_row(list, 1), vec![("x".to_string(), 1)]); + + let raw: ArrayRef = Arc::new(StringArray::from(vec![ + Some("z"), + None, + Some("q"), + Some("r"), + ])); + let filter = BooleanArray::from(vec![Some(true), Some(true), Some(false), None]); + let converter = ApproxTopKGroupsAccumulator::new(1, DataType::Utf8); + let states = converter + .convert_to_state(std::slice::from_ref(&raw), Some(&filter)) + .unwrap(); + let counters = states[0].as_list::(); + assert!(Arc::ptr_eq(counters.values().as_struct().column(0), &raw)); + assert!(counters.is_valid(0)); + assert!(counters.is_null(1)); + assert!(counters.is_null(2)); + assert!(counters.is_null(3)); + let mut merged = ApproxTopKGroupsAccumulator::new(1, DataType::Utf8); + merged.merge_batch(&states, &[0, 1, 2, 3], 4).unwrap(); + assert_allocated_exact(&merged); + let result = merged.evaluate(EmitTo::All).unwrap(); + let list = result.as_list::(); + assert_eq!(extract_top_k_row(list, 0), vec![("z".to_string(), 1)]); + assert!(extract_top_k_row(list, 1).is_empty()); + assert!(extract_top_k_row(list, 2).is_empty()); + assert!(extract_top_k_row(list, 3).is_empty()); + + // EmitTo::First on Full groups (sparse and dense alpha maps) plus + // exact allocated_bytes accounting across promotions and emissions. + let mut raw_values = Vec::new(); + let mut raw_groups = Vec::new(); + for i in 0..8 { + raw_values.push(format!("sparse_{i}")); + raw_groups.push(0); + } + for i in 0..1_000 { + raw_values.push(format!("dense_{i}")); + raw_groups.push(1); + } + raw_values.push("c".to_string()); + raw_groups.push(2); + let values: ArrayRef = Arc::new(StringArray::from(raw_values)); + let mut emit = ApproxTopKGroupsAccumulator::new(1, DataType::Utf8); + emit.update_batch(&[values], &raw_groups, None, 3).unwrap(); + assert_allocated_exact(&emit); + let initial_size = emit.size(); + + let first_state = emit.state(EmitTo::First(1)).unwrap(); + assert_eq!(first_state[0].len(), 1); + assert!(emit.size() < initial_size); + assert_allocated_exact(&emit); + let mut first = ApproxTopKGroupsAccumulator::new(1, DataType::Utf8); + first.merge_batch(&first_state, &[0], 1).unwrap(); + assert_allocated_exact(&first); + let result = first.evaluate(EmitTo::All).unwrap(); + assert_eq!(extract_top_k_row(result.as_list::(), 0).len(), 1); + + let result = emit.evaluate(EmitTo::First(1)).unwrap(); + assert_eq!(extract_top_k_row(result.as_list::(), 0).len(), 1); + assert_allocated_exact(&emit); + let shifted: ArrayRef = Arc::new(StringArray::from(vec!["c"])); + emit.update_batch(&[shifted], &[0], None, 1).unwrap(); + assert_allocated_exact(&emit); + let result = emit.evaluate(EmitTo::All).unwrap(); + assert_eq!( + extract_top_k_row(result.as_list::(), 0), + vec![("c".to_string(), 2)] + ); + assert_eq!(emit.allocated_bytes, 0); + } +} diff --git a/datafusion/functions-aggregate/src/lib.rs b/datafusion/functions-aggregate/src/lib.rs index 376342c3455a6..235a151c680a5 100644 --- a/datafusion/functions-aggregate/src/lib.rs +++ b/datafusion/functions-aggregate/src/lib.rs @@ -57,6 +57,7 @@ pub mod approx_distinct; pub mod approx_median; pub mod approx_percentile_cont; pub mod approx_percentile_cont_with_weight; +pub mod approx_top_k; pub mod array_agg; pub mod average; pub mod bit_and_or_xor; @@ -95,6 +96,7 @@ pub mod expr_fn { pub use super::approx_median::approx_median; pub use super::approx_percentile_cont::approx_percentile_cont; pub use super::approx_percentile_cont_with_weight::approx_percentile_cont_with_weight; + pub use super::approx_top_k::approx_top_k; pub use super::array_agg::array_agg; pub use super::average::avg; pub use super::average::avg_distinct; @@ -165,6 +167,7 @@ pub fn all_default_aggregate_functions() -> Vec> { approx_distinct::approx_distinct_udaf(), approx_percentile_cont_udaf(), approx_percentile_cont_with_weight_udaf(), + approx_top_k::approx_top_k_udaf(), percentile_cont::percentile_cont_udaf(), string_agg::string_agg_udaf(), bit_and_or_xor::bit_and_udaf(), diff --git a/datafusion/proto/tests/cases/roundtrip_logical_plan.rs b/datafusion/proto/tests/cases/roundtrip_logical_plan.rs index 0f700d0d7dc21..f76d8ddb94634 100644 --- a/datafusion/proto/tests/cases/roundtrip_logical_plan.rs +++ b/datafusion/proto/tests/cases/roundtrip_logical_plan.rs @@ -43,9 +43,9 @@ use datafusion::execution::FunctionRegistry; use datafusion::execution::session_state::SessionStateBuilder; use datafusion::functions_aggregate::count::count_udaf; use datafusion::functions_aggregate::expr_fn::{ - approx_median, approx_percentile_cont, approx_percentile_cont_with_weight, count, - count_distinct, covar_pop, covar_samp, first_value, grouping, max, median, min, - stddev, stddev_pop, sum, var_pop, var_sample, + approx_median, approx_percentile_cont, approx_percentile_cont_with_weight, + approx_top_k, count, count_distinct, covar_pop, covar_samp, first_value, grouping, + max, median, min, stddev, stddev_pop, sum, var_pop, var_sample, }; use datafusion::functions_aggregate::min_max::max_udaf; use datafusion::functions_nested::map::map; @@ -1714,6 +1714,7 @@ async fn roundtrip_expr_api() -> Result<()> { stddev_pop(lit(2.2)), approx_distinct(lit(2)), approx_median(lit(2)), + approx_top_k(col("a"), lit(3)), approx_percentile_cont(lit(2).sort(true, false), lit(0.5), None), approx_percentile_cont(lit(2).sort(true, false), lit(0.5), Some(lit(50))), approx_percentile_cont_with_weight( diff --git a/datafusion/sqllogictest/test_files/aggregate_skip_partial.slt b/datafusion/sqllogictest/test_files/aggregate_skip_partial.slt index 09ed518a22603..a2a48c532ab2d 100644 --- a/datafusion/sqllogictest/test_files/aggregate_skip_partial.slt +++ b/datafusion/sqllogictest/test_files/aggregate_skip_partial.slt @@ -177,6 +177,21 @@ GROUP BY 1, 2 ORDER BY 1 LIMIT 5; -2117946883 d [-59] [NULL] NULL NULL -2098805236 c [22] [NULL] NULL NULL +query IT???? +SELECT c5, c1, + APPROX_TOP_K(c3, 2), + APPROX_TOP_K(CASE WHEN c1 = 'a' THEN c3 ELSE NULL END, 2), + APPROX_TOP_K(c3, 2) FILTER (WHERE c1 = 'b'), + APPROX_TOP_K(CASE WHEN c1 = 'a' THEN c3 ELSE NULL END, 2) FILTER (WHERE c1 = 'b') +FROM aggregate_test_100 +GROUP BY 1, 2 ORDER BY 1 LIMIT 5; +---- +-2141999138 c [{value: -2, count: 1}] [] [] [] +-2141451704 a [{value: -72, count: 1}] [{value: -72, count: 1}] [] [] +-2138770630 b [{value: 63, count: 1}] [] [{value: 63, count: 1}] [] +-2117946883 d [{value: -59, count: 1}] [] [] [] +-2098805236 c [{value: 22, count: 1}] [] [] [] + # Regression test for https://github.com/apache/datafusion/issues/11846 query TBBBB rowsort select v1, bool_or(v2), bool_and(v2), bool_or(v3), bool_and(v3) @@ -324,6 +339,16 @@ SELECT c2, approx_distinct(c1), approx_distinct(c5) FROM aggregate_test_100 GROU 4 5 23 5 5 14 +# Test approx_top_k for varchar / int +query I?? +SELECT c2, approx_top_k(c1, 2), approx_top_k(c3 % 3, 2) FROM aggregate_test_100 GROUP BY c2 ORDER BY c2; +---- +1 [{value: d, count: 7}, {value: a, count: 5}] [{value: 0, count: 8}, {value: 2, count: 6}] +2 [{value: c, count: 7}, {value: e, count: 5}] [{value: 0, count: 7}, {value: 1, count: 6}] +3 [{value: a, count: 6}, {value: c, count: 4}] [{value: 1, count: 6}, {value: 2, count: 6}] +4 [{value: e, count: 7}, {value: b, count: 5}] [{value: 0, count: 9}, {value: 2, count: 5}] +5 [{value: b, count: 5}, {value: a, count: 3}] [{value: -2, count: 5}, {value: -1, count: 4}] + # Test approx_distinct for varchar(with Utf8View) / int statement ok CREATE TABLE aggregate_test_100_utf8view AS SELECT diff --git a/datafusion/sqllogictest/test_files/approx_top_k.slt b/datafusion/sqllogictest/test_files/approx_top_k.slt new file mode 100644 index 0000000000000..7f7c891bc30e8 --- /dev/null +++ b/datafusion/sqllogictest/test_files/approx_top_k.slt @@ -0,0 +1,307 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership +# SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements + +########### +# approx_top_k tests +########### + +# approx_top_k basic usage with string column +query ? +SELECT approx_top_k(column1, 2) FROM (VALUES ('apple'), ('banana'), ('apple'), ('cherry'), ('apple'), ('banana')) AS t(column1); +---- +[{value: apple, count: 3}, {value: banana, count: 2}] + +# approx_top_k with integer column +query ? +SELECT approx_top_k(column1, 2) FROM (VALUES (1), (2), (1), (3), (1), (2)) AS t(column1); +---- +[{value: 1, count: 3}, {value: 2, count: 2}] + +# approx_top_k with GROUP BY +query T? +SELECT column2, approx_top_k(column1, 2) FROM (VALUES ('a', 'x'), ('b', 'x'), ('a', 'x'), ('c', 'y'), ('c', 'y'), ('d', 'y')) AS t(column1, column2) GROUP BY column2 ORDER BY column2; +---- +x [{value: a, count: 2}, {value: b, count: 1}] +y [{value: c, count: 2}, {value: d, count: 1}] + +# approx_top_k with k=1 +query ? +SELECT approx_top_k(column1, 1) FROM (VALUES ('red'), ('blue'), ('red'), ('green'), ('red')) AS t(column1); +---- +[{value: red, count: 3}] + +# approx_top_k with NULLs (should be skipped) +query ? +SELECT approx_top_k(column1, 2) FROM (VALUES ('a'), (NULL), ('a'), ('b'), (NULL), ('b'), ('b')) AS t(column1); +---- +[{value: b, count: 3}, {value: a, count: 2}] + +# approx_top_k error: missing k argument +statement error .*expects 2 arguments.* +SELECT approx_top_k(column1) FROM (VALUES ('a')) AS t(column1); + +# approx_top_k error: k must be positive +statement error DataFusion error: Error during planning: approx_top_k requires k to be between 1 and 10000 +SELECT approx_top_k(column1, 0) FROM (VALUES ('a')) AS t(column1); + +# approx_top_k error: negative k +statement error DataFusion error: Error during planning: approx_top_k requires k to be between 1 and 10000, got -1 +SELECT approx_top_k(column1, -1) FROM (VALUES ('a')) AS t(column1); + +# approx_top_k error: k must be a constant +statement error DataFusion error: Error during planning: approx_top_k requires k to be a literal integer +SELECT approx_top_k(column1, column2) FROM (VALUES ('a', 2)) AS t(column1, column2); + +# approx_top_k error: k must not be NULL +statement error DataFusion error: Error during planning: approx_top_k requires k to be a literal integer, got NULL +SELECT approx_top_k(column1, NULL) FROM (VALUES ('a')) AS t(column1); + +# approx_top_k: k may be any constant integer expression +query ? +SELECT approx_top_k(column1, CAST('1' AS TINYINT UNSIGNED) + 1) FROM (VALUES ('a'), ('b'), ('a'), ('c')) AS t(column1); +---- +[{value: a, count: 2}, {value: b, count: 1}] + +statement error .*approx_top_k does not support DISTINCT.* +SELECT approx_top_k(DISTINCT column1, 2) FROM (VALUES ('a'), ('a')) AS t(column1); + +# Maximum k is accepted without eagerly allocating its full memory budget. +query ? +SELECT approx_top_k(column1, 10000) FROM (VALUES ('a')) AS t(column1); +---- +[{value: a, count: 1}] + +statement error DataFusion error: Error during planning: approx_top_k requires k to be between 1 and 10000 +SELECT approx_top_k(column1, 10001) FROM (VALUES ('a')) AS t(column1); + +# approx_top_k with WHERE clause +# Surviving rows are a, c, a, b -> a=2 and then a tie between b and c at 1, +# which is resolved on the value's bytes so the result is stable. +query ? +SELECT approx_top_k(column1, 2) FROM (VALUES ('a', 1), ('b', 2), ('a', 3), ('c', 4), ('a', 5), ('b', 6)) AS t(column1, column2) WHERE column2 > 2; +---- +[{value: a, count: 2}, {value: b, count: 1}] + +# approx_top_k on empty input (should return an empty list) +query ? +SELECT approx_top_k(column1, 3) FROM (VALUES ('a')) AS t(column1) WHERE false; +---- +[] + +# approx_top_k with all NULLs (should return an empty list) +query ? +SELECT approx_top_k(column1, 2) FROM (VALUES (NULL), (NULL), (NULL)) AS t(column1); +---- +[] + +# An empty window frame also returns an empty list +query I? +SELECT column2, approx_top_k(column1, 2) OVER (ORDER BY column2 ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) +FROM (VALUES ('a', 1), ('b', 2), ('a', 3)) AS t(column1, column2) +ORDER BY column2; +---- +1 [] +2 [{value: a, count: 1}] +3 [{value: a, count: 1}, {value: b, count: 1}] + +# So does a correlated subquery without matching rows +query I? +SELECT o.column1, (SELECT approx_top_k(i.column1, 2) FROM (VALUES (1), (1), (2)) AS i(column1) WHERE i.column1 = o.column1) +FROM (VALUES (1), (2), (3)) AS o(column1) +ORDER BY o.column1; +---- +1 [{value: 1, count: 2}] +2 [{value: 2, count: 1}] +3 [] + +# Physical encodings the sketch cannot store are rejected during planning +query error DataFusion error: Error during planning: approx_top_k does not support input type RunEndEncoded +SELECT approx_top_k(arrow_cast(column1, 'RunEndEncoded("run_ends": non-null Int32, "values": Int32)'), 2) +FROM (VALUES (1), (1), (2)) AS t(column1); + +# approx_top_k where k > number of distinct values (should return all distinct values) +query ? +SELECT approx_top_k(column1, 100) FROM (VALUES ('x'), ('y'), ('x')) AS t(column1); +---- +[{value: x, count: 2}, {value: y, count: 1}] + +# approx_top_k ties are broken deterministically (by the value's bytes, which +# for strings is lexicographic order) so results are stable +query ? +SELECT approx_top_k(column1, 4) FROM (VALUES ('delta'), ('alpha'), ('charlie'), ('bravo')) AS t(column1); +---- +[{value: alpha, count: 1}, {value: bravo, count: 1}, {value: charlie, count: 1}, {value: delta, count: 1}] + +# approx_top_k over a view-encoded column +query ? +SELECT approx_top_k(arrow_cast(column1, 'Utf8View'), 2) FROM (VALUES ('a'), ('b'), ('a'), ('a'), ('b')) AS t(column1); +---- +[{value: a, count: 3}, {value: b, count: 2}] + +# The returned values keep the input type; dictionaries are decoded to their value type +query TTT +SELECT + arrow_typeof(approx_top_k(arrow_cast(column1, 'LargeUtf8'), 1)), + arrow_typeof(approx_top_k(arrow_cast(column1, 'Dictionary(Int32, Utf8)'), 1)), + arrow_typeof(approx_top_k(arrow_cast(column1, 'Timestamp(Millisecond, Some("+05:00"))'), 1)) +FROM (VALUES (1)) AS t(column1); +---- +List(Struct("value": LargeUtf8, "count": non-null UInt64)) List(Struct("value": Utf8, "count": non-null UInt64)) List(Struct("value": Timestamp(ms, "+05:00"), "count": non-null UInt64)) + +query ? +SELECT approx_top_k(arrow_cast(column1, 'Dictionary(Int32, Utf8)'), 2) FROM (VALUES ('a'), ('b'), ('a')) AS t(column1); +---- +[{value: a, count: 2}, {value: b, count: 1}] + +query ?? +SELECT approx_top_k(column1, 1), approx_top_k(column2, 1) +FROM (VALUES (true, 1.5), (false, 2.25), (true, 1.5)) AS t(column1, column2); +---- +[{value: true, count: 2}] [{value: 1.5, count: 2}] + +query ?? +SELECT + approx_top_k(arrow_cast(column1, 'Decimal128(10, 2)'), 1), + approx_top_k(arrow_cast(column1, 'Decimal256(40, 3)'), 1) +FROM (VALUES (1.25), (3.5), (1.25)) AS t(column1); +---- +[{value: 1.25, count: 2}] [{value: 1.250, count: 2}] + +query ??? +SELECT + approx_top_k(arrow_cast(column1, 'Time32(Second)'), 1), + approx_top_k(arrow_cast(column1, 'Time64(Nanosecond)'), 1), + approx_top_k(arrow_cast(column2, 'Date32'), 1) +FROM (VALUES ('10:00:00', '2024-01-01'), ('11:30:00', '2024-01-02'), ('10:00:00', '2024-01-01')) AS t(column1, column2); +---- +[{value: 10:00:00, count: 2}] [{value: 10:00:00, count: 2}] [{value: 2024-01-01, count: 2}] + +# Fixed-size binary values, such as UUIDs, keep their type +query T? +SELECT arrow_typeof(approx_top_k(v, 1)), approx_top_k(v, 2) +FROM ( + SELECT arrow_cast(column1, 'FixedSizeBinary(16)') AS v + FROM (VALUES + (X'0123456789abcdef0123456789abcdef'), + (X'ffffffffffffffffffffffffffffffff'), + (X'0123456789abcdef0123456789abcdef') + ) AS t(column1) +); +---- +List(Struct("value": FixedSizeBinary(16), "count": non-null UInt64)) [{value: 0123456789abcdef0123456789abcdef, count: 2}, {value: ffffffffffffffffffffffffffffffff, count: 1}] + +# FILTER clauses are applied before values reach the sketch +query T? +SELECT column2, approx_top_k(column1, 2) FILTER (WHERE column3 > 0) +FROM (VALUES ('a', 'x', 1), ('b', 'x', 0), ('a', 'x', 1), ('b', 'x', 0), ('c', 'y', 1)) AS t(column1, column2, column3) +GROUP BY column2 ORDER BY column2; +---- +x [{value: a, count: 2}] +y [{value: c, count: 1}] + +# approx_top_k is order insensitive: an ORDER BY inside the call is accepted +# and ignored +query ? +SELECT approx_top_k(column1, 2 ORDER BY column2) +FROM (VALUES ('a', 2), ('b', 1), ('a', 3)) AS t(column1, column2); +---- +[{value: a, count: 2}, {value: b, count: 1}] + +########### +# Multi-partition tests +# +# The sqllogictest harness runs with target_partitions = 4, so these produce a +# two-phase aggregate and exercise the partial -> final state exchange +# (state / merge_batch) from SQL rather than only in unit tests. +########### + +# Built as a UNION ALL of disjoint ranges so the data really does land in four +# partitions; a plain CTAS over generate_series would leave it all in one and the +# per-partition summaries would be trivial. +statement ok +CREATE TABLE topk_low_cardinality AS +SELECT CASE WHEN v % 10 < 5 THEN 'hot' WHEN v % 10 < 8 THEN 'warm' ELSE 'cool' END AS item +FROM generate_series(1, 250) AS t(v) +UNION ALL +SELECT CASE WHEN v % 10 < 5 THEN 'hot' WHEN v % 10 < 8 THEN 'warm' ELSE 'cool' END AS item +FROM generate_series(251, 500) AS t(v) +UNION ALL +SELECT CASE WHEN v % 10 < 5 THEN 'hot' WHEN v % 10 < 8 THEN 'warm' ELSE 'cool' END AS item +FROM generate_series(501, 750) AS t(v) +UNION ALL +SELECT CASE WHEN v % 10 < 5 THEN 'hot' WHEN v % 10 < 8 THEN 'warm' ELSE 'cool' END AS item +FROM generate_series(751, 1000) AS t(v); + +# Few distinct values, so the merged result is exact. +query ? +SELECT approx_top_k(item, 2) FROM topk_low_cardinality; +---- +[{value: hot, count: 500}, {value: warm, count: 300}] + +# Same data with a GROUP BY, merged across partitions. +query T? +SELECT item, approx_top_k(item, 1) FROM topk_low_cardinality GROUP BY item ORDER BY item; +---- +cool [{value: cool, count: 200}] +hot [{value: hot, count: 500}] +warm [{value: warm, count: 300}] + +########### +# Approximation tests +# +# 9000 copies of 'dominant' plus 1000 singleton values. With k = 1 the summary +# tracks 3 counters, so filtering and eviction happen repeatedly in every +# partition and the alpha map is exercised. +########### + +statement ok +CREATE TABLE topk_high_cardinality AS +SELECT v % 3 AS grp, CASE WHEN v % 10 < 9 THEN 'dominant' ELSE 'rare_' || CAST(v AS VARCHAR) END AS item +FROM generate_series(1, 2500) AS t(v) +UNION ALL +SELECT v % 3 AS grp, CASE WHEN v % 10 < 9 THEN 'dominant' ELSE 'rare_' || CAST(v AS VARCHAR) END AS item +FROM generate_series(2501, 5000) AS t(v) +UNION ALL +SELECT v % 3 AS grp, CASE WHEN v % 10 < 9 THEN 'dominant' ELSE 'rare_' || CAST(v AS VARCHAR) END AS item +FROM generate_series(5001, 7500) AS t(v) +UNION ALL +SELECT v % 3 AS grp, CASE WHEN v % 10 < 9 THEN 'dominant' ELSE 'rare_' || CAST(v AS VARCHAR) END AS item +FROM generate_series(7501, 10000) AS t(v); + +# Space-Saving guarantees any item above total/capacity (10000/3 ~ 3333) is +# retained, so 'dominant' must be found despite the surrounding churn. Its +# reported count is an upper bound, hence the inequality rather than equality. +query TB +SELECT s['value'], s['count'] >= 9000 +FROM (SELECT unnest(approx_top_k(item, 1)) AS s FROM topk_high_cardinality); +---- +dominant true + +# The evicted long tail must not crowd out the heavy hitter even when more +# counters are requested. +query TB +SELECT s['value'], s['count'] >= 9000 +FROM (SELECT unnest(approx_top_k(item, 5)) AS s FROM topk_high_cardinality) +LIMIT 1; +---- +dominant true + +# Same with a GROUP BY: every group evicts and its partial summaries are merged +# across partitions. The reported count must be an upper bound of the exact one. +query ITB +SELECT a.grp, a.s['value'], a.s['count'] >= e.cnt +FROM (SELECT grp, unnest(approx_top_k(item, 1)) AS s FROM topk_high_cardinality GROUP BY grp) a +JOIN (SELECT grp, count(*) AS cnt FROM topk_high_cardinality WHERE item = 'dominant' GROUP BY grp) e + ON a.grp = e.grp +ORDER BY a.grp; +---- +0 dominant true +1 dominant true +2 dominant true + +statement ok +DROP TABLE topk_low_cardinality; + +statement ok +DROP TABLE topk_high_cardinality; diff --git a/docs/source/user-guide/expressions.md b/docs/source/user-guide/expressions.md index 8922165f040e9..f9f450cb5b0fd 100644 --- a/docs/source/user-guide/expressions.md +++ b/docs/source/user-guide/expressions.md @@ -280,6 +280,7 @@ select log(-1), log(0), sqrt(-1); | approx_median(expr) | Calculates an approximation of the median for `expr`. | | approx_percentile_cont(expr, percentile [, centroids]) | Calculates an approximation of the specified `percentile` for `expr`. Optional `centroids` parameter controls accuracy (default: 100). | | approx_percentile_cont_with_weight(expr, weight_expr, percentile [, centroids]) | Calculates an approximation of the specified `percentile` for `expr` and `weight_expr`. Optional `centroids` parameter controls accuracy (default: 100). | +| approx_top_k(expr, k) | Returns the approximate `k` most frequent values for `expr`, ranked by estimated count with lower-error estimates preferred when counts tie. | | bit_and(expr) | Computes the bitwise AND of all non-null input values for `expr`. | | bit_or(expr) | Computes the bitwise OR of all non-null input values for `expr`. | | bit_xor(expr) | Computes the bitwise exclusive OR of all non-null input values for `expr`. | diff --git a/docs/source/user-guide/sql/aggregate_functions.md b/docs/source/user-guide/sql/aggregate_functions.md index a3cebed016874..418a5636fd985 100644 --- a/docs/source/user-guide/sql/aggregate_functions.md +++ b/docs/source/user-guide/sql/aggregate_functions.md @@ -1091,6 +1091,7 @@ _Alias of [stddev](#stddev)._ - [approx_median](#approx_median) - [approx_percentile_cont](#approx_percentile_cont) - [approx_percentile_cont_with_weight](#approx_percentile_cont_with_weight) +- [approx_top_k](#approx_top_k) ### `approx_distinct` @@ -1229,3 +1230,33 @@ An alternative syntax is also supported: | 78.5 | +----------------------------------------------------------------------+ ``` + +### `approx_top_k` + +Returns the approximate most frequent (top-k) values with their estimated counts as a list of `{value, count}` structs. Values are ranked by estimated count, with lower-error estimates preferred when counts tie. + +Because the aggregate uses bounded memory, `count` is an upper-bound estimate. It is exact for a value that has been tracked since it was first seen. A value that starts being tracked later, because it was first seen after the summary filled up or because it was evicted and seen again, starts from an estimate of how often it may already have occurred, and distributed merging may add an omission bound from partitions where that value was not tracked. Values whose frequency is far from the top-k boundary are the ones reported reliably; ties and near-ties may be resolved arbitrarily. + +NULL values are skipped; an empty or all-NULL input returns an empty list `[]`. For float columns, -0.0 and +0.0 are treated as the same value, while different NaN representations are tracked separately. + +Supported input types are strings, binary (including fixed-size binary), booleans, integers, 32- and 64-bit floats, decimals, dates, times, and timestamps. `value` has the same type as `expression`, except that dictionary-encoded inputs are returned as their value type. + +```sql +approx_top_k(expression, k) +``` + +#### Arguments + +- **expression**: The expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **k**: The number of top elements to return. Must be a literal integer between 1 and 10,000. + +#### Example + +```sql +> SELECT approx_top_k(column_name, 3) FROM table_name; ++-----------------------------------------------------------------------------+ +| approx_top_k(column_name,Int64(3)) | ++-----------------------------------------------------------------------------+ +| [{value: foo, count: 3}, {value: bar, count: 2}, {value: baz, count: 1}] | ++-----------------------------------------------------------------------------+ +```