crates/kleene-index/src/names.rs
//! Name to id: a minimal perfect hash over the distinct strings of a column, after the
//! idea of PtrHash (Groot Koerkamp, 2025): keys hash into buckets, each bucket gets the
//! first pilot that sends all its keys to free slots, buckets largest first; the few slots
//! past the key count are sent back onto the free slots below it. A lookup is one hash
//! (folded multiplies, sixteen bytes a step), one pilot, at most one remap entry, one
//! 16-byte slot (the row and where its bytes lie in the column's value buffer) and one
//! compare of those bytes, so an unknown name is refused, never mapped to a wrong id.
use arrow_array::{
Array, ArrayRef, BinaryArray, BinaryViewArray, LargeBinaryArray, LargeStringArray, StringArray,
StringViewArray, cast::AsArray,
};
use arrow_buffer::ScalarBuffer;
use arrow_schema::DataType;
use crate::error::{Result, bad};
/// Keys per bucket, on average.
const LAMBDA: f64 = 3.0;
/// Keys per slot: a few slots more than keys, so the last buckets find room fast.
const ALPHA: f64 = 0.97;
/// Seeds tried before a build gives up (each one fails with a tiny chance).
const SEEDS: u64 = 16;
/// The first meta word of stored parts: the hash and slot functions they were built with.
const VERSION: u64 = 2;
/// A slot whose bytes are read through the column (a view column, or a name past
/// `u32::MAX` bytes).
const BY_ROW: u32 = u32::MAX;
/// A string or bytes column of the set (a set's string tables are `Binary`), read in
/// place.
#[derive(Clone, Debug)]
enum Strings {
Utf8(StringArray),
Large(LargeStringArray),
View(StringViewArray),
Bin(BinaryArray),
LargeBin(LargeBinaryArray),
BinView(BinaryViewArray),
}
impl Strings {
fn of(a: &ArrayRef) -> Result<Self> {
Ok(match a.data_type() {
DataType::Utf8 => Strings::Utf8(a.as_string::<i32>().clone()),
DataType::LargeUtf8 => Strings::Large(a.as_string::<i64>().clone()),
DataType::Utf8View => Strings::View(a.as_string_view().clone()),
DataType::Binary => Strings::Bin(a.as_binary::<i32>().clone()),
DataType::LargeBinary => Strings::LargeBin(a.as_binary::<i64>().clone()),
DataType::BinaryView => Strings::BinView(a.as_binary_view().clone()),
t => {
return Err(bad(format!(
"a name column holds strings or bytes, not {t}"
)));
}
})
}
fn array(&self) -> &dyn Array {
match self {
Strings::Utf8(a) => a,
Strings::Large(a) => a,
Strings::View(a) => a,
Strings::Bin(a) => a,
Strings::LargeBin(a) => a,
Strings::BinView(a) => a,
}
}
fn len(&self) -> usize {
self.array().len()
}
/// The value buffer of an offsets column (where its strings' bytes lie), `None` for a
/// view column.
fn values(&self) -> Option<arrow_buffer::Buffer> {
Some(match self {
Strings::Utf8(a) => a.values().clone(),
Strings::Large(a) => a.values().clone(),
Strings::Bin(a) => a.values().clone(),
Strings::LargeBin(a) => a.values().clone(),
Strings::View(_) | Strings::BinView(_) => return None,
})
}
/// Where row `i`'s bytes start in [`Strings::values`] (offsets columns).
fn start(&self, i: usize) -> u64 {
match self {
Strings::Utf8(a) => a.value_offsets()[i] as u64,
Strings::Large(a) => a.value_offsets()[i] as u64,
Strings::Bin(a) => a.value_offsets()[i] as u64,
Strings::LargeBin(a) => a.value_offsets()[i] as u64,
Strings::View(_) | Strings::BinView(_) => 0,
}
}
#[inline]
fn get(&self, i: usize) -> Option<&[u8]> {
if self.array().is_null(i) {
return None;
}
Some(match self {
Strings::Utf8(a) => a.value(i).as_bytes(),
Strings::Large(a) => a.value(i).as_bytes(),
Strings::View(a) => a.value(i).as_bytes(),
Strings::Bin(a) => a.value(i),
Strings::LargeBin(a) => a.value(i),
Strings::BinView(a) => a.value(i),
})
}
}
/// A slot as a lookup reads it: the row and where its bytes lie, in one 16-byte read.
#[derive(Clone, Copy, Debug)]
#[repr(C, align(16))]
struct Slot {
start: u64,
/// The length of the bytes, or [`BY_ROW`]: read them through the column.
len: u32,
row: u32,
}
/// A name's row: the minimal perfect hash over a string column's distinct values, each
/// slot holding the first row with that value. Nulls have no row.
#[derive(Clone, Debug)]
pub struct Names {
strings: Strings,
/// The value buffer of an offsets column.
values: Option<arrow_buffer::Buffer>,
/// `[seed, keys, buckets, slots]`.
meta: [u64; 4],
/// A `u16` pilot per bucket, four to a word (as stored).
pilots: ScalarBuffer<u64>,
/// The same pilots one to a `u16` (the same buffer).
pilot: ScalarBuffer<u16>,
/// For each slot from `keys` up: the free slot below `keys` it stands for.
remap: ScalarBuffer<u32>,
/// The row of the key in each slot (as stored).
rows: ScalarBuffer<u32>,
/// Each slot's row and bytes, made from `rows` and the column.
slots: Vec<Slot>,
}
/// The parts [`Names::parts`] gives and [`Names::from_parts`] takes: the meta words
/// (version, seed, keys, buckets, slots), the pilots, the remap and the rows.
pub type NameParts = (
ScalarBuffer<u64>,
ScalarBuffer<u64>,
ScalarBuffer<u32>,
ScalarBuffer<u32>,
);
#[inline]
fn mix(mut x: u64) -> u64 {
// murmur3's finalizer
x ^= x >> 33;
x = x.wrapping_mul(0xff51_afd7_ed55_8ccd);
x ^= x >> 33;
x = x.wrapping_mul(0xc4ce_b9fe_1a85_ec53);
x ^ (x >> 33)
}
/// The 64-bit halves of `a * b` folded together.
#[inline]
fn fold(a: u64, b: u64) -> u64 {
let f = u128::from(a) * u128::from(b);
(f as u64) ^ ((f >> 64) as u64)
}
#[inline]
fn word(b: &[u8], at: usize) -> u64 {
u64::from_le_bytes(b[at..at + 8].try_into().expect("eight bytes"))
}
const K0: u64 = 0x2d35_8dcc_aa6c_78a5;
const K1: u64 = 0x8bb8_4b93_962e_acc9;
const K2: u64 = 0x4b33_a62e_d433_d4a3;
const K3: u64 = 0x4d5a_2da5_1de1_aa47;
/// A 64-bit hash of `b` under `seed`: sixteen bytes a folded multiply (the last sixteen
/// read overlapping), short names in one.
#[inline]
fn hash(b: &[u8], seed: u64) -> u64 {
let n = b.len();
let mut h = seed ^ (n as u64).wrapping_mul(K0);
if n <= 16 {
let (x, y) = if n >= 8 {
(word(b, 0), word(b, n - 8))
} else if n >= 4 {
let w =
|at: usize| u64::from(u32::from_le_bytes(b[at..at + 4].try_into().expect("four")));
(w(0), w(n - 4))
} else if n > 0 {
(
u64::from(b[0]) | u64::from(b[n / 2]) << 8 | u64::from(b[n - 1]) << 16,
0,
)
} else {
(0, 0)
};
h = fold(x ^ K1, y ^ h ^ K2);
} else {
let mut at = 0;
while at + 16 < n {
h = fold(word(b, at) ^ K1, word(b, at + 8) ^ h);
at += 16;
}
h = fold(word(b, n - 16) ^ K2, word(b, n - 8) ^ h);
}
fold(h ^ K3, K0 ^ (n as u64))
}
#[inline]
fn reduce(h: u64, n: u64) -> u64 {
((u128::from(h) * u128::from(n)) >> 64) as u64
}
/// The slot of a key of hash `h` under `pilot`: the pilot's hash xored in, one multiply
/// to bring the low bits up (keys of one bucket share their high bits), then reduced.
#[inline]
fn slot(h: u64, pilot: u64, slots: u64) -> u64 {
reduce(
(h ^ pilot.wrapping_mul(0x517c_c1b7_2722_0a95)).wrapping_mul(K3 | 1),
slots,
)
}
impl Names {
/// The index over string column `col` (`Utf8`, `LargeUtf8`, `Utf8View`, or the bytes
/// kinds `Binary`, `LargeBinary`, `BinaryView` a set's string tables are): a row per
/// distinct value, the first one; nulls left out. Refused when it holds more than
/// `u32::MAX` rows.
pub fn build(col: &ArrayRef) -> Result<Self> {
let strings = Strings::of(col)?;
let n = strings.len();
if n > u32::MAX as usize {
return Err(bad("a name column of more than u32::MAX rows"));
}
for s in 0..SEEDS {
let seed = mix(0x6b6c_6565_6e65 ^ s);
if let Some(names) = Self::try_seed(&strings, seed)? {
return Ok(names);
}
}
Err(bad("no seed gave a perfect hash (a hash flaw)"))
}
fn try_seed(strings: &Strings, seed: u64) -> Result<Option<Self>> {
let n = strings.len();
// (hash, row) of every value, the first row of each distinct value only
let pieces = gatling::gatling_forkjoin::gatling_for_each(n.div_ceil(1 << 16), 0, |p| {
let (lo, hi) = (p << 16, ((p + 1) << 16).min(n));
(lo..hi)
.filter_map(|i| strings.get(i).map(|b| (hash(b, seed), i as u32)))
.collect::<Vec<(u64, u32)>>()
});
let mut keys: Vec<(u64, u32)> = Vec::with_capacity(pieces.iter().map(Vec::len).sum());
for p in pieces {
keys.extend(p);
}
gatling::gatling_sort::gatling_sort_unstable_by(&mut keys, |a, b| a.cmp(b));
let mut kept: Vec<(u64, u32)> = Vec::with_capacity(keys.len());
let mut run = 0;
for (k, &(h, r)) in keys.iter().enumerate() {
if k > 0 && h != keys[k - 1].0 {
run = kept.len();
}
// a repeat of a kept value (same hash, same bytes) is dropped; the first row
// stays (rows rise within a hash)
let again = kept[run..]
.iter()
.any(|&(_, q)| strings.get(q as usize) == strings.get(r as usize));
if !again {
kept.push((h, r));
}
}
let keys = kept;
let m = keys.len() as u64;
let buckets = ((m as f64 / LAMBDA).ceil() as u64).max(1);
let slots = ((m as f64 / ALPHA).ceil() as u64).max(m).max(1);
// keys by bucket
let mut start = vec![0u32; buckets as usize + 1];
for &(h, _) in &keys {
start[reduce(h, buckets) as usize + 1] += 1;
}
for b in 0..buckets as usize {
start[b + 1] += start[b];
}
let mut fill = start.clone();
let mut by_bucket = vec![(0u64, 0u32); keys.len()];
for &(h, r) in &keys {
let b = reduce(h, buckets) as usize;
by_bucket[fill[b] as usize] = (h, r);
fill[b] += 1;
}
let mut order: Vec<u32> = (0..buckets as u32).collect();
let size = |b: u32| start[b as usize + 1] - start[b as usize];
order.sort_unstable_by_key(|&b| std::cmp::Reverse(size(b)));
// place each bucket, largest first
let mut taken = vec![0u64; (slots as usize).div_ceil(64)];
let mut row_of = vec![u32::MAX; slots as usize];
let mut pilots = vec![0u64; (buckets as usize).div_ceil(4)];
let mut tried: Vec<u64> = Vec::with_capacity(8);
for &b in &order {
let ks = &by_bucket[start[b as usize] as usize..start[b as usize + 1] as usize];
if ks.is_empty() {
continue;
}
let mut placed = None;
'pilot: for p in 0..=u64::from(u16::MAX) {
tried.clear();
for &(h, _) in ks {
let s = slot(h, p, slots);
if taken[s as usize / 64] >> (s % 64) & 1 == 1 || tried.contains(&s) {
continue 'pilot;
}
tried.push(s);
}
placed = Some(p);
break;
}
let Some(p) = placed else {
return Ok(None);
};
pilots[b as usize / 4] |= p << (16 * (b % 4));
for (&(_, r), &s) in ks.iter().zip(&tried) {
taken[s as usize / 64] |= 1 << (s % 64);
row_of[s as usize] = r;
}
}
// slots past m onto the free slots below m
let mut free = (0..m).filter(|&s| taken[s as usize / 64] >> (s % 64) & 1 == 0);
let mut remap = vec![0u32; (slots - m) as usize];
for s in m..slots {
if taken[s as usize / 64] >> (s % 64) & 1 == 1 {
let f = free
.next()
.expect("as many free slots below m as taken above");
remap[(s - m) as usize] = f as u32;
row_of[f as usize] = row_of[s as usize];
}
}
row_of.truncate(m as usize);
Ok(Some(Self::assemble(
strings.clone(),
[seed, m, buckets, slots],
pilots.into(),
remap.into(),
row_of.into(),
)))
}
/// The index from its parts: the pilots seen one to a `u16`, each slot's bytes found.
fn assemble(
strings: Strings,
meta: [u64; 4],
pilots: ScalarBuffer<u64>,
remap: ScalarBuffer<u32>,
rows: ScalarBuffer<u32>,
) -> Self {
let values = strings.values();
let slots = rows
.iter()
.map(|&r| {
let len = strings.get(r as usize).map_or(0, <[u8]>::len);
match (&values, u32::try_from(len)) {
(Some(_), Ok(len)) if len != BY_ROW => Slot {
start: strings.start(r as usize),
len,
row: r,
},
_ => Slot {
start: 0,
len: BY_ROW,
row: r,
},
}
})
.collect();
// little-endian words: pilot b is the b-th u16 of the buffer
let pilot = ScalarBuffer::new(pilots.inner().clone(), 0, pilots.len() * 4);
Names {
strings,
values,
meta,
pilots,
pilot,
remap,
rows,
slots,
}
}
/// The index from its stored parts (as [`Names::parts`] gave them) over the same
/// column.
pub fn from_parts(col: &ArrayRef, parts: NameParts) -> Result<Self> {
let (meta, pilots, remap, rows) = parts;
let strings = Strings::of(col)?;
let [version, seed, m, buckets, slots]: [u64; 5] = meta[..]
.try_into()
.map_err(|_| bad("stored names: five meta words"))?;
if version != VERSION {
return Err(bad(format!(
"stored names of version {version}, this build reads {VERSION}"
)));
}
if rows.len() as u64 != m
|| remap.len() as u64 != slots.saturating_sub(m)
|| pilots.len() as u64 != buckets.div_ceil(4)
|| buckets == 0
|| rows.iter().any(|&r| r as usize >= strings.len())
|| remap.iter().any(|&r| u64::from(r) >= m.max(1))
{
return Err(bad("stored names do not fit together or the column"));
}
Ok(Self::assemble(
strings,
[seed, m, buckets, slots],
pilots,
remap,
rows,
))
}
/// The meta words, pilots, remap and rows, for storing.
pub fn parts(&self) -> NameParts {
(
[VERSION]
.into_iter()
.chain(self.meta)
.collect::<Vec<u64>>()
.into(),
self.pilots.clone(),
self.remap.clone(),
self.rows.clone(),
)
}
/// The number of distinct names.
pub fn len(&self) -> usize {
self.rows.len()
}
/// Whether there are no names.
pub fn is_empty(&self) -> bool {
self.rows.is_empty()
}
/// The slot of `name` in `0..len()` (any value for a name not in the column).
#[inline]
fn place(&self, name: &[u8]) -> usize {
let [seed, m, buckets, slots] = self.meta;
let h = hash(name, seed);
let b = reduce(h, buckets) as usize;
let s = slot(h, u64::from(self.pilot[b]), slots);
if s < m {
s as usize
} else {
self.remap[(s - m) as usize] as usize
}
}
/// The first row holding `name`, if any. Allocates nothing.
#[inline]
pub fn id(&self, name: &str) -> Option<u32> {
self.id_bytes(name.as_bytes())
}
/// [`Names::id`] of raw bytes.
#[inline]
pub fn id_bytes(&self, name: &[u8]) -> Option<u32> {
if self.rows.is_empty() {
return None;
}
let s = self.slots[self.place(name)];
let same = match &self.values {
Some(v) if s.len != BY_ROW => {
s.len as usize == name.len() && {
let at = s.start as usize;
v.get(at..at + name.len()) == Some(name)
}
}
_ => self.strings.get(s.row as usize) == Some(name),
};
same.then_some(s.row)
}
/// The perfect hash of a name of the column: a number in `0..len()`, distinct per
/// name (for a name not in the column, some number in that range).
#[inline]
pub fn hash_of(&self, name: &str) -> usize {
self.place(name.as_bytes())
}
}