crates/kleene-plan/src/cols.rs
//! The column kernels of the rule layer. Relations are columns of `u32` or `u64` values
//! (Arrow buffers used in place); a rule's bindings are a [`Table`], one `u64` column per
//! variable. Joins probe a flat hash [`Index`] on packed multi-column keys (hash and
//! compare per key, no per-row allocation), a range condition joins through a sort, and
//! negation is an anti-join on the same index. A relation's facts are kept distinct by a
//! [`RowSet`] (open addressing over the rows' hashes), and sorted once when done. Large
//! probes split over the device's workers, in pieces whose results are joined in piece
//! order, so the result never depends on the number of threads. The pieces run on the
//! parked workers of the engine's CPU device ([`Par`]): a kernel call spawns no thread.
use std::cmp::Ordering;
use std::sync::Mutex;
use std::sync::atomic::{AtomicU32, AtomicUsize, Ordering as AtomicOrdering};
use kleene_sparse::{CpuDevice, KeyCol, prefetch_read};
use crate::facts::{Column, Facts};
use crate::rules::{Cmp, Cond, List, Plan, Term, Value, Var};
/// Atom rows from which a cross join picks each table row's rows by the SIMD range
/// selection (fewer: the call costs more than the rows).
const CROSS_SIMD_MIN: usize = 32;
/// Probes an [`Index`] handles at a time, their memory fetched ahead.
const BATCH: usize = 32;
/// Rows ahead of the one at hand whose slot an open-addressing pass asks for (and, half as
/// far ahead, the hash of the row that slot holds).
const AHEAD: usize = 32;
/// Whether the open-addressing passes ask for their slots ahead.
const FETCH_AHEAD: bool = true;
/// Slots asked for ahead by the open-addressing passes (read by the tests).
#[cfg(test)]
static AHEAD_FETCHES: AtomicUsize = AtomicUsize::new(0);
/// Ask for the slot of row `i + AHEAD` (by its hash in `h`) and for the hash of the row
/// held in the slot of row `i + AHEAD / 2`, `slots` holding a row as `row + off` with `empty`
/// for none; rows past `hi` ask for nothing.
#[inline]
fn fetch_ahead(
slots: &[AtomicU32],
mask: usize,
h: &[u64],
i: usize,
hi: usize,
empty: u32,
off: u32,
) {
if !FETCH_AHEAD {
return;
}
#[cfg(test)]
AHEAD_FETCHES.fetch_add(1, AtomicOrdering::Relaxed);
if i + AHEAD < hi {
prefetch_read(slots, h[i + AHEAD] as usize & mask);
}
if i + AHEAD / 2 < hi {
let s = slots[h[i + AHEAD / 2] as usize & mask].load(AtomicOrdering::Relaxed);
if s != empty {
prefetch_read(h, s.wrapping_sub(off) as usize);
}
}
}
/// Rows per piece of a split probe; less than two pieces run on the calling thread.
const PIECE: usize = 1 << 14;
/// Items below which a sort runs on the calling thread.
const SORT_PIECE: usize = 1 << 14;
/// Where the column kernels run their pieces: the parked workers of a CPU device (the
/// engine's own, or one for host-side work beside another backend). Nothing here starts a
/// thread once the device's workers are up.
#[derive(Clone, Debug, Default)]
pub(crate) struct Par {
device: CpuDevice,
/// Slot tables asked for: [filled on the workers, taken as zeroed memory, kept from the
/// last call] (read by the tests).
#[cfg(test)]
slot_tables: std::sync::Arc<[std::sync::atomic::AtomicUsize; 3]>,
/// The last first-of-kind table, kept for the next call of a run ([`kind_slots`]).
spare: std::sync::Arc<Mutex<Vec<AtomicU32>>>,
}
/// Lock a slot of a parallel job; a panic in a piece is raised by the executor, so a
/// poisoned slot is never read.
fn slot<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
m.lock().unwrap_or_else(|p| p.into_inner())
}
impl Par {
pub(crate) fn new(device: CpuDevice) -> Self {
Par {
device,
#[cfg(test)]
slot_tables: Default::default(),
spare: Default::default(),
}
}
/// Let the kept first-of-kind table go (at the end of a run).
pub(crate) fn drop_spare(&self) {
drop(std::mem::take(&mut *slot(&self.spare)));
}
/// Slot tables asked for so far: (filled on the workers, taken as zeroed memory, kept
/// from the last call).
#[cfg(test)]
pub(crate) fn slot_tables(&self) -> (usize, usize, usize) {
let [f, z, k] = &*self.slot_tables;
(
f.load(AtomicOrdering::Relaxed),
z.load(AtomicOrdering::Relaxed),
k.load(AtomicOrdering::Relaxed),
)
}
/// Run `job(i)` for every `i` in `0..n` on the device's threads (each thread takes the
/// next free `i`), returning when all are done.
fn each(&self, n: usize, job: &(dyn Fn(usize) + Sync)) {
let exec = self.device.executor();
if n < 2 || exec.threads() < 2 {
(0..n).for_each(job);
return;
}
let next = AtomicUsize::new(0);
exec.run(n, &|_| {
loop {
let i = next.fetch_add(1, AtomicOrdering::Relaxed);
if i >= n {
break;
}
job(i);
}
});
}
/// Run `f` over pieces of `0..n`, the results in piece order; less than two pieces, or
/// a device of one thread, run as one piece on the calling thread.
pub(crate) fn split<T: Send>(&self, n: usize, f: impl Fn(usize, usize) -> T + Sync) -> Vec<T> {
let pieces = n.div_ceil(PIECE);
if pieces < 2 || self.device.threads() < 2 {
return vec![f(0, n)];
}
let slots: Vec<Mutex<Option<T>>> = (0..pieces).map(|_| Mutex::new(None)).collect();
self.each(pieces, &|p| {
let v = f(p * PIECE, ((p + 1) * PIECE).min(n));
*slot(&slots[p]) = Some(v);
});
slots
.into_iter()
.map(|m| {
m.into_inner()
.unwrap_or_else(|p| p.into_inner())
.expect("every piece ran")
})
.collect()
}
/// `f(i)` for every `i` in `0..n`, in one vector of exactly `n` items, written in place
/// by pieces on the device's workers (nothing gathered twice, no growth).
pub(crate) fn fill<T: Copy + Default + Send>(
&self,
n: usize,
f: impl Fn(usize) -> T + Sync,
) -> Vec<T> {
let mut out = vec![T::default(); n];
if n.div_ceil(PIECE) < 2 || self.device.threads() < 2 {
for (i, x) in out.iter_mut().enumerate() {
*x = f(i);
}
return out;
}
{
let pieces: Vec<Mutex<&mut [T]>> = out.chunks_mut(PIECE).map(Mutex::new).collect();
self.each(pieces.len(), &|p| {
for (k, x) in slot(&pieces[p]).iter_mut().enumerate() {
*x = f(p * PIECE + k);
}
});
}
out
}
/// A vector of exactly `n` items written in place by pieces on the device's workers:
/// `f(lo, out)` fills the piece of places `lo..lo + out.len()`.
pub(crate) fn fill_by<T: Copy + Default + Send>(
&self,
n: usize,
f: impl Fn(usize, &mut [T]) + Sync,
) -> Vec<T> {
let mut out = vec![T::default(); n];
if n.div_ceil(PIECE) < 2 || self.device.threads() < 2 {
f(0, &mut out);
return out;
}
{
let pieces: Vec<Mutex<&mut [T]>> = out.chunks_mut(PIECE).map(Mutex::new).collect();
self.each(pieces.len(), &|p| {
let mut piece = slot(&pieces[p]);
f(p * PIECE, &mut piece);
});
}
out
}
/// The pieces of a [`Par::split`] as one vector of exactly their total length: each
/// piece copied to its place (prefix sums of the lengths) on the device's workers, so
/// the join of the pieces runs on all cores (one piece is moved, not copied).
pub(crate) fn concat<T: Copy + Default + Send + Sync>(&self, pieces: Vec<Vec<T>>) -> Vec<T> {
if pieces.len() == 1 {
return pieces.into_iter().next().expect("one piece");
}
let total = pieces.iter().map(Vec::len).sum();
let mut out = vec![T::default(); total];
if self.device.threads() < 2 {
let mut at = 0;
for p in &pieces {
out[at..at + p.len()].copy_from_slice(p);
at += p.len();
}
return out;
}
{
let mut parts: Vec<Mutex<&mut [T]>> = Vec::with_capacity(pieces.len());
let mut rest = &mut out[..];
for p in &pieces {
let (head, tail) = rest.split_at_mut(p.len());
parts.push(Mutex::new(head));
rest = tail;
}
self.each(pieces.len(), &|i| {
slot(&parts[i]).copy_from_slice(&pieces[i])
});
}
out
}
/// Sort (a comparison sort; equal items in no fixed order); items already in order are
/// left as they are. Large inputs: runs sorted on the device's threads, then merged in
/// rounds, each round's output cut into pieces at their merge-path split points.
pub(crate) fn sort_by<T: Copy + Default + Send + Sync>(
&self,
v: &mut [T],
cmp: impl Fn(&T, &T) -> Ordering + Sync,
) {
if v.is_sorted_by(|a, b| cmp(a, b) != Ordering::Greater) {
return;
}
let n = v.len();
let threads = self.device.executor().threads();
if n < 2 * SORT_PIECE || threads < 2 {
v.sort_unstable_by(cmp);
return;
}
let runs = threads.min(n / SORT_PIECE).max(2);
let per = n.div_ceil(runs);
let mut bounds: Vec<usize> = (0..n).step_by(per).chain([n]).collect();
// the merge rounds alternate between `v` and a scratch of the same length (zeroed,
// so its pages are not written before the first round): with an odd number of
// rounds the runs are sorted in the scratch (each run copied there by its worker),
// so the last round lands in `v` and nothing is copied back
let rounds = (bounds.len() - 1).next_power_of_two().trailing_zeros();
let mut scratch: Vec<T> = vec![T::default(); n];
let mut in_v = rounds.is_multiple_of(2);
if in_v {
let chunks: Vec<Mutex<&mut [T]>> = v.chunks_mut(per).map(Mutex::new).collect();
self.each(chunks.len(), &|i| slot(&chunks[i]).sort_unstable_by(&cmp));
} else {
let src: &[T] = v;
let chunks: Vec<Mutex<&mut [T]>> = scratch.chunks_mut(per).map(Mutex::new).collect();
self.each(chunks.len(), &|i| {
let mut c = slot(&chunks[i]);
let k = c.len();
c.copy_from_slice(&src[i * per..i * per + k]);
c.sort_unstable_by(&cmp);
});
}
let seg = (n / (4 * threads)).max(SORT_PIECE);
while bounds.len() > 2 {
{
let (src, dst): (&[T], &mut [T]) = if in_v {
(&*v, &mut scratch[..])
} else {
(&scratch[..], &mut *v)
};
// this round's tasks: (first run's start, second run's start, its end,
// output piece start, output piece end); a lone last run is copied
let mut tasks: Vec<(usize, usize, usize, usize, usize)> = Vec::new();
let mut r = 0;
while r + 1 < bounds.len() {
let (lo, mid) = (bounds[r], bounds[r + 1]);
let hi = if r + 2 < bounds.len() {
bounds[r + 2]
} else {
mid
};
let mut k = lo;
while k < hi {
let e = (k + seg).min(hi);
tasks.push((lo, mid, hi, k, e));
k = e;
}
r += 2;
}
let mut outs: Vec<Mutex<&mut [T]>> = Vec::with_capacity(tasks.len());
let mut rest = dst;
let mut at = 0;
for &(_, _, _, k, e) in &tasks {
let (_, tail) = std::mem::take(&mut rest).split_at_mut(k - at);
let (piece, tail) = tail.split_at_mut(e - k);
outs.push(Mutex::new(piece));
rest = tail;
at = e;
}
self.each(tasks.len(), &|t| {
let (lo, mid, hi, k, e) = tasks[t];
let (a, b) = (&src[lo..mid], &src[mid..hi]);
let i0 = co_rank(k - lo, a, b, &cmp);
let i1 = co_rank(e - lo, a, b, &cmp);
merge(
&a[i0..i1],
&b[k - lo - i0..e - lo - i1],
&mut slot(&outs[t]),
&cmp,
);
});
}
let last = bounds.len() - 1;
bounds = bounds
.iter()
.enumerate()
.filter(|&(i, _)| i % 2 == 0 || i == last)
.map(|(_, &b)| b)
.collect();
in_v = !in_v;
}
debug_assert!(in_v, "the last round lands in v");
}
}
/// How many of the first `k` merged items of the sorted `a` and `b` come from `a`.
fn co_rank<T>(k: usize, a: &[T], b: &[T], cmp: &impl Fn(&T, &T) -> Ordering) -> usize {
let (mut lo, mut hi) = (k.saturating_sub(b.len()), k.min(a.len()));
while lo < hi {
let i = lo + (hi - lo) / 2;
let j = k - i;
// more of `a` is needed while b's last taken item is above a's next one
if j > 0 && cmp(&b[j - 1], &a[i]) == Ordering::Greater {
lo = i + 1;
} else {
hi = i;
}
}
lo
}
/// Merge the sorted `a` and `b` into `out` (exactly their length).
fn merge<T: Copy>(a: &[T], b: &[T], out: &mut [T], cmp: &impl Fn(&T, &T) -> Ordering) {
let (mut i, mut j) = (0, 0);
for o in out.iter_mut() {
if j == b.len() || (i < a.len() && cmp(&b[j], &a[i]) == Ordering::Greater) {
*o = a[i];
i += 1;
} else {
*o = b[j];
j += 1;
}
}
}
/// The marker of an empty slot or the end of a chain.
const NONE: u32 = u32::MAX;
/// One column borrowed for a kernel.
#[derive(Clone, Copy, Debug)]
pub(crate) enum Col<'a> {
U32(&'a [u32]),
U64(&'a [u64]),
}
impl<'a> Col<'a> {
/// Values `lo..hi` as a key column of the SIMD kernels.
fn key(self, lo: usize, hi: usize) -> KeyCol<'a> {
match self {
Col::U32(v) => KeyCol::U32(&v[lo..hi]),
Col::U64(v) => KeyCol::U64(&v[lo..hi]),
}
}
#[inline]
pub(crate) fn get(self, k: usize) -> Value {
match self {
Col::U32(v) => v[k] as Value,
Col::U64(v) => v[k],
}
}
}
/// Rows borrowed for a kernel: equally long columns.
#[derive(Clone, Debug)]
pub(crate) struct Rows<'a> {
cols: Vec<Col<'a>>,
len: usize,
}
impl<'a> Rows<'a> {
/// The rows of `f`.
pub(crate) fn of(f: &'a Facts) -> Self {
let cols = (0..f.arity())
.map(|i| match f.column(i) {
Column::U32(v) => Col::U32(v),
Column::U64(v) => Col::U64(v),
})
.collect();
Rows { cols, len: f.len() }
}
/// Rows `lo..hi` of `s`.
pub(crate) fn range(s: &'a RowSet, lo: usize, hi: usize) -> Self {
Rows {
cols: s.cols.iter().map(|c| Col::U64(&c[lo..hi])).collect(),
len: hi - lo,
}
}
#[inline]
pub(crate) fn get(&self, c: usize, k: usize) -> Value {
self.cols[c].get(k)
}
/// Ask for row `k` of the columns `cols` ahead of reading it.
#[inline]
pub(crate) fn ahead(&self, cols: &[usize], k: usize) {
for &c in cols {
match self.cols[c] {
Col::U32(v) => prefetch_read(v, k),
Col::U64(v) => prefetch_read(v, k),
}
}
}
pub(crate) fn len(&self) -> usize {
self.len
}
}
/// The bindings of a rule's variables: one column per variable, `len` rows (a table with
/// no variables still counts its rows).
#[derive(Clone, Debug, Default)]
pub(crate) struct Table {
pub vars: Vec<Var>,
pub cols: Vec<Vec<Value>>,
pub len: usize,
/// No two rows bind the head's variables alike (a pass checked it).
pub distinct: bool,
/// The rows in an order of their own: row `i` is stored at `perm[i]` (the columns not
/// gathered into that order until the head reads them).
pub perm: Option<Vec<u32>>,
}
impl Table {
/// Where row `i` is stored.
#[inline]
pub(crate) fn row(&self, i: usize) -> usize {
match &self.perm {
Some(p) => p[i] as usize,
None => i,
}
}
/// The columns gathered into the rows' order (nothing to do without one).
pub(crate) fn resolve(&mut self, par: &Par) {
if let Some(p) = self.perm.take() {
for c in &mut self.cols {
*c = gather(par, c, &p);
}
}
}
/// One row of no variables: the start of a body that has only externals.
pub(crate) fn unit() -> Self {
Table {
vars: Vec::new(),
cols: Vec::new(),
len: 1,
distinct: false,
perm: None,
}
}
/// The column of `v`.
pub(crate) fn col_of(&self, v: Var) -> Option<usize> {
self.vars.iter().position(|&w| w == v)
}
/// Keep the rows at the places `at` (rising, from [`kept_places`]), in order: every
/// column gathered at them on the device's workers; nothing moves when every row stays.
pub(crate) fn keep_at(&mut self, par: &Par, at: Vec<u32>) {
if at.len() == self.len {
return;
}
self.resolve(par);
let all: Vec<usize> = (0..self.cols.len()).collect();
let distinct = self.distinct;
*self = self.at_rows(par, &at, &all);
self.distinct = distinct;
}
/// The table at rows `rows` (rising), with the columns `cols` only, each gathered into
/// a column of exactly that length on the device's workers.
pub(crate) fn at_rows(&self, par: &Par, rows: &[u32], cols: &[usize]) -> Table {
Table {
vars: cols.iter().map(|&c| self.vars[c]).collect(),
cols: cols
.iter()
.map(|&c| {
let col = &self.cols[c];
par.fill(rows.len(), |i| col[self.row(rows[i] as usize)])
})
.collect(),
len: rows.len(),
distinct: false,
perm: None,
}
}
/// The columns put in the order of `vars` (each one of the table's variables).
pub(crate) fn reorder(&mut self, vars: &[Var]) {
let mut cols: Vec<Option<Vec<Value>>> = std::mem::take(&mut self.cols)
.into_iter()
.map(Some)
.collect();
self.cols = vars
.iter()
.map(|&v| {
let at = self.col_of(v).expect("a bound variable");
cols[at].take().expect("one column per variable")
})
.collect();
self.vars = vars.to_vec();
}
}
#[inline]
fn mix(h: u64, x: u64) -> u64 {
(h ^ x).wrapping_mul(0x9E37_79B9_7F4A_7C15).rotate_left(27)
}
#[inline]
fn finish(h: u64) -> u64 {
let h = (h ^ (h >> 31)).wrapping_mul(0xD6E8_FEB8_6659_FD93);
h ^ (h >> 32)
}
/// The hash of a key read value by value.
#[inline]
pub(crate) fn hash_of(n: usize, at: impl Fn(usize) -> Value) -> u64 {
let mut h = 0x243F_6A88_85A3_08D3u64;
for i in 0..n {
h = mix(h, at(i));
}
finish(h)
}
/// Which rows of a relation an atom reads.
#[derive(Clone, Debug)]
pub(crate) enum Sel {
/// Every row.
All(usize),
/// These rows, rising.
Rows(Vec<u32>),
}
impl Sel {
pub(crate) fn len(&self) -> usize {
match self {
Sel::All(n) => *n,
Sel::Rows(r) => r.len(),
}
}
#[inline]
pub(crate) fn at(&self, i: usize) -> u32 {
match self {
Sel::All(_) => i as u32,
Sel::Rows(r) => r[i],
}
}
/// The selected rows at the places `k` (rising): `k` itself when every row is
/// selected, else gathered on the device's workers.
pub(crate) fn pick(&self, par: &Par, k: Vec<u32>) -> Sel {
match self {
Sel::All(_) => Sel::Rows(k),
Sel::Rows(r) => Sel::Rows(par.fill(k.len(), |i| r[k[i] as usize])),
}
}
}
/// Where a condition's term comes from in a join step: a column of the table, a column of
/// the atom's rows, or a constant.
#[derive(Clone, Copy, Debug)]
pub(crate) enum Src {
T(usize),
R(usize),
K(Value),
}
/// A condition with its terms placed.
#[derive(Clone, Copy, Debug)]
pub(crate) enum Check<'a> {
Cmp(Src, Cmp, Src),
Within(Src, Src, Src),
/// Whether the value is the null code (true) or not (false).
Null(Src, bool),
/// Whether the value (a string id) is in a set of ids, a bit per id.
In(Src, &'a [u64]),
/// Whether the value is one of the sorted codes (true: is not).
OneOf(Src, &'a [Value], bool),
}
impl<'a> Check<'a> {
/// `c` placed by `place` (a variable to its source), or `None` when a variable is not
/// at hand.
/// A text test's pattern is the number of its id set in the text sets of `p` (a
/// resolved plan); a list test reads the list's codes in `p`.
pub(crate) fn place(
c: &Cond,
place: impl Fn(Var) -> Option<Src>,
p: &'a Plan,
) -> Option<Check<'a>> {
let sets = &p.text_sets;
let src = |t: Term| match t {
Term::Const(k) => Some(Src::K(k)),
Term::Var(v) => place(v),
};
Some(match *c {
Cond::Cmp { left, op, right } => Check::Cmp(src(left)?, op, src(right)?),
Cond::Within { x, lo, hi } => Check::Within(src(x)?, src(lo)?, src(hi)?),
Cond::IsNull { x, null } => Check::Null(src(x)?, null),
Cond::Text { x, pat, .. } => {
let Term::Const(k) = pat else {
unreachable!("a text test's pattern is a constant")
};
Check::In(
src(x)?,
sets.get(k as usize)
.expect("a resolved text test names its set"),
)
}
Cond::OneOf { x, list, not } => Check::OneOf(src(x)?, &p.lists[list.index()].run, not),
})
}
#[inline]
fn value(s: Src, t: &Table, l: usize, r: &Rows, k: usize) -> Value {
match s {
Src::T(c) => t.cols[c][l],
Src::R(c) => r.get(c, k),
Src::K(x) => x,
}
}
/// The atom column whose values alone decide the condition once the table row is
/// known (the other terms are table columns or constants), if there is one.
fn range_col(&self) -> Option<usize> {
let fixed = |s: Src| !matches!(s, Src::R(_));
match *self {
Check::Cmp(Src::R(c), _, b) if fixed(b) => Some(c),
Check::Cmp(a, _, Src::R(c)) if fixed(a) => Some(c),
Check::Within(Src::R(c), lo, hi) if fixed(lo) && fixed(hi) => Some(c),
_ => None,
}
}
/// For a condition with a [`Check::range_col`]: the values of that column it keeps on
/// table row `l`, as `(lo, hi, inside)`: kept where `(lo <= x && x <= hi) == inside`
/// (an empty range is `lo > hi`).
fn range_at(&self, t: &Table, l: usize) -> (Value, Value, bool) {
let v = |s: Src| match s {
Src::T(c) => t.cols[c][l],
Src::K(x) => x,
Src::R(_) => unreachable!("one side is the atom's column"),
};
// `x op k` as a range of x
let range = |op: Cmp, k: Value| match op {
Cmp::Eq => (k, k, true),
Cmp::Ne => (k, k, false),
Cmp::Lt if k == 0 => (1, 0, true),
Cmp::Lt => (0, k - 1, true),
Cmp::Le => (0, k, true),
Cmp::Gt if k == Value::MAX => (1, 0, true),
Cmp::Gt => (k + 1, Value::MAX, true),
Cmp::Ge => (k, Value::MAX, true),
};
match *self {
Check::Cmp(Src::R(_), op, b) => range(op, v(b)),
Check::Cmp(a, op, Src::R(_)) => {
let flipped = match op {
Cmp::Lt => Cmp::Gt,
Cmp::Le => Cmp::Ge,
Cmp::Gt => Cmp::Lt,
Cmp::Ge => Cmp::Le,
o => o,
};
range(flipped, v(a))
}
Check::Within(_, lo, hi) => match v(hi) {
0 => (1, 0, true),
h => (v(lo), h - 1, true),
},
_ => unreachable!("only a condition with a range column"),
}
}
/// Whether the condition holds on table row `l` with atom row `k`.
#[inline]
pub(crate) fn holds(&self, t: &Table, l: usize, r: &Rows, k: usize) -> bool {
match *self {
Check::Cmp(a, op, b) => {
op.holds(Self::value(a, t, l, r, k), Self::value(b, t, l, r, k))
}
Check::Within(x, lo, hi) => {
let x = Self::value(x, t, l, r, k);
Self::value(lo, t, l, r, k) <= x && x < Self::value(hi, t, l, r, k)
}
Check::Null(x, null) => (Self::value(x, t, l, r, k) == crate::typed::NULL) == null,
Check::In(x, bits) => {
let v = Self::value(x, t, l, r, k);
bits.get((v / 64) as usize)
.is_some_and(|w| w >> (v % 64) & 1 == 1)
}
Check::OneOf(x, run, not) => List::has(run, Self::value(x, t, l, r, k)) != not,
}
}
}
/// The rows of `r` an atom with `terms` reads: equal to its constants, equal where a
/// variable repeats, and passing `checks` (over the atom's own columns).
pub(crate) fn select(par: &Par, terms: &[Term], r: &Rows, checks: &[Check]) -> Sel {
let mut consts: Vec<(usize, Value)> = Vec::new();
let mut repeats: Vec<(usize, usize)> = Vec::new();
for (j, t) in terms.iter().enumerate() {
match *t {
Term::Const(k) => consts.push((j, k)),
Term::Var(v) => {
if let Some(f) = terms[..j].iter().position(|&u| u == Term::Var(v)) {
repeats.push((f, j));
}
}
}
}
if consts.is_empty() && repeats.is_empty() && checks.is_empty() {
return Sel::All(r.len());
}
let none = Table::default();
let keep = |k: usize| {
consts.iter().all(|&(j, x)| r.get(j, k) == x)
&& repeats.iter().all(|&(a, b)| r.get(a, k) == r.get(b, k))
&& checks.iter().all(|c| c.holds(&none, 0, r, k))
};
// A constant or a condition against a constant picks the candidate rows by the
// SIMD range selection (then every test is checked on them).
let first = consts.first().map(|&(j, x)| (j, (x, x, true))).or_else(|| {
checks
.iter()
.find_map(|c| c.range_col().map(|j| (j, c.range_at(&none, 0))))
});
if let Some((j, (lo, hi, inside))) = first {
let simd = par.device.simd();
let col = r.cols[j];
return Sel::Rows(par.concat(par.split(r.len(), |a, b| {
let mut out = vec![0u32; b - a];
let n = simd.select_range(col.key(a, b), lo, hi, inside, a as u32, &mut out);
out.truncate(n);
out.retain(|&k| keep(k as usize));
out
})));
}
Sel::Rows(kept_places(par, r.len(), keep))
}
/// The places `0..n` where `keep` holds, rising: each piece's found on the device's
/// workers, then copied to its place.
pub(crate) fn kept_places(par: &Par, n: usize, keep: impl Fn(usize) -> bool + Sync) -> Vec<u32> {
par.concat(par.split(n, |lo, hi| {
(lo..hi)
.filter(|&k| keep(k))
.map(|k| k as u32)
.collect::<Vec<u32>>()
}))
}
/// The chains of an index whose rows have hashes `hash` in `mask + 1` slots: each slot's
/// first row and each row's next in its slot (rising), linked on the device's workers from
/// the rows sorted by (slot, place) (few rows: on the calling thread). A slot's last row is
/// found only when the index is first extended ([`Index::extend`]).
fn chains(par: &Par, hash: &[u64], mask: usize) -> (Vec<u32>, Vec<u32>) {
let n = hash.len();
if n < 4 * PIECE || par.device.threads() < 2 {
// few rows: linked last to first, so a chain lists its rows rising
let (mut head, mut next) = (vec![NONE; mask + 1], vec![NONE; n]);
for i in (0..n).rev() {
let b = hash[i] as usize & mask;
next[i] = head[b];
head[b] = i as u32;
}
return (head, next);
}
let mut order: Vec<u64> =
par.fill(n, |i| (((hash[i] as usize & mask) as u64) << 32) | i as u64);
par.sort_by(&mut order, |a, b| a.cmp(b));
// each holds a row + 1 (0: none), so they start at 0, filled on the workers
let (head, next) = (filled_slots(par, mask + 1), filled_slots(par, n));
let slot = |k: usize| order[k] >> 32;
par.split(n, |lo, hi| {
for k in lo..hi {
let (b, i) = (slot(k) as usize, order[k] as u32 + 1);
if k == 0 || slot(k - 1) != slot(k) {
head[b].store(i, AtomicOrdering::Relaxed);
}
if k + 1 < n && slot(k + 1) == slot(k) {
next[i as usize - 1].store(order[k + 1] as u32 + 1, AtomicOrdering::Relaxed);
}
}
});
// a row + 1 back to the row, 0 to NONE (u32::MAX)
let plain = |v: Vec<AtomicU32>| -> Vec<u32> {
v.into_iter()
.map(|x| x.into_inner().wrapping_sub(1))
.collect()
};
(plain(head), plain(next))
}
/// `n` atomic slots, all 0, filled on the device's workers, so each page is first touched
/// in order by a worker and not by a probe: for a table every slot of which is written
/// (an index's chains; measured: fail 0.067 -> 0.060 s against zeroed memory).
fn filled_slots(par: &Par, n: usize) -> Vec<AtomicU32> {
#[cfg(test)]
par.slot_tables[0].fetch_add(1, AtomicOrdering::Relaxed);
par.fill(n, |_| 0u32)
.into_iter()
.map(AtomicU32::new)
.collect()
}
/// A first-of-kind table of at least `n` atomic slots, the first `n` all 0: the table of
/// the last call kept in `par` and its first `n` slots cleared on the workers when large
/// enough (walk asks for one every round: 1.045 -> 0.930 s, loki, 8 threads), else fresh
/// zeroed memory (filling a fresh one on the workers costs loose 0.149 -> 0.166 s).
fn kind_slots(par: &Par, n: usize) -> Vec<AtomicU32> {
let table = std::mem::take(&mut *slot(&par.spare));
if table.len() < n {
return zeroed_slots(par, n);
}
#[cfg(test)]
par.slot_tables[2].fetch_add(1, AtomicOrdering::Relaxed);
par.split(n, |lo, hi| {
table[lo..hi]
.iter()
.for_each(|s| s.store(0, AtomicOrdering::Relaxed))
});
table
}
/// `n` atomic slots, all 0, from zeroed memory: the allocator hands fresh zero pages (no
/// pass writes them), and each page is first touched by the worker that probes it.
fn zeroed_slots(par: &Par, n: usize) -> Vec<AtomicU32> {
#[cfg(test)]
par.slot_tables[1].fetch_add(1, AtomicOrdering::Relaxed);
#[cfg(not(test))]
let _ = par;
vec![0u32; n].into_iter().map(AtomicU32::new).collect()
}
/// A flat hash index over the selected rows of a relation, by `key` columns: a bucket
/// head per power-of-two slot and a chain through the rows.
#[derive(Debug)]
pub(crate) struct Index {
key: Vec<usize>,
/// The rows of the relation it was built from or extended to (selected or not).
upto: usize,
rows: Vec<u32>,
hash: Vec<u64>,
head: Vec<u32>,
/// The last row of each slot's chain, so a row is added at its chain's end directly:
/// empty until the index is first extended (an index never extended needs none).
tail: Vec<u32>,
next: Vec<u32>,
mask: usize,
/// Chain links walked to find a chain's end while extending (read by the tests).
#[cfg(test)]
walked: usize,
/// Batches of probes whose memory was fetched ahead (read by the tests).
#[cfg(test)]
batches: AtomicUsize,
}
impl Index {
/// The index of the selected rows of `r` by `key` (the selection's rows moved in),
/// every pass on the device's workers: the hashes, the rows ordered by slot (a sort of
/// (slot, place) keys, so each chain lists its rows rising at any thread count), and
/// the chains linked from that order.
pub(crate) fn build(par: &Par, r: &Rows, sel: Sel, key: &[usize]) -> Self {
let n = sel.len();
let slots = (2 * n).next_power_of_two().max(16);
let mask = slots - 1;
let rows: Vec<u32> = match sel {
Sel::Rows(v) => v,
Sel::All(n) => par.fill(n, |i| i as u32),
};
let hash: Vec<u64> = par.fill(n, |i| {
let k = rows[i] as usize;
hash_of(key.len(), |j| r.get(key[j], k))
});
let (head, next) = chains(par, &hash, mask);
Index {
key: key.to_vec(),
upto: r.len(),
rows,
hash,
head,
tail: Vec::new(),
next,
mask,
#[cfg(test)]
walked: 0,
#[cfg(test)]
batches: AtomicUsize::new(0),
}
}
/// The index of every row of `r`, of which it holds every row up to the ones it was
/// last built from or extended to (a relation that only grew at its end): the new rows
/// added at their chains' ends (each chain still rising; each slot's last row found in
/// one pass the first time), or all built anew once the chains average one row a slot.
pub(crate) fn extend(&mut self, par: &Par, r: &Rows) {
let (from, n) = (self.upto, r.len());
if n <= from {
return;
}
if self.rows.len() + (n - from) > self.head.len() {
let key = std::mem::take(&mut self.key);
*self = Index::build(par, r, Sel::All(n), &key);
return;
}
// the new rows' hashes on the workers, then each row linked after its chain's tail
let key = &self.key;
let hash = par.fill(n - from, |i| {
hash_of(key.len(), |j| r.get(key[j], from + i))
});
if self.tail.is_empty() {
// the first extend: each slot's last row, from the rows in order (chains rise)
let mut tail = vec![NONE; self.head.len()];
for (i, &h) in self.hash.iter().enumerate() {
tail[h as usize & self.mask] = i as u32;
}
self.tail = tail;
}
let at = self.rows.len();
self.rows.extend((from..n).map(|k| k as u32));
self.hash.extend_from_slice(&hash);
self.next.resize(at + hash.len(), NONE);
for (q, &h) in hash.iter().enumerate() {
let i = (at + q) as u32;
let b = h as usize & self.mask;
match self.tail[b] {
NONE => self.head[b] = i,
t => self.next[t as usize] = i,
}
self.tail[b] = i;
}
self.upto = n;
}
/// Every indexed row whose key equals the probe's (hash `h`; `eq(row)` compares the
/// key), rising: one probe alone, the reference of [`Index::probe_each`].
#[cfg(test)]
pub(crate) fn probe(&self, h: u64, eq: impl Fn(usize) -> bool, mut f: impl FnMut(u32)) {
let mut i = self.head[h as usize & self.mask];
while i != NONE {
let at = i as usize;
if self.hash[at] == h && eq(self.rows[at] as usize) {
f(self.rows[at]);
}
i = self.next[at];
}
}
/// The probes `lo..hi` of one piece (probe `l` hashes to `hash(l)`; `eq(l, row)`
/// compares its key with an indexed row's): every indexed row whose key equals probe
/// `l`'s handed to `f(l, row)`, probe after probe and each chain rising, the order of
/// one [`Index::probe`] after another. The probes go [`BATCH`] at a time, their memory
/// asked for ahead: the batch's slots, then each chain's first entry, then by
/// `ahead(row)` the key columns of its row; so the misses of a batch overlap.
#[inline]
pub(crate) fn probe_each(
&self,
lo: usize,
hi: usize,
hash: impl Fn(usize) -> u64,
eq: impl Fn(usize, usize) -> bool,
ahead: impl Fn(usize),
mut f: impl FnMut(usize, u32),
) {
let (mut hs, mut first) = ([0u64; BATCH], [NONE; BATCH]);
let mut b = lo;
while b < hi {
let m = (hi - b).min(BATCH);
self.fetch(b, m, &hash, &ahead, &mut hs, &mut first);
for q in 0..m {
let (l, h) = (b + q, hs[q]);
let mut i = first[q];
while i != NONE {
let at = i as usize;
if self.hash[at] == h && eq(l, self.rows[at] as usize) {
f(l, self.rows[at]);
}
i = self.next[at];
}
}
b += m;
}
}
/// [`Index::probe_each`] asking only whether a row matches: `f(l, found)` for every
/// probe `l` of `lo..hi`, in order.
#[inline]
pub(crate) fn any_each(
&self,
lo: usize,
hi: usize,
hash: impl Fn(usize) -> u64,
eq: impl Fn(usize, usize) -> bool,
ahead: impl Fn(usize),
mut f: impl FnMut(usize, bool),
) {
let (mut hs, mut first) = ([0u64; BATCH], [NONE; BATCH]);
let mut b = lo;
while b < hi {
let m = (hi - b).min(BATCH);
self.fetch(b, m, &hash, &ahead, &mut hs, &mut first);
for q in 0..m {
let (l, h) = (b + q, hs[q]);
let mut i = first[q];
let mut found = false;
while i != NONE {
let at = i as usize;
if self.hash[at] == h && eq(l, self.rows[at] as usize) {
found = true;
break;
}
i = self.next[at];
}
f(l, found);
}
b += m;
}
}
/// The hashes and chains' first entries of the `m` probes from `b`, their memory asked
/// for stage by stage: every slot, then every first entry (hash, next, row), then
/// every first row's key columns (`ahead`).
#[inline]
fn fetch(
&self,
b: usize,
m: usize,
hash: &impl Fn(usize) -> u64,
ahead: &impl Fn(usize),
hs: &mut [u64; BATCH],
first: &mut [u32; BATCH],
) {
#[cfg(test)]
self.batches.fetch_add(1, AtomicOrdering::Relaxed);
for (q, slot) in hs.iter_mut().enumerate().take(m) {
let h = hash(b + q);
*slot = h;
prefetch_read(&self.head, h as usize & self.mask);
}
for q in 0..m {
let i = self.head[hs[q] as usize & self.mask];
first[q] = i;
if i != NONE {
let at = i as usize;
prefetch_read(&self.hash, at);
prefetch_read(&self.next, at);
prefetch_read(&self.rows, at);
}
}
for &i in &first[..m] {
if i != NONE {
ahead(self.rows[i as usize] as usize);
}
}
}
/// Whether an indexed row's key equals the probe's: one probe alone, the reference of
/// [`Index::any_each`].
#[cfg(test)]
pub(crate) fn any(&self, h: u64, eq: impl Fn(usize) -> bool) -> bool {
let mut i = self.head[h as usize & self.mask];
while i != NONE {
let at = i as usize;
if self.hash[at] == h && eq(self.rows[at] as usize) {
return true;
}
i = self.next[at];
}
false
}
pub(crate) fn key(&self) -> &[usize] {
&self.key
}
/// The rows indexed.
pub(crate) fn len(&self) -> usize {
self.rows.len()
}
}
/// Rows below which [`first_of_kind`] runs without estimating first; also the rows its
/// guard samples.
const GUARD_MIN: usize = 1 << 16;
/// Whether rows `0..n` (at least [`GUARD_MIN`]), keyed by `hash(i)`, look to hold repeats
/// worth a pass: one row drawn from each of [`GUARD_MIN`] equal stretches (at a place fixed
/// by the stretch number), the pairs of equal hashes among them counted. A kind of `m` rows
/// gives about `m (m - 1) / 2` times the square of the share drawn, so `2 n pairs / s²`
/// estimates the rows past the first of their kind per row; the pass runs from one in ten.
fn repeats_worth_a_pass(par: &Par, n: usize, hash: &(impl Fn(usize) -> u64 + Sync)) -> bool {
let s = GUARD_MIN;
let mut h: Vec<u64> = par.fill(s, |i| {
let (lo, hi) = (i * n / s, (i + 1) * n / s);
let jitter = (i as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 40;
hash(lo + (jitter as usize) % (hi - lo).max(1))
});
par.sort_by(&mut h, |a, b| a.cmp(b));
let mut pairs = 0u64;
let mut run = 1u64;
for k in 1..=h.len() {
if k < h.len() && h[k] == h[k - 1] {
run += 1;
} else {
pairs += run * (run - 1) / 2;
run = 1;
}
}
let excess = 2.0 * n as f64 * pairs as f64 / (s as f64 * s as f64);
excess >= 0.1
}
/// Of the rows `0..n`, keyed by `hash(i)` and equal by `eq(i, j)`, the first of each kind
/// (the least row), rising. `None` when every row is the first of its kind, and, with
/// `guard`, when a sample of a large table finds fewer than about one row in ten a repeat
/// (the pass would not pay for itself). The rows go into one open-addressing table of atomic slots
/// on the device's workers, each slot of a kind keeping the least row of it (the least of
/// any order of arrival), then each row is kept when its kind's slot holds it: the answer
/// does not depend on the number of threads. Nothing is allocated per row.
pub(crate) fn first_of_kind(
par: &Par,
n: usize,
guard: bool,
hash: impl Fn(usize) -> u64 + Sync,
eq: impl Fn(usize, usize) -> bool + Sync,
) -> Option<Vec<u32>> {
first_of_kind_by(par, n, guard, hash, eq, |i, j| i < j)
}
/// [`first_of_kind`] with the row of each kind kept the least by `less` (a total order of
/// the rows, so the answer still does not depend on the number of threads).
pub(crate) fn first_of_kind_by(
par: &Par,
n: usize,
guard: bool,
hash: impl Fn(usize) -> u64 + Sync,
eq: impl Fn(usize, usize) -> bool + Sync,
less: impl Fn(u32, u32) -> bool + Sync,
) -> Option<Vec<u32>> {
match kinds_by(par, n, guard, hash, eq, less) {
Kinds::Kept(k) => Some(k),
Kinds::Distinct | Kinds::Skipped => None,
}
}
/// What a pass for the first row of each kind found.
pub(crate) enum Kinds {
/// Every row is the first of its kind (checked).
Distinct,
/// The guard skipped the pass: the rows may hold repeats.
Skipped,
/// The first row of each kind, rising (some rows were repeats).
Kept(Vec<u32>),
}
/// [`first_of_kind_by`], telling a table found distinct from one the guard skipped.
pub(crate) fn kinds_by(
par: &Par,
n: usize,
guard: bool,
hash: impl Fn(usize) -> u64 + Sync,
eq: impl Fn(usize, usize) -> bool + Sync,
less: impl Fn(u32, u32) -> bool + Sync,
) -> Kinds {
if n < 2 {
return Kinds::Distinct;
}
if guard && n >= GUARD_MIN && !repeats_worth_a_pass(par, n, &hash) {
return Kinds::Skipped;
}
let h: Vec<u64> = hash_rows(par, n, &hash);
kinds_hashed(par, &h, eq, less)
}
/// The hash of every row `0..n`, in one exact vector written on the device's workers.
pub(crate) fn hash_rows(par: &Par, n: usize, hash: &(impl Fn(usize) -> u64 + Sync)) -> Vec<u64> {
par.fill(n, hash)
}
/// [`kinds_by`] over rows whose hashes `h` are in hand (no guard).
pub(crate) fn kinds_hashed(
par: &Par,
h: &[u64],
eq: impl Fn(usize, usize) -> bool + Sync,
less: impl Fn(u32, u32) -> bool + Sync,
) -> Kinds {
let n = h.len();
if n < 2 {
return Kinds::Distinct;
}
let size = (2 * n).next_power_of_two();
let mask = size - 1;
// a slot holds its row + 1 (0: empty), so it starts cleared
let table = kind_slots(par, size);
let slots = &table[..size];
let same = |s: usize, i: usize| h[s] == h[i] && eq(s, i);
par.split(n, |lo, hi| {
for (i, &hv) in h.iter().enumerate().take(hi).skip(lo) {
fetch_ahead(slots, mask, h, i, hi, 0, 1);
let mut b = hv as usize & mask;
let me = i as u32 + 1;
loop {
let s = slots[b].load(AtomicOrdering::Relaxed);
if s == 0 {
match slots[b].compare_exchange(
0,
me,
AtomicOrdering::Relaxed,
AtomicOrdering::Relaxed,
) {
Ok(_) => break,
Err(_) => continue,
}
}
if same(s as usize - 1, i) {
// a slot holds one kind for good: keep the least row of it
let mut cur = s;
while less(i as u32, cur - 1) {
match slots[b].compare_exchange(
cur,
me,
AtomicOrdering::Relaxed,
AtomicOrdering::Relaxed,
) {
Ok(_) => break,
Err(x) => cur = x,
}
}
break;
}
b = (b + 1) & mask;
}
}
});
let kept = par.concat(par.split(n, |lo, hi| {
let mut out: Vec<u32> = Vec::new();
for (i, &hv) in h.iter().enumerate().take(hi).skip(lo) {
fetch_ahead(slots, mask, h, i, hi, 0, 1);
let mut b = hv as usize & mask;
loop {
let s = slots[b].load(AtomicOrdering::Relaxed) as usize - 1;
if same(s, i) {
if s == i {
out.push(i as u32);
}
break;
}
b = (b + 1) & mask;
}
}
out
}));
*slot(&par.spare) = table;
if kept.len() < n {
Kinds::Kept(kept)
} else {
Kinds::Distinct
}
}
/// The pairs (table row, atom row) of a join step.
pub(crate) struct Pairs {
pub left: Vec<u32>,
pub right: Vec<u32>,
}
impl Pairs {
/// The pairs at places `at` (rising).
pub(crate) fn at(&self, par: &Par, at: &[u32]) -> Pairs {
Pairs {
left: par.fill(at.len(), |i| self.left[at[i] as usize]),
right: par.fill(at.len(), |i| self.right[at[i] as usize]),
}
}
}
fn pairs_of(par: &Par, pieces: Vec<(Vec<u32>, Vec<u32>)>) -> Pairs {
let (l, r): (Vec<_>, Vec<_>) = pieces.into_iter().unzip();
Pairs {
left: par.concat(l),
right: par.concat(r),
}
}
/// The table's rows joined with the atom's rows of equal key (`tk` columns of the table
/// against the index's columns of `r`), passing `checks`.
pub(crate) fn hash_join(
par: &Par,
t: &Table,
tk: &[usize],
r: &Rows,
ix: &Index,
checks: &[Check],
) -> Pairs {
let rk = ix.key();
pairs_of(
par,
par.split(t.len, |lo, hi| {
let (mut left, mut right) = (Vec::new(), Vec::new());
ix.probe_each(
lo,
hi,
|l| hash_of(tk.len(), |j| t.cols[tk[j]][l]),
|l, k| (0..tk.len()).all(|j| t.cols[tk[j]][l] == r.get(rk[j], k)),
|k| r.ahead(rk, k),
|l, k| {
if checks.iter().all(|c| c.holds(t, l, r, k as usize)) {
left.push(l as u32);
right.push(k);
}
},
);
(left, right)
}),
)
}
/// The table's rows joined with the atom's selected rows where `x` lies in `[lo, hi)`,
/// passing `checks`: the side that holds `x` sorted by it, the other side's ranges
/// looked up by binary search.
#[allow(clippy::too_many_arguments)]
pub(crate) fn range_join(
par: &Par,
t: &Table,
r: &Rows,
sel: &Sel,
x: Src,
lo: Src,
hi: Src,
checks: &[Check],
) -> Pairs {
let none = Table::default();
match x {
Src::T(xc) => {
// x in the table: its rows by x; each atom row looks up its range.
let xs = &t.cols[xc];
let mut order: Vec<u32> = (0..t.len as u32).collect();
par.sort_by(&mut order, |&a, &b| xs[a as usize].cmp(&xs[b as usize]));
pairs_of(
par,
par.split(sel.len(), |a, b| {
let (mut left, mut right) = (Vec::new(), Vec::new());
for i in a..b {
let k = sel.at(i) as usize;
let (l0, h0) = (
Check::value(lo, &none, 0, r, k),
Check::value(hi, &none, 0, r, k),
);
let s = order.partition_point(|&l| xs[l as usize] < l0);
for &l in &order[s..] {
if xs[l as usize] >= h0 {
break;
}
if checks.iter().all(|c| c.holds(t, l as usize, r, k)) {
left.push(l);
right.push(k as u32);
}
}
}
(left, right)
}),
)
}
_ => {
// x in the atom: its selected rows by x; each table row looks up its range.
let Src::R(xc) = x else {
unreachable!("a range join has x on one side")
};
let mut order: Vec<u32> = (0..sel.len()).map(|i| sel.at(i)).collect();
par.sort_by(&mut order, |&a, &b| {
r.get(xc, a as usize).cmp(&r.get(xc, b as usize))
});
pairs_of(
par,
par.split(t.len, |a, b| {
let (mut left, mut right) = (Vec::new(), Vec::new());
for l in a..b {
let (l0, h0) = (Check::value(lo, t, l, r, 0), Check::value(hi, t, l, r, 0));
let s = order.partition_point(|&k| r.get(xc, k as usize) < l0);
for &k in &order[s..] {
if r.get(xc, k as usize) >= h0 {
break;
}
if checks.iter().all(|c| c.holds(t, l, r, k as usize)) {
left.push(l as u32);
right.push(k);
}
}
}
(left, right)
}),
)
}
}
}
/// One end of a [`Band`]: where its value comes from, and whether the tested value must
/// lie strictly past it.
#[derive(Clone, Copy, Debug)]
pub(crate) struct End {
pub(crate) at: Src,
pub(crate) strict: bool,
}
/// A value of one side of a join step between two ends from the other side (or
/// constants, not both): `lo <= x` (`lo < x` when strict) and `x <= hi` (`x < hi`).
/// Compared as codes, as [`Check::holds`] compares them.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Band {
pub(crate) x: Src,
pub(crate) lo: End,
pub(crate) hi: End,
}
impl Band {
/// The first band `checks` give, and the places of the checks it stands for (one range,
/// or a lower and an upper comparison of one value): a range first, then the
/// comparisons in the order written. `None` when none: no value with both ends on the
/// other side of the join.
pub(crate) fn find(checks: &[Check]) -> Option<(Band, Vec<usize>)> {
// the side of a source: Some(true) the table, Some(false) the atom, None a constant
let side = |s: Src| match s {
Src::T(_) => Some(true),
Src::R(_) => Some(false),
Src::K(_) => None,
};
let same = |a: Src, b: Src| match (a, b) {
(Src::T(x), Src::T(y)) | (Src::R(x), Src::R(y)) => x == y,
_ => false,
};
// an end fits a value of side `sx`: the other side or a constant
let fits = |sx: bool, e: Src| side(e).is_none_or(|s| s != sx);
for (i, c) in checks.iter().enumerate() {
if let Check::Within(x, lo, hi) = *c
&& let Some(sx) = side(x)
&& fits(sx, lo)
&& fits(sx, hi)
&& (side(lo).is_some() || side(hi).is_some())
{
let lo = End {
at: lo,
strict: false,
};
let hi = End {
at: hi,
strict: true,
};
return Some((Band { x, lo, hi }, vec![i]));
}
}
// each comparison as an end of either of its values: (x, end, upper)
let mut ends: Vec<(Src, End, bool, usize)> = Vec::new();
for (i, c) in checks.iter().enumerate() {
let Check::Cmp(a, op, b) = *c else { continue };
// `x op e` as an end of x
let mut put = |x: Src, op: Cmp, e: Src| {
let Some(sx) = side(x) else { return };
if !fits(sx, e) {
return;
}
let (upper, strict) = match op {
Cmp::Lt => (true, true),
Cmp::Le => (true, false),
Cmp::Gt => (false, true),
Cmp::Ge => (false, false),
Cmp::Eq | Cmp::Ne => return,
};
ends.push((x, End { at: e, strict }, upper, i));
};
put(a, op, b);
let flipped = match op {
Cmp::Lt => Cmp::Gt,
Cmp::Le => Cmp::Ge,
Cmp::Gt => Cmp::Lt,
Cmp::Ge => Cmp::Le,
o => o,
};
put(b, flipped, a);
}
for &(x, lo, up, i) in &ends {
if up {
continue;
}
for &(y, hi, up2, j) in &ends {
if up2 && i != j && same(x, y) && (side(lo.at).is_some() || side(hi.at).is_some()) {
let mut used = vec![i, j];
used.sort_unstable();
return Some((Band { x, lo, hi }, used));
}
}
}
None
}
}
/// The table's rows joined with the atom's selected rows of equal key (`tk` columns of the
/// table against `rk` columns of the atom, none for no key) where the band's value lies
/// between its ends, passing `checks`: the side that holds the value sorted by (key,
/// value), each row of the other side looking up its stretch by binary search. The pairs
/// come as [`hash_join`] and [`cross_join`] give them: table row after table row, each
/// one's atom rows rising (so each fact keeps the derivation found first). `n log n` plus
/// the pairs found (sorted).
#[allow(clippy::too_many_arguments)]
pub(crate) fn band_join(
par: &Par,
t: &Table,
r: &Rows,
sel: &Sel,
tk: &[usize],
rk: &[usize],
band: Band,
checks: &[Check],
) -> Pairs {
let none = Table::default();
// whether a value is at or past the lower end, and at or before the upper end
let above = |x: Value, lo: Value| if band.lo.strict { x > lo } else { x >= lo };
let below = |x: Value, hi: Value| if band.hi.strict { x < hi } else { x <= hi };
match band.x {
Src::R(xc) => {
// the atom's selected rows by (key, x, row); each table row finds its stretch
let mut order: Vec<u32> = (0..sel.len()).map(|i| sel.at(i)).collect();
par.sort_by(&mut order, |&a, &b| {
let (a, b) = (a as usize, b as usize);
rk.iter()
.map(|&c| r.get(c, a).cmp(&r.get(c, b)))
.find(|o| o.is_ne())
.unwrap_or(Ordering::Equal)
.then_with(|| r.get(xc, a).cmp(&r.get(xc, b)))
.then_with(|| a.cmp(&b))
});
pairs_of(
par,
par.split(t.len, |a, b| {
let (mut left, mut right) = (Vec::new(), Vec::new());
let mut found: Vec<u32> = Vec::new();
for l in a..b {
let key = |k: u32| {
tk.iter()
.zip(rk)
.map(|(&tc, &rc)| r.get(rc, k as usize).cmp(&t.cols[tc][l]))
.find(|o| o.is_ne())
.unwrap_or(Ordering::Equal)
};
let lo = Check::value(band.lo.at, t, l, r, 0);
let hi = Check::value(band.hi.at, t, l, r, 0);
let s = order.partition_point(|&k| match key(k) {
Ordering::Less => true,
Ordering::Greater => false,
Ordering::Equal => !above(r.get(xc, k as usize), lo),
});
let e = order.partition_point(|&k| match key(k) {
Ordering::Less => true,
Ordering::Greater => false,
Ordering::Equal => below(r.get(xc, k as usize), hi),
});
if s >= e {
continue;
}
found.clear();
found.extend_from_slice(&order[s..e]);
found.sort_unstable();
for &k in &found {
if checks.iter().all(|c| c.holds(t, l, r, k as usize)) {
left.push(l as u32);
right.push(k);
}
}
}
(left, right)
}),
)
}
Src::T(xc) => {
// the table's rows by (key, x, row); each atom row finds its stretch, the pairs
// then put in table row order
let xs = &t.cols[xc];
let mut order: Vec<u32> = (0..t.len as u32).collect();
par.sort_by(&mut order, |&a, &b| {
let (a, b) = (a as usize, b as usize);
tk.iter()
.map(|&c| t.cols[c][a].cmp(&t.cols[c][b]))
.find(|o| o.is_ne())
.unwrap_or(Ordering::Equal)
.then_with(|| xs[a].cmp(&xs[b]))
.then_with(|| a.cmp(&b))
});
let mut packed: Vec<u64> = par.concat(par.split(sel.len(), |a, b| {
let mut out: Vec<u64> = Vec::new();
for i in a..b {
let k = sel.at(i) as usize;
let key = |l: u32| {
tk.iter()
.zip(rk)
.map(|(&tc, &rc)| t.cols[tc][l as usize].cmp(&r.get(rc, k)))
.find(|o| o.is_ne())
.unwrap_or(Ordering::Equal)
};
let lo = Check::value(band.lo.at, &none, 0, r, k);
let hi = Check::value(band.hi.at, &none, 0, r, k);
let s = order.partition_point(|&l| match key(l) {
Ordering::Less => true,
Ordering::Greater => false,
Ordering::Equal => !above(xs[l as usize], lo),
});
let e = order.partition_point(|&l| match key(l) {
Ordering::Less => true,
Ordering::Greater => false,
Ordering::Equal => below(xs[l as usize], hi),
});
for &l in order.get(s..e).unwrap_or(&[]) {
if checks.iter().all(|c| c.holds(t, l as usize, r, k)) {
out.push(((l as u64) << 32) | k as u64);
}
}
}
out
}));
par.sort_by(&mut packed, |a, b| a.cmp(b));
Pairs {
left: par.fill(packed.len(), |i| (packed[i] >> 32) as u32),
right: par.fill(packed.len(), |i| packed[i] as u32),
}
}
Src::K(_) => unreachable!("a band's value is a column"),
}
}
/// Every table row with every selected atom row, passing `checks`.
pub(crate) fn cross_join(par: &Par, t: &Table, r: &Rows, sel: &Sel, checks: &[Check]) -> Pairs {
// A condition that one atom column decides per table row: each table row's atom rows
// picked by the SIMD range selection over that column (at the selected rows), the other
// conditions checked on them; the same pairs in the same order.
let n = sel.len();
if n >= CROSS_SIMD_MIN
&& let Some(p) = checks.iter().position(|c| c.range_col().is_some())
{
let j = checks[p].range_col().expect("found above");
let picked: Vec<u64>;
let col = match sel {
Sel::All(_) => r.cols[j].key(0, n),
Sel::Rows(rows) => {
picked = par.fill(n, |i| r.get(j, rows[i] as usize));
KeyCol::U64(&picked)
}
};
let rest: Vec<&Check> = checks
.iter()
.enumerate()
.filter(|&(i, _)| i != p)
.map(|(_, c)| c)
.collect();
let simd = par.device.simd();
return pairs_of(
par,
par.split(t.len, |a, b| {
let (mut left, mut right) = (Vec::new(), Vec::new());
let mut places = vec![0u32; n];
for l in a..b {
let (lo, hi, inside) = checks[p].range_at(t, l);
let m = simd.select_range(col, lo, hi, inside, 0, &mut places);
for &i in &places[..m] {
let k = sel.at(i as usize);
if rest.iter().all(|c| c.holds(t, l, r, k as usize)) {
left.push(l as u32);
right.push(k);
}
}
}
(left, right)
}),
);
}
cross_join_plain(par, t, r, sel, checks)
}
/// [`cross_join`] testing every condition on every pair: the reference of the SIMD path.
fn cross_join_plain(par: &Par, t: &Table, r: &Rows, sel: &Sel, checks: &[Check]) -> Pairs {
pairs_of(
par,
par.split(t.len, |a, b| {
let (mut left, mut right) = (Vec::new(), Vec::new());
for l in a..b {
for i in 0..sel.len() {
let k = sel.at(i);
if checks.iter().all(|c| c.holds(t, l, r, k as usize)) {
left.push(l as u32);
right.push(k);
}
}
}
(left, right)
}),
)
}
/// The table after a join step: its columns marked in `keep` at the pairs' left rows, then
/// `new` columns of the atom (variable, column) at their right rows; gathered in pieces on
/// the device's workers.
pub(crate) fn extend_table(
par: &Par,
t: &Table,
keep: &[bool],
r: &Rows,
p: &Pairs,
new: &[(Var, usize)],
) -> Table {
let n = p.left.len();
let mut cols: Vec<Vec<Value>> = Vec::with_capacity(t.cols.len() + new.len());
let mut vars = Vec::with_capacity(t.cols.len() + new.len());
for ((c, &v), _) in t.cols.iter().zip(&t.vars).zip(keep).filter(|x| *x.1) {
cols.push(gather(par, c, &p.left));
vars.push(v);
}
for &(v, j) in new {
cols.push(gather_rows(par, r, j, &p.right));
vars.push(v);
}
Table {
vars,
cols,
len: n,
distinct: false,
perm: None,
}
}
/// Column `j` of `r` at the selected rows, in one exact column written on the device's
/// workers.
pub(crate) fn gather_sel(par: &Par, r: &Rows, j: usize, sel: &Sel) -> Vec<Value> {
match sel {
Sel::All(n) => par.fill(*n, |i| r.get(j, i)),
Sel::Rows(at) => gather_rows(par, r, j, at),
}
}
/// `c` at the places `at`, in one exact column written on the device's workers.
pub(crate) fn gather(par: &Par, c: &[Value], at: &[u32]) -> Vec<Value> {
par.fill(at.len(), |i| c[at[i] as usize])
}
/// Column `j` of `r` at the rows `at`, in one exact column written on the device's workers.
pub(crate) fn gather_rows(par: &Par, r: &Rows, j: usize, at: &[u32]) -> Vec<Value> {
par.fill(at.len(), |i| r.get(j, at[i] as usize))
}
/// Whether each table row has a match among the indexed rows (`tk` columns against the
/// index's key).
pub(crate) fn semi_join(par: &Par, t: &Table, tk: &[usize], r: &Rows, ix: &Index) -> Vec<bool> {
semi_join_by(par, t.len, tk.len(), |j, l| t.cols[tk[j]][l], r, ix)
}
/// Whether each of `n` probe rows has a match among the indexed rows: probe row `l`'s key
/// column `j` (of `nk`, against the index's key) read as `key(j, l)`, so the probe's keys
/// need not be gathered into columns first.
pub(crate) fn semi_join_by(
par: &Par,
n: usize,
nk: usize,
key: impl Fn(usize, usize) -> Value + Sync,
r: &Rows,
ix: &Index,
) -> Vec<bool> {
let rk = ix.key();
par.fill_by(n, |lo, out| {
ix.any_each(
lo,
lo + out.len(),
|l| hash_of(nk, |j| key(j, l)),
|l, k| (0..nk).all(|j| key(j, l) == r.get(rk[j], k)),
|k| r.ahead(rk, k),
|l, found| out[l - lo] = found,
);
})
}
/// Where a column of head rows comes from: a column of the bindings (handed over, to be
/// moved in when every row goes in), or a constant.
#[derive(Debug)]
pub(crate) enum HeadCol {
Own(Vec<Value>),
Const(Value),
}
impl HeadCol {
#[inline]
fn get(&self, k: usize) -> Value {
match self {
HeadCol::Own(c) => c[k],
HeadCol::Const(x) => *x,
}
}
/// The first `n` values as a column of their own (moved when handed over).
fn into_col(self, n: usize) -> Vec<Value> {
match self {
HeadCol::Own(mut c) => {
c.truncate(n);
c
}
HeadCol::Const(x) => vec![x; n],
}
}
}
/// A bag of at least this many rows is made distinct once it has doubled since it last was.
const BAG_MIN: usize = 1 << 16;
/// The distinct rows of one relation as they arrive, in arrival order: `u64` columns and
/// an open-addressing table over the rows' hashes. Nothing is allocated per row (the
/// columns and the table grow by doubling).
#[derive(Debug)]
pub(crate) struct RowSet {
cols: Vec<Vec<Value>>,
hash: Vec<u64>,
/// Row numbers by hash, open addressing (atomic, so a batch goes in on the workers).
slots: Vec<AtomicU32>,
len: usize,
/// Rows kept as they come, repeats too, and made distinct by the sort at the end (and
/// whenever they doubled since they last were distinct, so a bag grows with its facts,
/// not with the bindings that find them). Only for rows whose arrival order nobody
/// reads: no why is kept of a bag.
bag: bool,
/// The bag's rows when it was last made distinct.
distinct_at: usize,
/// Times the slots grew one row at a time, and passes for the first of each kind run
/// over a batch (read by the tests).
#[cfg(test)]
grows: usize,
#[cfg(test)]
passes: usize,
}
impl RowSet {
pub(crate) fn new(arity: usize) -> Self {
RowSet {
cols: vec![Vec::new(); arity],
hash: Vec::new(),
slots: (0..16).map(|_| AtomicU32::new(NONE)).collect(),
len: 0,
bag: false,
distinct_at: 0,
#[cfg(test)]
grows: 0,
#[cfg(test)]
passes: 0,
}
}
/// The rows of a relation whose rules do not read it: kept as they come, repeats too
/// (no hash table), and made distinct by the sort at the end, on the device's workers.
pub(crate) fn bag(arity: usize) -> Self {
RowSet {
cols: vec![Vec::new(); arity],
hash: Vec::new(),
slots: Vec::new(),
len: 0,
bag: true,
distinct_at: 0,
#[cfg(test)]
grows: 0,
#[cfg(test)]
passes: 0,
}
}
pub(crate) fn len(&self) -> usize {
self.len
}
fn grow(&mut self) {
#[cfg(test)]
{
self.grows += 1;
}
let n = self.slots.len() * 2;
let mask = n - 1;
let mut slots = vec![NONE; n];
for (i, &h) in self.hash.iter().enumerate() {
let mut b = h as usize & mask;
while slots[b] != NONE {
b = (b + 1) & mask;
}
slots[b] = i as u32;
}
self.slots = slots.into_iter().map(AtomicU32::new).collect();
}
/// Rows `from..len` (distinct, and not held before) put in the slots on the device's
/// workers, the slots first made anew, larger, when the rows would fill half of them.
/// Which slot a row takes depends on the threads; which rows are held does not.
fn place(&mut self, par: &Par, from: usize) {
let hash = &self.hash;
let put = |slots: &[AtomicU32], lo: usize, hi: usize| {
let mask = slots.len() - 1;
for (i, &h) in hash.iter().enumerate().take(hi).skip(lo) {
let mut b = h as usize & mask;
while slots[b]
.compare_exchange(
NONE,
i as u32,
AtomicOrdering::Relaxed,
AtomicOrdering::Relaxed,
)
.is_err()
{
b = (b + 1) & mask;
}
}
};
if 2 * self.len > self.slots.len() {
let size = (2 * self.len).next_power_of_two().max(16);
let slots: Vec<AtomicU32> = par
.fill(size, |_| NONE)
.into_iter()
.map(AtomicU32::new)
.collect();
par.split(self.len, |lo, hi| put(&slots, lo, hi));
self.slots = slots;
} else {
let slots = &self.slots;
par.split(self.len - from, |lo, hi| put(slots, from + lo, from + hi));
}
}
/// Room for `extra` more rows without growing one row at a time: the slots made anew
/// on the device's workers when the rows would fill half of them.
fn reserve(&mut self, par: &Par, extra: usize) {
if 2 * (self.len + extra) > self.slots.len() {
// slots sized for the rows to come, the rows held placed in them on the workers
let size = (2 * (self.len + extra)).next_power_of_two().max(16);
self.slots = par
.fill(size, |_| NONE)
.into_iter()
.map(AtomicU32::new)
.collect();
self.place(par, 0);
}
}
/// Add `row`; true when it was new (always in a bag).
#[inline]
pub(crate) fn insert(&mut self, row: &[Value]) -> bool {
if self.bag {
// a repeat of the row before goes at once (rows often come in runs)
if self.len > 0
&& self
.cols
.iter()
.zip(row)
.all(|(c, &x)| c[self.len - 1] == x)
{
return false;
}
for (c, &x) in self.cols.iter_mut().zip(row) {
c.push(x);
}
self.len += 1;
return true;
}
let h = hash_of(row.len(), |j| row[j]);
self.insert_hashed(|j| row[j], h)
}
/// Add the row whose column `j` is `row(j)` and whose hash is `h`; true when it was new.
#[inline]
fn insert_hashed(&mut self, row: impl Fn(usize) -> Value, h: u64) -> bool {
if 2 * (self.len + 1) > self.slots.len() {
self.grow();
}
let mask = self.slots.len() - 1;
let mut b = h as usize & mask;
loop {
let s = self.slots[b].load(AtomicOrdering::Relaxed);
if s == NONE {
break;
}
let i = s as usize;
if self.hash[i] == h && self.cols.iter().enumerate().all(|(j, c)| c[i] == row(j)) {
return false;
}
b = (b + 1) & mask;
}
self.slots[b].store(self.len as u32, AtomicOrdering::Relaxed);
self.hash.push(h);
for (j, c) in self.cols.iter_mut().enumerate() {
c.push(row(j));
}
self.len += 1;
true
}
/// Whether a set (not a bag) holds the row whose column `j` is `row(j)`, of hash `h`.
#[inline]
fn holds(&self, row: impl Fn(usize) -> Value, h: u64) -> bool {
let mask = self.slots.len() - 1;
let mut b = h as usize & mask;
loop {
let s = self.slots[b].load(AtomicOrdering::Relaxed);
if s == NONE {
return false;
}
let i = s as usize;
if self.hash[i] == h && self.cols.iter().enumerate().all(|(j, c)| c[i] == row(j)) {
return true;
}
b = (b + 1) & mask;
}
}
/// Add the `n` rows whose columns `src` gives, as a batch. A set returns the rows that
/// were new (not held before, and the first of their kind in the batch), rising: their
/// hashes and the probe of the rows held run on the device's workers, then the new rows
/// go in, in order (a column handed over is moved in when every row is new and the set
/// was empty). `distinct`: the caller knows no two of the rows are equal. A bag takes
/// every row, returns nothing, and makes itself distinct once it has doubled since it
/// last was (on the device's workers).
pub(crate) fn add_batch(
&mut self,
par: &Par,
src: Vec<HeadCol>,
n: usize,
distinct: bool,
) -> Sel {
if n == 0 {
return Sel::Rows(Vec::new());
}
if self.bag {
let empty = self.len == 0;
for (c, s) in self.cols.iter_mut().zip(src) {
match s {
s if empty => *c = s.into_col(n),
HeadCol::Own(v) => c.extend_from_slice(&v[..n]),
HeadCol::Const(x) => c.resize(c.len() + n, x),
}
}
self.len += n;
if self.len > 2 * self.distinct_at.max(BAG_MIN) {
self.make_distinct(par);
}
return Sel::Rows(Vec::new());
}
let arity = src.len();
let h: Vec<u64> = hash_rows(par, n, &|k| hash_of(arity, |j| src[j].get(k)));
// the rows not held before (all when the set is empty)
let fresh: Sel = if self.len == 0 {
Sel::All(n)
} else {
let set = &*self;
Sel::Rows(par.concat(par.split(n, |lo, hi| {
(lo..hi)
.filter(|&k| !set.holds(|j| src[j].get(k), h[k]))
.map(|k| k as u32)
.collect::<Vec<u32>>()
})))
};
if fresh.len() < 2 * PIECE || par.device.threads() < 2 {
self.reserve(par, fresh.len());
let mut new = Vec::with_capacity(fresh.len());
for i in 0..fresh.len() {
let k = fresh.at(i) as usize;
if self.insert_hashed(|j| src[j].get(k), h[k]) {
new.push(k as u32);
}
}
return Sel::Rows(new);
}
// many: the first of each kind among them, appended whole and placed on the workers
let eq = |a: usize, b: usize| src.iter().all(|c| c.get(a) == c.get(b));
let new: Sel = if distinct {
fresh
} else {
#[cfg(test)]
{
self.passes += 1;
}
match &fresh {
Sel::All(_) => match kinds_hashed(par, &h, eq, |a, b| a < b) {
Kinds::Kept(k) => Sel::Rows(k),
Kinds::Distinct | Kinds::Skipped => fresh,
},
Sel::Rows(f) => match first_of_kind(
par,
f.len(),
false,
|i| h[f[i] as usize],
|a, b| eq(f[a] as usize, f[b] as usize),
) {
Some(k) => fresh.pick(par, k),
None => fresh,
},
}
};
let m = new.len();
if self.len == 0 && matches!(new, Sel::All(_)) {
// every row new into an empty set: the columns and hashes moved in
for (c, s) in self.cols.iter_mut().zip(src) {
*c = s.into_col(n);
}
self.hash = h;
} else {
for (c, s) in self.cols.iter_mut().zip(&src) {
let col = par.fill(m, |i| s.get(new.at(i) as usize));
if c.is_empty() {
*c = col;
} else {
c.extend_from_slice(&col);
}
}
let hs = par.fill(m, |i| h[new.at(i) as usize]);
if self.hash.is_empty() {
self.hash = hs;
} else {
self.hash.extend_from_slice(&hs);
}
}
let from = self.len;
self.len += m;
self.place(par, from);
new
}
/// A bag's rows made distinct (the first of each kind kept, in arrival order).
fn make_distinct(&mut self, par: &Par) {
let cols = &self.cols;
let arity = cols.len();
if let Some(keep) = first_of_kind(
par,
self.len,
true,
|i| hash_of(arity, |j| cols[j][i]),
|a, b| cols.iter().all(|c| c[a] == c[b]),
) {
self.cols = cols
.iter()
.map(|c| par.fill(keep.len(), |i| c[keep[i] as usize]))
.collect();
self.len = keep.len();
}
self.distinct_at = self.len;
}
/// The rows sorted (by the first column, then the next, ...), each once (of a bag's
/// repeats the first to come), as facts whose columns are `u32` where every value
/// fits; with `order`, the arrival number of each sorted row (else nothing).
pub(crate) fn finish(self, par: &Par, order: bool) -> (Facts, Vec<u32>) {
sort_rows(par, &self.cols, self.len, self.bag, order)
}
/// The rows as they came, as facts (a copy, not sorted; a bag's repeats kept).
pub(crate) fn facts(&self) -> Facts {
if self.cols.is_empty() {
return Facts::flag(self.len > 0);
}
let cols: Vec<Column> = self
.cols
.iter()
.map(|c| narrow(c.iter().copied(), c.len()))
.collect();
Facts::from_columns(cols).expect("equal lengths")
}
}
/// The rows of `cols` sorted, each once when `distinct` (the first to come kept), as facts
/// (`u32` columns where every value fits); with `order`, the arrival number of each row
/// out. One or two columns that fit in `u32` sort as packed `u64` keys; wider rows by their
/// first column, the rest read only between equal ones. Every pass runs on the device's
/// workers: whether a column fits (read in place: the order does not change it), the keys,
/// the sort, the repeats dropped (each row against the one before it) and the gathers.
fn sort_rows(
par: &Par,
cols: &[Vec<Value>],
len: usize,
distinct: bool,
order: bool,
) -> (Facts, Vec<u32>) {
if cols.is_empty() {
// no column: the one empty row (the first to come) or none
let ord = if order && len > 0 {
vec![0]
} else {
Vec::new()
};
return (Facts::flag(len > 0), ord);
}
let fits: Vec<bool> = cols.iter().map(|c| fits_u32(par, &c[..len])).collect();
let packed = cols.len() == 1 || (cols.len() == 2 && fits[0] && fits[1]);
if packed {
let key = |i: usize| match cols {
[a] => a[i],
[a, b] => (a[i] << 32) | b[i],
_ => unreachable!("one or two columns"),
};
let (keys, ord) = if order {
let mut kv: Vec<(u64, u32)> = par.fill(len, |i| (key(i), i as u32));
par.sort_by(&mut kv, |a, b| a.cmp(b));
if distinct {
kv = first_of_runs(par, kv, |a, b| a.0 == b.0);
}
let keys = par.fill(kv.len(), |i| kv[i].0);
let ord = par.fill(kv.len(), |i| kv[i].1);
(keys, ord)
} else {
let mut keys: Vec<u64> = par.fill(len, key);
par.sort_by(&mut keys, |a, b| a.cmp(b));
if distinct {
keys = first_of_runs(par, keys, |a, b| a == b);
}
(keys, Vec::new())
};
let n = keys.len();
let out = if cols.len() == 1 {
if fits[0] {
vec![Column::from(par.fill(n, |i| keys[i] as u32))]
} else {
vec![Column::from(keys)]
}
} else {
vec![
Column::from(par.fill(n, |i| (keys[i] >> 32) as u32)),
Column::from(par.fill(n, |i| keys[i] as u32)),
]
};
return (Facts::from_columns(out).expect("equal lengths"), ord);
}
// (first column, row number), the other columns read only between equal first values
let mut kv: Vec<(u64, u32)> = par.fill(len, |i| (cols[0][i], i as u32));
par.sort_by(&mut kv, |&(x, a), &(y, b)| {
x.cmp(&y).then_with(|| {
for c in &cols[1..] {
let o = c[a as usize].cmp(&c[b as usize]);
if o != Ordering::Equal {
return o;
}
}
a.cmp(&b)
})
});
let mut ord: Vec<u32> = par.fill(kv.len(), |i| kv[i].1);
drop(kv);
if distinct {
ord = first_of_runs(par, ord, |&a, &b| {
cols.iter().all(|c| c[a as usize] == c[b as usize])
});
}
let out: Vec<Column> = cols
.iter()
.zip(&fits)
.map(|(c, &fit)| {
if fit {
Column::from(par.fill(ord.len(), |i| c[ord[i] as usize] as u32))
} else {
Column::from(gather(par, c, &ord))
}
})
.collect();
let facts = Facts::from_columns(out).expect("equal lengths");
(facts, if order { ord } else { Vec::new() })
}
/// Whether every value of `c` fits in `u32`, read in pieces on the device's workers.
fn fits_u32(par: &Par, c: &[Value]) -> bool {
par.split(c.len(), |lo, hi| {
c[lo..hi].iter().all(|&x| x <= u32::MAX as Value)
})
.into_iter()
.all(|f| f)
}
/// The sorted `v` with each run of items `same` as the one before it cut to its first
/// (`v` itself when there is no run), compacted on the device's workers.
fn first_of_runs<T: Copy + Default + Send + Sync>(
par: &Par,
v: Vec<T>,
same: impl Fn(&T, &T) -> bool + Sync,
) -> Vec<T> {
let first = |i: usize| i == 0 || !same(&v[i - 1], &v[i]);
if par
.split(v.len(), |lo, hi| (lo..hi).all(first))
.into_iter()
.all(|f| f)
{
return v;
}
par.concat(par.split(v.len(), |lo, hi| {
(lo..hi)
.filter(|&i| first(i))
.map(|i| v[i])
.collect::<Vec<T>>()
}))
}
/// Values as a column: `u32` when every one fits, else `u64`.
pub(crate) fn narrow(vals: impl Iterator<Item = Value> + Clone, n: usize) -> Column {
if vals.clone().all(|x| x <= u32::MAX as Value) {
let mut v: Vec<u32> = Vec::with_capacity(n);
v.extend(vals.map(|x| x as u32));
Column::from(v)
} else {
let mut v: Vec<u64> = Vec::with_capacity(n);
v.extend(vals);
Column::from(v)
}
}
/// The rows of `f` from row `lo` on (the buffers shared, nothing copied).
pub(crate) fn rows_from(f: &Facts, lo: usize) -> Facts {
let n = f.len().saturating_sub(lo);
let lo = lo.min(f.len());
let cols: Vec<Column> = (0..f.arity())
.map(|i| match f.column(i) {
Column::U32(b) => Column::U32(b.slice(lo, n)),
Column::U64(b) => Column::U64(b.slice(lo, n)),
})
.collect();
if cols.is_empty() {
return Facts::flag(f.len() > lo);
}
Facts::from_columns(cols).expect("equal lengths")
}
/// The rows of `new` that `old` lacks, in `new`'s order: `old` indexed on every column,
/// each row of `new` probed (in pieces over the device's workers).
pub(crate) fn new_rows(par: &Par, old: &Facts, new: &Facts) -> Facts {
let arity = new.arity();
if old.is_empty() {
return new.clone();
}
if arity == 0 {
// old holds the one empty row: new has nothing old lacks
return Facts::flag(false);
}
let (o, r) = (Rows::of(old), Rows::of(new));
let key: Vec<usize> = (0..arity).collect();
let ix = Index::build(par, &o, Sel::All(old.len()), &key);
let keep: Vec<u32> = par.concat(par.split(new.len(), |lo, hi| {
let mut out: Vec<u32> = Vec::new();
ix.any_each(
lo,
hi,
|k| hash_of(arity, |j| r.get(j, k)),
|k, q| (0..arity).all(|j| o.get(j, q) == r.get(j, k)),
|q| o.ahead(&key, q),
|k, found| {
if !found {
out.push(k as u32);
}
},
);
out
}));
let cols: Vec<Column> = (0..arity)
.map(|j| narrow(keep.iter().map(|&k| r.get(j, k as usize)), keep.len()))
.collect();
Facts::from_columns(cols).expect("equal lengths")
}
/// Row `k` of `f` against `t`, column by column.
pub(crate) fn cmp_row(f: &Facts, k: usize, t: &[Value]) -> Ordering {
for (i, &x) in t.iter().enumerate() {
let o = f.value(i, k).cmp(&x);
if o != Ordering::Equal {
return o;
}
}
Ordering::Equal
}
/// The row of sorted facts `f` equal to `t`.
pub(crate) fn find_row(f: &Facts, t: &[Value]) -> Option<usize> {
if t.len() != f.arity() {
return None;
}
let (mut lo, mut hi) = (0, f.len());
while lo < hi {
let mid = (lo + hi) / 2;
match cmp_row(f, mid, t) {
Ordering::Less => lo = mid + 1,
Ordering::Greater => hi = mid,
Ordering::Equal => return Some(mid),
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_index_built_on_the_workers_lists_each_key_rising_at_any_thread_count() {
let n = 10 * PIECE + 3;
let c: Vec<u32> = (0..n as u32).map(|k| (k * 7919) % 5003).collect();
let f = Facts::from_columns(vec![Column::from(c.clone())]).expect("one column");
let r = Rows::of(&f);
let sel: Vec<u32> = (0..n as u32).filter(|k| k % 3 != 1).collect();
for threads in [1, 3, 8] {
let par = Par::new(CpuDevice::new(threads));
let ix = Index::build(&par, &r, Sel::Rows(sel.clone()), &[0]);
for key in [0u32, 1, 17, 5002] {
let mut got = Vec::new();
let h = hash_of(1, |_| key as Value);
ix.probe(h, |k| r.get(0, k) == key as Value, |k| got.push(k));
let want: Vec<u32> = sel
.iter()
.copied()
.filter(|&k| c[k as usize] == key)
.collect();
assert_eq!(got, want, "key {key}, {threads} threads");
}
}
}
#[test]
fn an_extended_index_walks_no_chain_and_keeps_each_chain_rising() {
let keys = |n: usize| -> Facts {
let c: Vec<u32> = (0..n as u32)
.map(|k| if k < 1000 { k } else { 7 })
.collect();
Facts::from_columns(vec![Column::from(c)]).expect("one column")
};
for threads in [1, 3, 8] {
let par = Par::new(CpuDevice::new(threads));
let (a, b) = (keys(1000), keys(1500));
let mut ix = Index::build(&par, &Rows::of(&a), Sel::All(1000), &[0]);
let r = Rows::of(&b);
ix.extend(&par, &r);
let mut got = Vec::new();
ix.probe(hash_of(1, |_| 7), |k| r.get(0, k) == 7, |k| got.push(k));
let want: Vec<u32> = std::iter::once(7).chain(1000..1500).collect();
assert_eq!(got, want, "{threads} threads");
assert_eq!(ix.walked, 0, "{threads} threads");
}
}
/// [`hash_join`] one probe after another: the reference of the batched probes.
fn hash_join_one(t: &Table, tk: &[usize], r: &Rows, ix: &Index, checks: &[Check]) -> Pairs {
let rk = ix.key();
let (mut left, mut right) = (Vec::new(), Vec::new());
for l in 0..t.len {
let h = hash_of(tk.len(), |j| t.cols[tk[j]][l]);
ix.probe(
h,
|k| (0..tk.len()).all(|j| t.cols[tk[j]][l] == r.get(rk[j], k)),
|k| {
if checks.iter().all(|c| c.holds(t, l, r, k as usize)) {
left.push(l as u32);
right.push(k);
}
},
);
}
Pairs { left, right }
}
#[test]
fn batched_probes_give_the_rows_of_one_probe_after_another_at_any_thread_count() {
// keys from few values (long runs of equal keys) to many (mostly misses), two key
// columns, one narrow; probes of every piece size and a remainder batch
for (m, sel_every) in [(3u64, 1u32), (61, 3), (5003, 1), (1 << 40, 2)] {
let n = 3 * PIECE / 2 + 5;
let a = noise(n, m, 11);
let b: Vec<u32> = noise(n, 4, 12).iter().map(|&x| x as u32).collect();
let f = Facts::from_columns(vec![Column::U64(a.clone().into()), Column::from(b)])
.expect("two columns");
let r = Rows::of(&f);
let len = PIECE + 37;
let t = Table {
vars: vec![Var(0), Var(1), Var(2)],
cols: vec![noise(len, m, 13), noise(len, 4, 14), noise(len, 1000, 15)],
len,
..Table::default()
};
let sel: Vec<u32> = (0..n as u32).filter(|k| k % sel_every == 0).collect();
let checks = [Check::Cmp(Src::T(2), Cmp::Lt, Src::R(0))];
for threads in [1, 3, 8] {
let par = Par::new(CpuDevice::new(threads));
for key in [&[0usize][..], &[0, 1][..]] {
let tk: Vec<usize> = key.to_vec();
let ix = Index::build(&par, &r, Sel::Rows(sel.clone()), key);
for ch in [&[][..], &checks[..]] {
let want = hash_join_one(&t, &tk, &r, &ix, ch);
let before = ix.batches.load(AtomicOrdering::Relaxed);
let got = hash_join(&par, &t, &tk, &r, &ix, ch);
assert_eq!(got.left, want.left, "m {m} {threads} threads {key:?}");
assert_eq!(got.right, want.right, "m {m} {threads} threads {key:?}");
let batches = ix.batches.load(AtomicOrdering::Relaxed) - before;
let pieces = if threads < 2 { 1 } else { len.div_ceil(PIECE) };
assert!(
batches >= len.div_ceil(BATCH)
&& batches <= len.div_ceil(BATCH) + pieces,
"probes in batches of {BATCH}: {batches} batches for {len} probes"
);
}
let want: Vec<bool> = (0..t.len)
.map(|l| {
let h = hash_of(tk.len(), |j| t.cols[tk[j]][l]);
ix.any(h, |k| {
(0..tk.len()).all(|j| t.cols[tk[j]][l] == r.get(key[j], k))
})
})
.collect();
let before = ix.batches.load(AtomicOrdering::Relaxed);
assert_eq!(semi_join(&par, &t, &tk, &r, &ix), want, "m {m} {threads}");
assert!(
ix.batches.load(AtomicOrdering::Relaxed) - before >= len.div_ceil(BATCH)
);
}
}
}
}
#[test]
fn a_band_join_gives_the_pairs_of_the_cross_product_cut_by_its_conditions() {
// table columns: key, value, lo, hi, extra; atom columns: key, value, lo, hi; values
// from a few (many repeats, ends equal to values) to the largest code; one side
// large (pieces on the workers), the other small
let wide = |v: Vec<u64>| -> Vec<u64> {
v.into_iter()
.enumerate()
.map(|(i, x)| if i % 97 == 0 { Value::MAX } else { x })
.collect()
};
for (n, len) in [(PIECE + 9, 120), (120, PIECE + 41)] {
let (rlo, rspan) = (noise(n, 300, 31), noise(n, 60, 32));
let f = Facts::from_columns(vec![
Column::from(
noise(n, 4, 33)
.iter()
.map(|&x| x as u32)
.collect::<Vec<_>>(),
),
Column::U64(wide(noise(n, 360, 34)).into()),
Column::U64(rlo.clone().into()),
Column::U64(
rlo.iter()
.zip(&rspan)
.map(|(a, b)| a + b)
.collect::<Vec<_>>()
.into(),
),
])
.expect("four columns");
let r = Rows::of(&f);
let (tlo, tspan) = (noise(len, 300, 35), noise(len, 80, 36));
let t = Table {
vars: (0..5).map(Var).collect(),
cols: vec![
noise(len, 4, 37),
wide(noise(len, 360, 38)),
tlo.clone(),
tlo.iter().zip(&tspan).map(|(a, b)| a + b).collect(),
noise(len, 360, 39),
],
len,
..Table::default()
};
let sel = Sel::Rows((0..n as u32).filter(|k| k % 5 != 2).collect());
let extra = Check::Cmp(Src::T(4), Cmp::Lt, Src::R(1));
let bands = [
(Src::T(1), Src::R(2), Src::R(3)),
(Src::R(1), Src::T(2), Src::T(3)),
(Src::R(1), Src::K(100), Src::T(3)),
(Src::T(1), Src::R(2), Src::K(Value::MAX)),
];
for threads in [1, 8] {
let par = Par::new(CpuDevice::new(threads));
for (x, lo, hi) in bands {
for (ls, hs) in [(false, true), (true, false), (false, false), (true, true)] {
for keyed in [false, true] {
let (tk, rk): (&[usize], &[usize]) =
if keyed { (&[0], &[0]) } else { (&[], &[]) };
let with = keyed == ls;
let rest: Vec<Check> = with.then_some(extra).into_iter().collect();
let mut all = rest.clone();
all.push(Check::Cmp(lo, if ls { Cmp::Lt } else { Cmp::Le }, x));
all.push(Check::Cmp(x, if hs { Cmp::Lt } else { Cmp::Le }, hi));
if keyed {
all.push(Check::Cmp(Src::T(0), Cmp::Eq, Src::R(0)));
}
let want = cross_join_plain(&par, &t, &r, &sel, &all);
let band = Band {
x,
lo: End { at: lo, strict: ls },
hi: End { at: hi, strict: hs },
};
let got = band_join(&par, &t, &r, &sel, tk, rk, band, &rest);
let at = format!("{x:?} {ls} {hs} keyed {keyed} {n}x{len} {threads}");
assert!(!want.left.is_empty(), "{at}");
assert_eq!(got.left, want.left, "{at}");
assert_eq!(got.right, want.right, "{at}");
}
}
}
}
}
}
#[test]
fn band_find_takes_a_range_or_a_lower_and_an_upper_comparison_of_one_value() {
let k = |c: &Check| Band::find(std::slice::from_ref(c)).map(|(_, u)| u);
// a range with its ends on the other side, or one end a constant
assert_eq!(
k(&Check::Within(Src::T(0), Src::R(1), Src::R(2))),
Some(vec![0])
);
assert_eq!(
k(&Check::Within(Src::R(0), Src::K(3), Src::T(2))),
Some(vec![0])
);
// not: an end on the value's side, both ends constants
assert_eq!(k(&Check::Within(Src::T(0), Src::T(1), Src::R(2))), None);
assert_eq!(k(&Check::Within(Src::T(0), Src::K(1), Src::K(2))), None);
// `lo <= x`, `hi > x` (flipped), with a check between them
let cs = [
Check::Cmp(Src::R(1), Cmp::Le, Src::T(0)),
Check::Cmp(Src::T(3), Cmp::Eq, Src::R(0)),
Check::Cmp(Src::R(2), Cmp::Gt, Src::T(0)),
];
let (b, used) = Band::find(&cs).expect("a band");
assert_eq!(used, vec![0, 2]);
assert!(matches!(b.x, Src::T(0)));
assert!(matches!(b.lo.at, Src::R(1)) && !b.lo.strict);
assert!(matches!(b.hi.at, Src::R(2)) && b.hi.strict);
// two lower ends only, or both sides one: none
let cs = [
Check::Cmp(Src::R(1), Cmp::Le, Src::T(0)),
Check::Cmp(Src::T(0), Cmp::Gt, Src::R(2)),
];
assert!(Band::find(&cs).is_none());
let cs = [
Check::Cmp(Src::T(1), Cmp::Le, Src::T(0)),
Check::Cmp(Src::T(0), Cmp::Lt, Src::T(2)),
];
assert!(Band::find(&cs).is_none());
}
#[test]
fn new_rows_by_batched_probes_keeps_the_rows_one_probe_after_another_keeps() {
let old = Facts::from_columns(vec![
Column::U64(noise(3 * PIECE, 900, 21).into()),
Column::from(
noise(3 * PIECE, 3, 22)
.iter()
.map(|&x| x as u32)
.collect::<Vec<_>>(),
),
])
.expect("two columns");
let new = Facts::from_columns(vec![
Column::U64(noise(2 * PIECE + 9, 1200, 23).into()),
Column::from(
noise(2 * PIECE + 9, 3, 24)
.iter()
.map(|&x| x as u32)
.collect::<Vec<_>>(),
),
])
.expect("two columns");
let (o, r) = (Rows::of(&old), Rows::of(&new));
let one = Par::new(CpuDevice::new(1));
let ix = Index::build(&one, &o, Sel::All(old.len()), &[0, 1]);
let want: Vec<Vec<Value>> = (0..new.len())
.filter(|&k| {
!ix.any(hash_of(2, |j| r.get(j, k)), |q| {
(0..2).all(|j| o.get(j, q) == r.get(j, k))
})
})
.map(|k| vec![r.get(0, k), r.get(1, k)])
.collect();
assert!(!want.is_empty() && want.len() < new.len());
for threads in [1, 3, 8] {
let got = new_rows(&Par::new(CpuDevice::new(threads)), &old, &new);
let got: Vec<Vec<Value>> = got.rows().collect();
assert_eq!(got, want, "{threads} threads");
}
}
#[test]
fn an_index_never_extended_holds_no_tail_and_one_extended_keeps_each_chain_rising() {
let keys = |n: usize| -> Facts {
let c: Vec<u32> = (0..n as u32).map(|k| k % 300).collect();
Facts::from_columns(vec![Column::from(c)]).expect("one column")
};
// the serial and the parallel linking of the chains
for (n, threads) in [(1000, 1), (1000, 8), (5 * PIECE, 8)] {
let par = Par::new(CpuDevice::new(threads));
let a = keys(n);
let mut ix = Index::build(&par, &Rows::of(&a), Sel::All(n), &[0]);
assert!(
ix.tail.is_empty(),
"{n} rows, {threads} threads: a tail of {} slots built for no extend",
ix.tail.len()
);
let b = keys(n + 100);
let r = Rows::of(&b);
ix.extend(&par, &r);
let mut got = Vec::new();
ix.probe(hash_of(1, |_| 7), |k| r.get(0, k) == 7, |k| got.push(k));
let want: Vec<u32> = (0..(n + 100) as u32).filter(|k| k % 300 == 7).collect();
assert_eq!(got, want, "{n} rows, {threads} threads");
}
}
#[test]
fn the_chains_of_an_index_built_on_the_workers_are_first_touched_by_the_workers() {
let n = 5 * PIECE;
let c: Vec<u32> = (0..n as u32).map(|k| k % 300).collect();
let a = Facts::from_columns(vec![Column::from(c)]).expect("one column");
let par = Par::new(CpuDevice::new(8));
let _ix = Index::build(&par, &Rows::of(&a), Sel::All(n), &[0]);
// head and next filled on the workers: zeroed memory first touched by the probes
// cost fail 0.067 -> 0.060 s (loki, 8 threads)
assert_eq!(
par.slot_tables(),
(2, 0, 0),
"(filled on the workers, zeroed memory, kept)"
);
}
#[test]
fn the_first_of_kind_table_is_kept_for_the_next_call_and_keeps_the_same_rows() {
// walk asks for a first-of-kind table every round: fresh zeroed memory each time
// cost walk 0.930 -> 1.045 s (loki, 8 threads), first touched by the probes
let big = noise(5 * PIECE, 1000, 41);
let small = noise(2 * PIECE + 7, 300, 42);
let kinds =
|par: &Par, h: &[u64]| match kinds_hashed(par, h, |i, j| h[i] == h[j], |a, b| a < b) {
Kinds::Kept(k) => k,
_ => panic!("the rows repeat"),
};
for threads in [1, 3, 8] {
let par = Par::new(CpuDevice::new(threads));
// a smaller table after a larger one, then the larger again over dirty slots
for h in [&big, &small, &big] {
let fresh = Par::new(CpuDevice::new(threads));
assert_eq!(kinds(&par, h), kinds(&fresh, h), "{threads} threads");
}
assert_eq!(
par.slot_tables(),
(0, 1, 2),
"(filled on the workers, zeroed memory, kept), {threads} threads"
);
}
}
/// A sequence of pseudo-random numbers below `m`.
fn noise(n: usize, m: u64, seed: u64) -> Vec<u64> {
let mut x = seed | 1;
(0..n)
.map(|_| {
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
x % m
})
.collect()
}
#[test]
fn the_parallel_sort_sorts_as_the_std_sort_at_any_size_and_thread_count() {
for threads in [1, 2, 3, 4, 7, 16] {
let par = Par::new(CpuDevice::new(threads));
for n in [0, 1, 5, 2 * SORT_PIECE - 1, 2 * SORT_PIECE, 70_001, 300_000] {
for m in [3, u64::MAX] {
let mut v = noise(n, m, n as u64 + threads as u64);
let mut want = v.clone();
want.sort_unstable();
par.sort_by(&mut v, |a, b| a.cmp(b));
assert_eq!(v, want, "{n} items below {m} on {threads} threads");
// (key, row) pairs by key only: every pair kept, keys in order
let mut kv: Vec<(u64, u32)> =
noise(n, m, 7).into_iter().zip(0..n as u32).collect();
par.sort_by(&mut kv, |a, b| a.0.cmp(&b.0));
assert!(kv.is_sorted_by_key(|p| p.0));
let mut rows: Vec<u32> = kv.iter().map(|p| p.1).collect();
rows.sort_unstable();
assert!(rows.iter().copied().eq(0..n as u32));
}
}
}
}
#[test]
fn split_gives_the_pieces_in_order_at_any_thread_count() {
for threads in [1, 3, 8] {
let par = Par::new(CpuDevice::new(threads));
for n in [0, 1, PIECE, PIECE + 1, 10 * PIECE + 17] {
let got = par.concat(par.split(n, |lo, hi| (lo..hi).collect::<Vec<_>>()));
assert!(got.into_iter().eq(0..n), "{n} on {threads} threads");
}
}
}
#[test]
fn the_first_of_kind_pass_asks_for_its_slots_ahead_and_keeps_the_same_rows() {
let n = 3 * PIECE + 11;
for m in [3u64, 1000, u64::MAX] {
let a = noise(n, m, 31);
let b = noise(n, 4, 32);
let mut seen = std::collections::HashSet::new();
let want: Vec<u32> = (0..n)
.filter(|&i| seen.insert((a[i], b[i])))
.map(|i| i as u32)
.collect();
for threads in [1, 3, 8] {
let par = Par::new(CpuDevice::new(threads));
let before = AHEAD_FETCHES.load(AtomicOrdering::Relaxed);
let got = first_of_kind(
&par,
n,
false,
|i| hash_of(2, |j| if j == 0 { a[i] } else { b[i] }),
|i, j| a[i] == a[j] && b[i] == b[j],
);
let asked = AHEAD_FETCHES.load(AtomicOrdering::Relaxed) - before;
match got {
Some(g) => assert_eq!(g, want, "rows below {m}, {threads} threads"),
None => assert_eq!(want.len(), n, "rows below {m}"),
}
// both passes ask once a row (the counter is shared with other tests)
assert!(asked >= 2 * n, "{asked} slots asked ahead for {n} rows");
}
}
}
#[test]
fn first_of_kind_keeps_the_least_row_of_each_kind_at_any_thread_count() {
for threads in [1, 2, 5, 16] {
let par = Par::new(CpuDevice::new(threads));
for n in [0, 1, 7, 5000, 3 * PIECE + 11, 200_000] {
for m in [1, 3, 1000, u64::MAX] {
let a = noise(n, m, 11 + n as u64);
let b = noise(n, 4, m.wrapping_add(3));
let mut seen = std::collections::HashSet::new();
let want: Vec<u32> = (0..n)
.filter(|&i| seen.insert((a[i], b[i])))
.map(|i| i as u32)
.collect();
let got = first_of_kind(
&par,
n,
false,
|i| hash_of(2, |j| if j == 0 { a[i] } else { b[i] }),
|i, j| a[i] == a[j] && b[i] == b[j],
);
match got {
Some(g) => assert_eq!(g, want, "{n} rows below {m}, {threads} threads"),
None => assert_eq!(want.len(), n, "{n} rows below {m}"),
}
// the guard passes over a table of few repeats only
let guarded = first_of_kind(
&par,
n,
true,
|i| hash_of(2, |j| if j == 0 { a[i] } else { b[i] }),
|i, j| a[i] == a[j] && b[i] == b[j],
);
if let Some(g) = guarded {
assert_eq!(g, want);
} else if n >= GUARD_MIN {
assert!(want.len() * 10 >= n * 8, "{} kinds of {n}", want.len());
}
}
}
}
}
#[test]
fn a_small_batch_goes_in_without_growing_the_slots_row_by_row() {
let par = Par::new(CpuDevice::new(4));
let mut set = RowSet::new(1);
let first: Vec<Value> = (0..10).collect();
set.add_batch(&par, vec![HeadCol::Own(first)], 10, false);
let more: Vec<Value> = (0..1000).collect();
let new = set.add_batch(&par, vec![HeadCol::Own(more)], 1000, false);
assert_eq!(new.len(), 990);
assert_eq!(set.len(), 1000);
assert_eq!(set.grows, 0, "the slots grew row by row");
}
#[test]
fn a_batch_known_distinct_takes_no_second_pass_and_keeps_every_new_row() {
for threads in [1, 3, 8] {
let par = Par::new(CpuDevice::new(threads));
let mut set = RowSet::new(2);
let n = 4 * PIECE + 17;
let a: Vec<Value> = (0..n as Value).collect();
let b: Vec<Value> = (0..n as Value).map(|x| x % 7).collect();
let src = || vec![HeadCol::Own(a.clone()), HeadCol::Own(b.clone())];
let new = set.add_batch(&par, src(), n, true);
assert_eq!(new.len(), n);
assert_eq!(set.passes, 0, "{threads} threads");
let again = set.add_batch(&par, src(), n, true);
assert_eq!(again.len(), 0);
let mut half: Vec<Value> = (0..2 * n as Value).collect();
half.retain(|x| x % 2 == 0);
let hb: Vec<Value> = half.iter().map(|x| x % 7).collect();
let m = half.len();
let got = set.add_batch(
&par,
vec![HeadCol::Own(half.clone()), HeadCol::Own(hb)],
m,
true,
);
let got: Vec<u32> = (0..got.len()).map(|i| got.at(i)).collect();
let want: Vec<u32> = (0..m)
.filter(|&i| half[i] >= n as Value)
.map(|i| i as u32)
.collect();
assert_eq!(got, want, "{threads} threads");
assert_eq!(set.passes, 0, "{threads} threads");
assert_eq!(set.len(), n + want.len());
}
}
#[test]
fn a_bag_makes_itself_distinct_as_it_doubles_and_a_set_returns_its_new_rows() {
let par = Par::new(CpuDevice::new(4));
let mut bag = RowSet::bag(2);
let mut set = RowSet::new(2);
let mut want = std::collections::BTreeSet::new();
let mut seen = std::collections::HashSet::new();
for round in 0..12u64 {
let a = noise(40_000, 5000, round + 1);
let b = noise(40_000, 3, round + 100);
let src = || vec![HeadCol::Own(a.clone()), HeadCol::Own(b.clone())];
bag.add_batch(&par, src(), a.len(), false);
let new = set.add_batch(&par, src(), a.len(), false);
let new: Vec<u32> = (0..new.len()).map(|i| new.at(i)).collect();
let fresh: Vec<u32> = (0..a.len())
.filter(|&i| seen.insert((a[i], b[i])))
.map(|i| i as u32)
.collect();
assert_eq!(new, fresh, "round {round}");
want.extend((0..a.len()).map(|i| vec![a[i], b[i]]));
assert!(bag.len() <= 3 * want.len().max(BAG_MIN) + a.len());
}
let (facts, _) = bag.finish(&par, false);
assert_eq!(
facts.rows().collect::<std::collections::BTreeSet<_>>(),
want
);
let (facts, _) = set.finish(&par, false);
assert_eq!(
facts.rows().collect::<std::collections::BTreeSet<_>>(),
want
);
}
/// Values near every edge a range turns on: zero, one, the u32 limit, the sign bit of
/// a u64 and the largest u64; and small ones that repeat.
fn edgy(n: usize, seed: u64) -> Vec<u64> {
let edges = [
0,
1,
2,
3,
u32::MAX as u64,
1 << 32,
1 << 63,
u64::MAX - 1,
u64::MAX,
];
let mut x = seed;
(0..n)
.map(|_| {
x = x
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
match (x >> 60) % 3 {
0 => edges[(x >> 20) as usize % edges.len()],
1 => (x >> 33) % 6,
_ => x ^ (x >> 29),
}
})
.collect()
}
const OPS: [Cmp; 6] = [Cmp::Eq, Cmp::Ne, Cmp::Lt, Cmp::Le, Cmp::Gt, Cmp::Ge];
#[test]
fn a_condition_of_one_atom_column_is_the_range_holds_keeps() {
let tv = edgy(40, 3);
let rv = edgy(200, 4);
let t = Table {
vars: vec![Var(0), Var(1)],
cols: vec![tv.clone(), tv.iter().rev().copied().collect()],
len: tv.len(),
..Table::default()
};
let f = Facts::from_columns(vec![Column::U64(rv.clone().into())]).expect("one column");
let r = Rows::of(&f);
let mut checks = Vec::new();
for op in OPS {
checks.push(Check::Cmp(Src::R(0), op, Src::T(0)));
checks.push(Check::Cmp(Src::T(1), op, Src::R(0)));
checks.push(Check::Cmp(Src::R(0), op, Src::K(1 << 63)));
checks.push(Check::Cmp(Src::K(0), op, Src::R(0)));
}
checks.push(Check::Within(Src::R(0), Src::T(0), Src::T(1)));
checks.push(Check::Within(Src::R(0), Src::K(0), Src::K(0)));
for c in &checks {
assert_eq!(c.range_col(), Some(0), "{c:?}");
for l in 0..t.len {
let (lo, hi, inside) = c.range_at(&t, l);
for (k, &x) in rv.iter().enumerate() {
assert_eq!(
(lo <= x && x <= hi) == inside,
c.holds(&t, l, &r, k),
"{c:?} row {l} value {x}"
);
}
}
}
// two atom columns, or none: no range
assert_eq!(Check::Cmp(Src::R(0), Cmp::Lt, Src::R(0)).range_col(), None);
assert_eq!(Check::Cmp(Src::T(0), Cmp::Lt, Src::K(3)).range_col(), None);
}
#[test]
fn a_cross_join_picked_by_ranges_gives_the_pairs_of_every_test_on_every_level() {
let tv = edgy(3 * PIECE / 2 + 5, 7);
let t = Table {
vars: vec![Var(0), Var(1)],
cols: vec![tv.clone(), edgy(tv.len(), 8)],
len: tv.len(),
..Table::default()
};
let wide = edgy(301, 9);
let narrow: Vec<u32> = wide.iter().map(|&x| x as u32).collect();
let f = Facts::from_columns(vec![Column::U64(wide.clone().into()), Column::from(narrow)])
.expect("two columns");
let r = Rows::of(&f);
let rows: Vec<u32> = (0..301).filter(|k| k % 4 != 1).collect();
let mut sets: Vec<Vec<Check>> = Vec::new();
for (i, op) in OPS.into_iter().enumerate() {
let other = OPS[(i + 2) % 6];
sets.push(vec![Check::Cmp(Src::R(i % 2), op, Src::T(0))]);
sets.push(vec![
Check::Cmp(Src::T(1), op, Src::R(1)),
Check::Cmp(Src::R(0), other, Src::T(0)),
]);
}
sets.push(vec![Check::Within(Src::R(1), Src::T(0), Src::T(1))]);
let reference = Par::new(CpuDevice::new(1).with_simd(kleene_sparse::Simd::scalar()));
for checks in &sets {
for sel in [Sel::All(301), Sel::Rows(rows.clone())] {
let want = cross_join_plain(&reference, &t, &r, &sel, checks);
for level in kleene_sparse::Simd::available() {
let simd = kleene_sparse::Simd::with_level(level).expect("available");
for threads in [1, 4] {
let par = Par::new(CpuDevice::new(threads).with_simd(simd));
let got = cross_join(&par, &t, &r, &sel, checks);
assert_eq!(got.left, want.left, "{checks:?} {level:?} {threads}");
assert_eq!(got.right, want.right, "{checks:?} {level:?} {threads}");
}
}
}
}
}
#[test]
fn a_selection_by_a_constant_keeps_the_rows_every_test_keeps_on_every_level() {
let n = 3 * PIECE + 11;
let wide = edgy(n, 11);
let narrow: Vec<u32> = edgy(n, 12).iter().map(|&x| x as u32).collect();
let f = Facts::from_columns(vec![
Column::U64(wide.clone().into()),
Column::from(narrow.clone()),
])
.expect("two columns");
let r = Rows::of(&f);
let v = Term::Var(Var(0));
let cases: Vec<(Vec<Term>, Vec<Check>)> = vec![
(vec![Term::Const(3), v], vec![]),
(vec![v, Term::Const(u32::MAX as u64)], vec![]),
(
vec![v, Term::Const(2)],
vec![Check::Cmp(Src::R(0), Cmp::Gt, Src::K(1))],
),
(
vec![v, Term::Var(Var(1))],
vec![Check::Cmp(Src::K(1 << 63), Cmp::Le, Src::R(0))],
),
(
vec![v, Term::Var(Var(1))],
vec![Check::Within(Src::R(1), Src::K(1), Src::K(4))],
),
(vec![v, v], vec![Check::Cmp(Src::R(1), Cmp::Ne, Src::K(0))]),
];
for (terms, checks) in &cases {
let want: Vec<u32> = (0..n)
.filter(|&k| {
terms.iter().enumerate().all(|(j, t)| match *t {
Term::Const(x) => r.get(j, k) == x,
Term::Var(_) => terms[..j]
.iter()
.position(|u| u == t)
.is_none_or(|f| r.get(f, k) == r.get(j, k)),
}) && checks.iter().all(|c| c.holds(&Table::default(), 0, &r, k))
})
.map(|k| k as u32)
.collect();
for level in kleene_sparse::Simd::available() {
let simd = kleene_sparse::Simd::with_level(level).expect("available");
for threads in [1, 4] {
let par = Par::new(CpuDevice::new(threads).with_simd(simd));
let Sel::Rows(got) = select(&par, terms, &r, checks) else {
panic!("a selection");
};
assert_eq!(got, want, "{terms:?} {checks:?} {level:?} {threads}");
}
}
}
}
}