use crate::aggregates::group_values::HashValue;
use arrow::array::types::{IntervalDayTime, IntervalMonthDayNano};
use arrow::array::{
Array, ArrayRef, ArrowNativeTypeOp, ArrowPrimitiveType, LargeStringArray,
PrimitiveArray, StringArray, StringViewArray, builder::PrimitiveBuilder,
cast::AsArray, downcast_primitive,
};
use arrow::array::{ArrayAccessor, StringArrayType};
use arrow::datatypes::{DataType, i256};
use datafusion_common::Result;
use datafusion_common::exec_datafusion_err;
use datafusion_common::hash_utils::RandomState;
use half::f16;
use hashbrown::hash_table::{Entry, HashTable};
use std::borrow::BorrowMut;
use std::fmt::Debug;
use std::hash::BuildHasher;
use std::sync::Arc;
const NULL_HEAP_IDX: usize = usize::MAX - 1;
const VACANT_HEAP_IDX: usize = usize::MAX;
pub struct HashTableItem<ID> {
hash: u64,
pub id: Option<ID>,
pub heap_idx: usize,
}
struct TopKHashTable<ID> {
map: HashTable<usize>,
store: Vec<HashTableItem<ID>>,
free_indices: Vec<usize>,
free_slots: Vec<ID>,
limit: usize,
null_count: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InsertKind {
Existing,
New,
ReplacedNull,
}
pub trait ArrowHashTable {
fn set_batch(&mut self, ids: ArrayRef);
fn len(&self) -> usize;
fn update_heap_idx(&mut self, mapper: &[(usize, usize)]);
fn heap_idx_at(&self, map_idx: usize) -> usize;
fn take_all(&mut self, indexes: Vec<usize>) -> ArrayRef;
fn find_or_insert(
&mut self,
row_idx: usize,
replace_idx: usize,
) -> (usize, InsertKind);
fn insert_null(&mut self, row_idx: usize) -> bool;
fn remove_if_null(&mut self, row_idx: usize) -> bool;
fn null_map_idxs(&self, out: &mut Vec<usize>) -> usize;
}
pub fn is_supported_hash_key_type(kt: &DataType) -> bool {
kt.is_primitive()
|| matches!(
kt,
DataType::Utf8 | DataType::Utf8View | DataType::LargeUtf8
)
}
pub struct StringHashTable<S: Array>
where
for<'a> &'a S: StringArrayType<'a>,
{
owned: S,
map: TopKHashTable<String>,
rnd: RandomState,
}
struct PrimitiveHashTable<VAL: ArrowPrimitiveType> {
owned: PrimitiveArray<VAL>,
map: TopKHashTable<VAL::Native>,
rnd: RandomState,
value_type: DataType,
}
impl<S> StringHashTable<S>
where
S: Array + From<Vec<Option<String>>>,
for<'a> &'a S: StringArrayType<'a>,
{
pub fn new(limit: usize) -> Self {
Self {
owned: S::from(Vec::new()),
map: TopKHashTable::new(limit, limit * 10),
rnd: RandomState::default(),
}
}
#[inline]
fn eq_fn(id: Option<&str>) -> impl Fn(&Option<String>) -> bool {
move |mi| id == mi.as_deref()
}
}
impl<S> ArrowHashTable for StringHashTable<S>
where
S: Array + Clone + From<Vec<Option<String>>> + 'static,
for<'a> &'a S: StringArrayType<'a>,
{
fn set_batch(&mut self, ids: ArrayRef) {
self.owned = ids
.as_any()
.downcast_ref::<S>()
.expect("Unsupported data type")
.clone();
}
fn len(&self) -> usize {
self.map.len()
}
fn update_heap_idx(&mut self, mapper: &[(usize, usize)]) {
self.map.update_heap_idx(mapper);
}
fn heap_idx_at(&self, map_idx: usize) -> usize {
self.map.heap_idx_at(map_idx)
}
fn take_all(&mut self, indexes: Vec<usize>) -> ArrayRef {
let ids = self.map.take_all(indexes);
Arc::new(S::from(ids))
}
fn find_or_insert(
&mut self,
row_idx: usize,
replace_idx: usize,
) -> (usize, InsertKind) {
let id = some_value(&self.owned, row_idx);
let hash = self.rnd.hash_one(id);
self.map
.find_or_insert(hash, id, replace_idx, Self::eq_fn(id))
}
fn insert_null(&mut self, row_idx: usize) -> bool {
let id = some_value(&self.owned, row_idx);
let hash = self.rnd.hash_one(id);
self.map.insert_null(hash, id, Self::eq_fn(id))
}
fn remove_if_null(&mut self, row_idx: usize) -> bool {
let id = some_value(&self.owned, row_idx);
let hash = self.rnd.hash_one(id);
self.map.remove_if_null(hash, Self::eq_fn(id))
}
fn null_map_idxs(&self, out: &mut Vec<usize>) -> usize {
self.map.null_map_idxs(out)
}
}
impl<VAL: ArrowPrimitiveType> PrimitiveHashTable<VAL>
where
VAL::Native: HashValue,
Option<VAL::Native>: HashValue,
{
pub fn new(limit: usize, value_type: DataType) -> Self {
Self {
owned: PrimitiveArray::<VAL>::new_null(0).with_data_type(value_type.clone()),
map: TopKHashTable::new(limit, limit * 10),
rnd: RandomState::default(),
value_type,
}
}
#[inline]
fn id_and_hash(&self, row_idx: usize) -> (Option<VAL::Native>, u64) {
let id = some_value(&self.owned, row_idx).map(HashValue::normalize_key);
let hash: u64 = id.hash(&self.rnd);
(id, hash)
}
#[inline]
fn eq_fn(id: Option<VAL::Native>) -> impl Fn(&Option<VAL::Native>) -> bool {
move |mi| match (id, *mi) {
(Some(left), Some(right)) => left.is_eq(right),
(None, None) => true,
_ => false,
}
}
}
impl<VAL: ArrowPrimitiveType> ArrowHashTable for PrimitiveHashTable<VAL>
where
VAL::Native: HashValue,
Option<VAL::Native>: HashValue,
{
fn set_batch(&mut self, ids: ArrayRef) {
self.owned = ids.as_primitive().clone();
}
fn len(&self) -> usize {
self.map.len()
}
fn update_heap_idx(&mut self, mapper: &[(usize, usize)]) {
self.map.update_heap_idx(mapper);
}
fn heap_idx_at(&self, map_idx: usize) -> usize {
self.map.heap_idx_at(map_idx)
}
fn take_all(&mut self, indexes: Vec<usize>) -> ArrayRef {
let ids = self.map.take_all(indexes);
let mut builder: PrimitiveBuilder<VAL> =
PrimitiveArray::builder(ids.len()).with_data_type(self.value_type.clone());
for id in ids.into_iter() {
builder.append_option(id);
}
let ids = builder.finish();
Arc::new(ids)
}
fn find_or_insert(
&mut self,
row_idx: usize,
replace_idx: usize,
) -> (usize, InsertKind) {
let (id, hash) = self.id_and_hash(row_idx);
self.map
.find_or_insert(hash, id.as_ref(), replace_idx, Self::eq_fn(id))
}
fn insert_null(&mut self, row_idx: usize) -> bool {
let (id, hash) = self.id_and_hash(row_idx);
self.map.insert_null(hash, id.as_ref(), Self::eq_fn(id))
}
fn remove_if_null(&mut self, row_idx: usize) -> bool {
let (id, hash) = self.id_and_hash(row_idx);
self.map.remove_if_null(hash, Self::eq_fn(id))
}
fn null_map_idxs(&self, out: &mut Vec<usize>) -> usize {
self.map.null_map_idxs(out)
}
}
impl<ID> TopKHashTable<ID> {
pub fn new(limit: usize, capacity: usize) -> Self {
Self {
map: HashTable::with_capacity(capacity),
store: Vec::with_capacity(capacity),
free_indices: Vec::new(),
free_slots: Vec::new(),
limit,
null_count: 0,
}
}
pub fn heap_idx_at(&self, map_idx: usize) -> usize {
self.store[map_idx].heap_idx
}
fn remove_at(&mut self, map_idx: usize) {
let hash = self.store[map_idx].hash;
let eq = |idx: &usize| *idx == map_idx;
let hasher = |idx: &usize| self.store[*idx].hash;
match self.map.entry(hash, eq, hasher) {
Entry::Occupied(entry) => {
let (removed_idx, _) = entry.remove();
let mi = &mut self.store[removed_idx];
debug_assert!(mi.is_occupied());
mi.heap_idx = VACANT_HEAP_IDX;
match mi.id.take() {
Some(slot) if Self::use_free_slots() => {
self.free_slots.push(slot);
}
_ => (),
}
self.free_indices.push(removed_idx);
}
Entry::Vacant(_) => unreachable!(),
}
}
pub fn remove_if_full(&mut self, replace_idx: usize) -> usize {
let valued_len = self.map.len() - self.null_count;
if valued_len >= self.limit {
self.remove_at(replace_idx);
0 } else {
valued_len }
}
fn update_heap_idx(&mut self, mapper: &[(usize, usize)]) {
for (m, h) in mapper {
self.store[*m].heap_idx = *h;
}
}
const fn use_free_slots() -> bool {
std::mem::needs_drop::<ID>()
}
pub fn find_or_insert<Q>(
&mut self,
hash: u64,
id: Option<&Q>,
replace_idx: usize,
mut eq: impl FnMut(&Option<ID>) -> bool,
) -> (usize, InsertKind)
where
Q: ToOwned<Owned = ID> + ?Sized,
{
let mut replaced_null = false;
let eq_fn = |idx: &usize| eq(&self.store[*idx].id);
if let Some(&map_idx) = self.map.find(hash, eq_fn) {
if self.store[map_idx].is_null() {
self.remove_at(map_idx);
self.null_count -= 1;
replaced_null = true;
} else {
return (map_idx, InsertKind::Existing);
}
}
let heap_idx = self.remove_if_full(replace_idx);
let store_idx = self.push_store_item(hash, id, heap_idx);
let kind = if replaced_null {
InsertKind::ReplacedNull
} else {
InsertKind::New
};
(store_idx, kind)
}
fn push_store_item<Q>(&mut self, hash: u64, id: Option<&Q>, heap_idx: usize) -> usize
where
Q: ToOwned<Owned = ID> + ?Sized,
{
let id = if Self::use_free_slots() {
id.map(|id| match self.free_slots.pop() {
Some(mut slot) => {
id.clone_into(&mut slot);
slot
}
_ => id.to_owned(),
})
} else {
debug_assert!(self.free_slots.is_empty(), "primitives should not pool");
id.map(ToOwned::to_owned)
};
let mi = HashTableItem::new(hash, id, heap_idx);
let store_idx = if let Some(idx) = self.free_indices.pop() {
debug_assert!(self.store[idx].is_vacant(), "slot should be empty");
self.store[idx] = mi;
idx
} else {
self.store.push(mi);
self.store.len() - 1
};
let hasher = |idx: &usize| self.store[*idx].hash;
if self.map.len() == self.map.capacity() {
self.map.reserve(self.limit, hasher);
}
self.map.insert_unique(hash, store_idx, hasher);
store_idx
}
pub fn insert_null<Q>(
&mut self,
hash: u64,
id: Option<&Q>,
mut eq: impl FnMut(&Option<ID>) -> bool,
) -> bool
where
Q: ToOwned<Owned = ID> + ?Sized,
ID: BorrowMut<Q::Owned>,
{
let eq_fn = |idx: &usize| eq(&self.store[*idx].id);
if self.map.find(hash, eq_fn).is_some() {
return false;
}
if self.null_count >= self.limit {
return false;
}
_ = self.push_store_item(hash, id, NULL_HEAP_IDX);
self.null_count += 1;
true
}
pub fn remove_if_null(
&mut self,
hash: u64,
mut eq: impl FnMut(&Option<ID>) -> bool,
) -> bool {
let eq_fn = |idx: &usize| eq(&self.store[*idx].id);
if let Some(&map_idx) = self.map.find(hash, eq_fn)
&& self.store[map_idx].is_null()
{
self.remove_at(map_idx);
self.null_count -= 1;
return true;
}
false
}
pub fn null_map_idxs(&self, out: &mut Vec<usize>) -> usize {
let iter = self
.store
.iter()
.enumerate()
.filter_map(|(idx, item)| item.is_null().then_some(idx));
let prev_len = out.len();
out.extend(iter);
debug_assert_eq!(out.len(), self.null_count + prev_len);
self.null_count
}
pub fn len(&self) -> usize {
self.map.len()
}
pub fn take_all(&mut self, idxs: Vec<usize>) -> Vec<Option<ID>> {
let ids = idxs
.into_iter()
.map(|idx| self.store[idx].id.take())
.collect();
self.map.clear();
self.store.clear();
self.free_indices.clear();
self.null_count = 0;
ids
}
}
impl<ID> HashTableItem<ID> {
pub fn new(hash: u64, id: Option<ID>, heap_idx: usize) -> Self {
Self { hash, id, heap_idx }
}
#[inline]
pub fn is_null(&self) -> bool {
self.heap_idx == NULL_HEAP_IDX
}
#[inline]
pub fn is_vacant(&self) -> bool {
self.heap_idx == VACANT_HEAP_IDX
}
#[inline]
pub fn is_occupied(&self) -> bool {
self.heap_idx != VACANT_HEAP_IDX
}
}
impl HashValue for Option<String> {
fn hash(&self, state: &RandomState) -> u64 {
state.hash_one(self)
}
}
macro_rules! hash_float {
($($t:ty),+) => {
$(impl HashValue for Option<$t> {
fn hash(&self, state: &RandomState) -> u64 {
self.map(|me| me.hash(state)).unwrap_or(0)
}
})+
};
}
macro_rules! has_integer {
($($t:ty),+) => {
$(impl HashValue for Option<$t> {
fn hash(&self, state: &RandomState) -> u64 {
self.map(|me| me.hash(state)).unwrap_or(0)
}
})+
};
}
has_integer!(i8, i16, i32, i64, i128, i256);
has_integer!(u8, u16, u32, u64);
has_integer!(IntervalDayTime, IntervalMonthDayNano);
hash_float!(f16, f32, f64);
#[inline]
fn some_value<'a, A>(array: &'a A, index: usize) -> Option<<&'a A as ArrayAccessor>::Item>
where
&'a A: ArrayAccessor,
{
if array.is_null(index) {
None
} else {
Some(array.value(index))
}
}
pub fn new_hash_table(
limit: usize,
kt: DataType,
) -> Result<Box<dyn ArrowHashTable + Send>> {
macro_rules! downcast_helper {
($kt:ty, $d:ident) => {
return Ok(Box::new(PrimitiveHashTable::<$kt>::new(limit, kt)))
};
}
downcast_primitive! {
kt => (downcast_helper, kt),
DataType::Utf8 => return Ok(Box::new(StringHashTable::<StringArray>::new(limit))),
DataType::LargeUtf8 => return Ok(Box::new(StringHashTable::<LargeStringArray>::new(limit))),
DataType::Utf8View => return Ok(Box::new(StringHashTable::<StringViewArray>::new(limit))),
_ => {}
}
Err(exec_datafusion_err!(
"Can't create HashTable for type: {kt:?}"
))
}
#[cfg(test)]
mod tests {
use super::*;
use arrow::array::TimestampMillisecondArray;
use arrow::datatypes::{Float16Type, Float32Type, Float64Type};
use arrow_schema::TimeUnit;
use std::collections::BTreeMap;
fn assert_nulls<ID>(map: &TopKHashTable<ID>, expected: &[usize]) {
assert_eq!(map.null_count, expected.len());
let mut actual = Vec::new();
assert_eq!(map.null_map_idxs(&mut actual), expected.len());
assert_eq!(actual, expected);
}
fn check_float_keys<T: ArrowPrimitiveType>(
nan: T::Native,
other_nan: T::Native,
negative_zero: T::Native,
) -> Result<()> {
let ids: ArrayRef = Arc::new(PrimitiveArray::<T>::from_iter_values([
nan,
nan,
other_nan,
negative_zero,
T::Native::default(),
]));
let data_type = ids.data_type().clone();
let mut ht = new_hash_table(3, data_type.clone())?;
ht.set_batch(Arc::clone(&ids));
let (nan_idx, kind) = ht.find_or_insert(0, 0);
assert_eq!(kind, InsertKind::New);
assert_eq!(ht.find_or_insert(1, 0), (nan_idx, InsertKind::Existing));
let (_, kind) = ht.find_or_insert(2, 0);
assert_eq!(kind, InsertKind::New);
let (zero_idx, kind) = ht.find_or_insert(3, 0);
assert_eq!(kind, InsertKind::New);
assert_eq!(ht.find_or_insert(4, 0), (zero_idx, InsertKind::Existing));
assert_eq!(ht.len(), 3);
let keys = ht.take_all(vec![zero_idx]);
assert!(
keys.as_primitive::<T>()
.value(0)
.is_eq(T::Native::default())
);
assert!(ht.insert_null(0));
assert!(!ht.insert_null(1));
let (nan_idx, kind) = ht.find_or_insert(1, 0);
assert_eq!(kind, InsertKind::ReplacedNull);
ht.take_all(vec![nan_idx]);
assert!(ht.insert_null(0));
assert!(ht.remove_if_null(1));
assert_eq!(ht.len(), 0);
let mut ht = new_hash_table(1, data_type)?;
ht.set_batch(ids);
ht.find_or_insert(0, 0);
let (zero_idx, kind) = ht.find_or_insert(3, 0);
assert_eq!(kind, InsertKind::New);
assert_eq!(ht.len(), 1);
let keys = ht.take_all(vec![zero_idx]);
assert!(
keys.as_primitive::<T>()
.value(0)
.is_eq(T::Native::default())
);
Ok(())
}
#[test]
fn should_handle_float_keys() -> Result<()> {
check_float_keys::<Float16Type>(
f16::from_bits(0x7e00),
f16::from_bits(0x7e01),
f16::from_bits(0x8000),
)?;
check_float_keys::<Float32Type>(
f32::NAN,
f32::from_bits(f32::NAN.to_bits() + 1),
-0.0,
)?;
check_float_keys::<Float64Type>(
f64::NAN,
f64::from_bits(f64::NAN.to_bits() + 1),
-0.0,
)
}
#[test]
fn should_emit_correct_type() -> Result<()> {
let ids =
TimestampMillisecondArray::from(vec![1000]).with_timezone("UTC".to_string());
let dt = DataType::Timestamp(TimeUnit::Millisecond, Some("UTC".into()));
let mut ht = new_hash_table(1, dt.clone())?;
ht.set_batch(Arc::new(ids));
ht.find_or_insert(0, 0);
let ids = ht.take_all(vec![0]);
assert_eq!(ids.data_type(), &dt);
Ok(())
}
#[test]
fn should_resize_properly() -> Result<()> {
let mut heap_to_map = BTreeMap::<usize, usize>::new();
let mut map = TopKHashTable::<String>::new(5, 3);
for (heap_idx, id) in ["1", "2", "3", "4", "5"].iter().enumerate() {
let value = Some(id.to_string());
let hash = heap_idx as u64;
let (map_idx, kind) =
map.find_or_insert(hash, value.as_ref(), heap_idx, |v| *v == value);
assert_eq!(kind, InsertKind::New, "Entry should be new");
heap_to_map.insert(heap_idx, map_idx);
}
assert_eq!(map.len(), 5);
let (_heap_idxs, map_idxs): (Vec<_>, Vec<_>) = heap_to_map.into_iter().unzip();
let ids = map.take_all(map_idxs);
assert_eq!(
format!("{ids:?}"),
r#"[Some("1"), Some("2"), Some("3"), Some("4"), Some("5")]"#
);
assert_eq!(map.len(), 0, "Map should have been cleared!");
Ok(())
}
#[test]
fn should_track_null_groups() -> Result<()> {
let mut map = TopKHashTable::<String>::new(2, 10);
let a = Some("a".to_string());
let b = Some("b".to_string());
let c = Some("c".to_string());
assert!(map.insert_null(100, a.as_ref(), |v| *v == a));
assert!(map.insert_null(200, b.as_ref(), |v| *v == b));
assert!(!map.insert_null(300, c.as_ref(), |v| *v == c));
assert!(!map.insert_null(100, a.as_ref(), |v| *v == a));
assert_nulls(&map, &[0, 1]);
let (map_idx, kind) = map.find_or_insert(200, b.as_ref(), 0, |v| *v == b);
assert_eq!(kind, InsertKind::ReplacedNull, "NULL group should convert");
assert_eq!(map.heap_idx_at(map_idx), 0, "Heap should append at 0");
assert_nulls(&map, &[0]);
map.remove_if_null(100, |v| *v == a);
assert_nulls(&map, &[]);
map.remove_if_null(100, |v| *v == a);
map.remove_if_null(200, |v| *v == b);
assert_eq!(map.len(), 1);
Ok(())
}
#[test]
fn should_track_null_id() {
let mut map = TopKHashTable::<String>::new(2, 10);
let hash = 0;
let none = Option::<&str>::None;
assert!(map.insert_null(hash, none, Option::is_none));
assert_nulls(&map, &[0]);
assert!(!map.insert_null(hash, none, Option::is_none));
assert_nulls(&map, &[0]);
assert!(map.remove_if_null(hash, Option::is_none));
assert_nulls(&map, &[]);
}
#[test]
fn should_reuse_all_freed_store_slots() -> Result<()> {
let mut map = TopKHashTable::<String>::new(1, 10);
let a = Some("a".to_string());
let b = Some("b".to_string());
let c = Some("c".to_string());
let (b_idx, kind) = map.find_or_insert(100, b.as_ref(), 0, |v| *v == b);
assert_eq!(kind, InsertKind::New);
assert!(map.insert_null(200, a.as_ref(), |v| *v == a));
let (_, kind) = map.find_or_insert(200, a.as_ref(), b_idx, |v| *v == a);
assert_eq!(kind, InsertKind::ReplacedNull);
assert!(map.insert_null(300, c.as_ref(), |v| *v == c));
assert_eq!(map.store.len(), 2);
Ok(())
}
}