use super::compare::apply;
use super::{Neighbor, StaticAtom, StaticFormula};
use crate::execution::classification::PACKED_CLASSIFY_CHUNK_ROWS;
use crate::execution::classification::packed::{ColumnThresholds, StaticClassification};
use crate::execution::storage::history_buffer::SharedHistoryBuffer;
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::common::{Result, ScalarValue};
use datafusion::logical_expr::Operator;
use std::collections::BTreeMap;
use std::ops::Range;
#[derive(Debug, Clone, Copy)]
pub(super) enum FormulaNode {
Atom(u64),
And(u16, u16),
Or(u16, u16),
}
#[derive(Debug)]
pub(super) enum FormulaPlan {
AllOf(u64),
AnyOf(u64),
Tree { nodes: Vec<FormulaNode>, root: u16 },
}
#[derive(Debug)]
pub(super) struct CompiledFormula {
bit: u64,
pub(super) plan: FormulaPlan,
}
impl CompiledFormula {
#[inline]
fn evaluate(&self, atoms: &[u64], out: &mut [u64]) {
let bit = self.bit;
match &self.plan {
FormulaPlan::AllOf(req) => {
let req = *req;
for (&a, mask) in atoms.iter().zip(out.iter_mut()) {
let hit = ((a & req) == req) as u64;
*mask |= bit & hit.wrapping_neg();
}
}
FormulaPlan::AnyOf(any) => {
let any = *any;
for (&a, mask) in atoms.iter().zip(out.iter_mut()) {
let hit = ((a & any) != 0) as u64;
*mask |= bit & hit.wrapping_neg();
}
}
FormulaPlan::Tree { nodes, root } => {
let root = *root;
for (&a, mask) in atoms.iter().zip(out.iter_mut()) {
let mut vals = 0_u64;
for (idx, node) in nodes.iter().enumerate() {
let truth = match *node {
FormulaNode::Atom(b) => a & b != 0,
FormulaNode::And(l, r) => {
((vals >> l) & (vals >> r) & 1) != 0
}
FormulaNode::Or(l, r) => {
(((vals >> l) | (vals >> r)) & 1) != 0
}
};
vals |= u64::from(truth) << idx;
}
let hit = (vals >> root) & 1;
*mask |= bit & hit.wrapping_neg();
}
}
}
}
}
#[derive(Debug)]
pub(super) struct NeighborThresholds {
pub(super) neighbor: Neighbor,
pub(super) thresholds: ColumnThresholds,
missing_mask: u64,
}
impl NeighborThresholds {
pub(super) fn new(
neighbor: Neighbor,
rules: Vec<(ScalarValue, Operator, u64)>,
) -> Option<Self> {
let thresholds = ColumnThresholds::new(neighbor.column, rules)?;
let missing_mask = match neighbor.default.as_deref() {
Some(value) => thresholds.eval_scalar(value).ok()?,
None => 0,
};
Some(Self {
neighbor,
thresholds,
missing_mask,
})
}
#[inline]
pub(super) fn classify_span(
&self,
history: &SharedHistoryBuffer,
batch: &RecordBatch,
local: usize,
absolute: usize,
partition: Range<usize>,
out: &mut [u64],
) -> Result<()> {
let len = out.len();
let valid = self.neighbor.valid_span(absolute, &partition, len);
if self.missing_mask != 0 {
for missing in [0..valid.start, valid.end..len] {
for word in &mut out[missing] {
*word |= self.missing_mask;
}
}
}
self.neighbor.visit_shifted_column(
history,
batch,
local + valid.start,
absolute + valid.start,
&mut out[valid],
|_, col, offset, out| self.thresholds.classify_array(col, offset, out),
)
}
}
pub(super) type PendingNeighborLiterals =
Vec<(Neighbor, Vec<(ScalarValue, Operator, u64)>)>;
pub(super) fn push_pending_neighbor_literal(
pending: &mut PendingNeighborLiterals,
neighbor: Neighbor,
lit: ScalarValue,
op: Operator,
bit: u64,
) {
if let Some((_, rules)) = pending.iter_mut().find(|(n, _)| n == &neighbor) {
rules.push((lit, op, bit));
} else {
pending.push((neighbor, vec![(lit, op, bit)]));
}
}
#[derive(Debug, Default)]
pub(super) struct FormulaBank {
pub(super) always: u64,
pub(super) output_bits: u64,
pub(super) pending_atoms: Vec<StaticAtom>,
pub(super) pending_literals: BTreeMap<usize, Vec<(ScalarValue, Operator, u64)>>,
pending_neighbor_literals: PendingNeighborLiterals,
pub(super) columns: Vec<ColumnThresholds>,
pub(super) neighbor_columns: Vec<NeighborThresholds>,
pub(super) groups: Vec<(Option<usize>, Neighbor, [u64; 4])>,
pub(super) formulas: Vec<CompiledFormula>,
}
impl FormulaBank {
pub(super) fn referenced_columns(&self) -> impl Iterator<Item = usize> + '_ {
self.columns
.iter()
.map(ColumnThresholds::input_column)
.chain(self.neighbor_columns.iter().map(|n| n.neighbor.column))
.chain(self.groups.iter().flat_map(|(left, neighbor, _)| {
left.iter().copied().chain(std::iter::once(neighbor.column))
}))
}
#[inline]
pub(super) fn evaluate_formulas(&self, atoms: &[u64], out: &mut [u64]) {
for formula in &self.formulas {
formula.evaluate(atoms, out);
}
}
#[inline]
pub(super) fn classify_current_slice(
&self,
batch: &RecordBatch,
start: usize,
masks: &mut [u64],
atom_buf: &mut [u64; PACKED_CLASSIFY_CHUNK_ROWS],
) -> Result<()> {
let mut offset = 0;
while offset < masks.len() {
let chunk = (masks.len() - offset).min(atom_buf.len());
let atoms = &mut atom_buf[..chunk];
atoms.fill(self.always);
for column in &self.columns {
column.classify(batch, start + offset, atoms)?;
}
for neighbor in &self.neighbor_columns {
neighbor.thresholds.classify_array(
batch.column(neighbor.neighbor.column),
start + offset,
atoms,
)?;
}
for (column, neighbor, bits) in &self.groups {
apply(
column.map(|c| batch.column(c)),
start + offset,
batch.column(neighbor.column),
start + offset,
bits,
atoms,
)?;
}
self.evaluate_formulas(atoms, &mut masks[offset..offset + chunk]);
offset += chunk;
}
Ok(())
}
fn intern_atom(
&mut self,
atom: StaticAtom,
track_offset: &mut impl FnMut(&Neighbor) -> Option<()>,
) -> Option<u64> {
if let Some(pos) = self.pending_atoms.iter().position(|a| a == &atom) {
return Some(1_u64 << pos);
}
if self.pending_atoms.len() >= 64 {
return None;
}
let bit = 1_u64 << self.pending_atoms.len();
self.pending_atoms.push(atom.clone());
match atom {
StaticAtom::Constant(value) => {
if value {
self.always |= bit;
}
}
StaticAtom::Literal(input, op, lit) => {
StaticClassification::supports_comparison(op, &lit).then_some(())?;
self.pending_literals
.entry(input)
.or_default()
.push((lit, op, bit));
}
StaticAtom::NeighborLiteral(neighbor, op, lit) => {
StaticClassification::supports_comparison(op, &lit).then_some(())?;
track_offset(&neighbor)?;
push_pending_neighbor_literal(
&mut self.pending_neighbor_literals,
neighbor,
lit,
op,
bit,
);
}
StaticAtom::Compare(left, op, neighbor) => {
let flags = compare_flags(op)?;
track_offset(&neighbor)?;
add_group(&mut self.groups, Some(left), neighbor, flags, bit);
}
StaticAtom::IsNull(neighbor, null) => {
let flags = [!null, !null, !null, null];
track_offset(&neighbor)?;
add_group(&mut self.groups, None, neighbor, flags, bit);
}
}
Some(bit)
}
pub(super) fn add_formula(
&mut self,
formula: StaticFormula,
bit: u64,
track_offset: &mut impl FnMut(&Neighbor) -> Option<()>,
) -> Option<()> {
fn homogeneous(formula: &StaticFormula, disjunction: bool) -> bool {
match (formula, disjunction) {
(StaticFormula::Atom(_), _) => true,
(StaticFormula::And(l, r), false) | (StaticFormula::Or(l, r), true) => {
homogeneous(l, disjunction) && homogeneous(r, disjunction)
}
_ => false,
}
}
fn collect_bits(
bank: &mut FormulaBank,
f: StaticFormula,
track_offset: &mut impl FnMut(&Neighbor) -> Option<()>,
) -> Option<u64> {
match f {
StaticFormula::Atom(atom) => bank.intern_atom(atom, track_offset),
StaticFormula::And(l, r) | StaticFormula::Or(l, r) => {
let lb = collect_bits(bank, *l, track_offset)?;
let rb = collect_bits(bank, *r, track_offset)?;
Some(lb | rb)
}
}
}
fn emit_tree(
bank: &mut FormulaBank,
f: StaticFormula,
nodes: &mut Vec<FormulaNode>,
track_offset: &mut impl FnMut(&Neighbor) -> Option<()>,
) -> Option<u16> {
if nodes.len() >= 64 {
return None;
}
let node = match f {
StaticFormula::Atom(atom) => {
FormulaNode::Atom(bank.intern_atom(atom, track_offset)?)
}
StaticFormula::And(l, r) => {
let li = emit_tree(bank, *l, nodes, track_offset)?;
let ri = emit_tree(bank, *r, nodes, track_offset)?;
FormulaNode::And(li, ri)
}
StaticFormula::Or(l, r) => {
let li = emit_tree(bank, *l, nodes, track_offset)?;
let ri = emit_tree(bank, *r, nodes, track_offset)?;
FormulaNode::Or(li, ri)
}
};
if nodes.len() >= 64 {
return None;
}
let idx = u16::try_from(nodes.len()).ok()?;
nodes.push(node);
Some(idx)
}
let disjunction = matches!(formula, StaticFormula::Or(..));
let plan = if homogeneous(&formula, disjunction) {
let bits = collect_bits(self, formula, track_offset)?;
if disjunction {
FormulaPlan::AnyOf(bits)
} else {
FormulaPlan::AllOf(bits)
}
} else {
let mut nodes = Vec::new();
let root = emit_tree(self, formula, &mut nodes, track_offset)?;
FormulaPlan::Tree { nodes, root }
};
self.output_bits |= bit;
self.formulas.push(CompiledFormula { bit, plan });
Some(())
}
pub(super) fn finalize(&mut self) -> Option<()> {
let pending = std::mem::take(&mut self.pending_literals);
self.columns = pending
.into_iter()
.map(|(input, rules)| ColumnThresholds::new(input, rules))
.collect::<Option<Vec<_>>>()?;
let pending_neighbors = std::mem::take(&mut self.pending_neighbor_literals);
self.neighbor_columns = pending_neighbors
.into_iter()
.map(|(neighbor, rules)| NeighborThresholds::new(neighbor, rules))
.collect::<Option<Vec<_>>>()?;
self.pending_atoms.clear();
self.pending_atoms.shrink_to_fit();
Some(())
}
}
pub(crate) fn is_strict_comparison(op: Operator) -> bool {
compare_flags(op).is_some()
}
pub(super) fn compare_flags(op: Operator) -> Option<[bool; 4]> {
match op {
Operator::Lt => Some([true, false, false, false]),
Operator::LtEq => Some([true, true, false, false]),
Operator::Eq => Some([false, true, false, false]),
Operator::NotEq => Some([true, false, true, false]),
Operator::Gt => Some([false, false, true, false]),
Operator::GtEq => Some([false, true, true, false]),
_ => None,
}
}
pub(super) fn add_group(
groups: &mut Vec<(Option<usize>, Neighbor, [u64; 4])>,
left: Option<usize>,
neighbor: Neighbor,
flags: [bool; 4],
bit: u64,
) {
let index = groups
.iter()
.position(|(column, n, _)| *column == left && n == &neighbor)
.unwrap_or_else(|| {
groups.push((left, neighbor, [0; 4]));
groups.len() - 1
});
let masks = &mut groups[index].2;
for (mask, flag) in masks.iter_mut().zip(flags) {
if flag {
*mask |= bit;
}
}
}