mod compare;
mod formula;
mod int64_compare;
mod offset_expr;
mod shifted;
#[cfg(test)]
mod tests;
pub(crate) use formula::is_strict_comparison;
pub(crate) use offset_expr::{OffsetExpression, fill_offset_default};
use super::PACKED_CLASSIFY_CHUNK_ROWS;
use super::packed::{ColumnPredicate, ColumnThresholds, StaticClassification};
use crate::execution::common::progress::COARSE_WORK_BATCH_SIZE;
use crate::execution::storage::history_buffer::SharedHistoryBuffer;
use compare::{apply, apply_navigation_group};
use datafusion::arrow::array::ArrayRef;
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::logical_expr::Operator;
use datafusion_common::{Result, ScalarValue};
use datafusion_execution::memory_pool::MemoryReservation;
use formula::{
FormulaBank, FormulaPlan, NeighborThresholds, PendingNeighborLiterals, add_group,
compare_flags, push_pending_neighbor_literal,
};
use int64_compare::Int64ComparisonShape;
use std::collections::BTreeMap;
use std::ops::Range;
use std::sync::Arc;
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Neighbor {
pub(crate) column: usize,
pub(crate) shift: i64,
pub(crate) default: Option<Arc<ScalarValue>>,
}
#[derive(Debug, Default)]
pub(crate) struct OffsetColumns {
pub(crate) columns: Vec<(usize, Neighbor)>,
pub(crate) previous: usize,
pub(crate) following: usize,
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum StaticAtom {
Constant(bool),
Literal(usize, Operator, ScalarValue),
NeighborLiteral(Neighbor, Operator, ScalarValue),
Compare(usize, Operator, Neighbor),
IsNull(Neighbor, bool),
}
impl StaticAtom {
fn remap_input(&mut self, indices: &[usize]) {
match self {
Self::Constant(_) => {}
Self::Literal(col, ..) => *col = indices[*col],
Self::NeighborLiteral(neighbor, ..) => {
neighbor.column = indices[neighbor.column]
}
Self::Compare(col, _, neighbor) => {
*col = indices[*col];
neighbor.column = indices[neighbor.column];
}
Self::IsNull(neighbor, _) => neighbor.column = indices[neighbor.column],
}
}
}
#[derive(Debug, Clone)]
pub(crate) enum StaticFormula {
Atom(StaticAtom),
And(Box<StaticFormula>, Box<StaticFormula>),
Or(Box<StaticFormula>, Box<StaticFormula>),
}
impl StaticFormula {
fn remap_input(&mut self, indices: &[usize]) {
match self {
Self::Atom(atom) => atom.remap_input(indices),
Self::And(l, r) | Self::Or(l, r) => {
l.remap_input(indices);
r.remap_input(indices);
}
}
}
fn atom_count(&self) -> usize {
match self {
Self::Atom(_) => 1,
Self::And(l, r) | Self::Or(l, r) => l.atom_count() + r.atom_count(),
}
}
}
#[derive(Debug, Clone)]
pub(crate) enum StaticRule {
Literal(usize, Operator, ScalarValue),
NeighborLiteral(Neighbor, Operator, ScalarValue),
ColumnFormula(usize, ColumnPredicate),
Compare(usize, Operator, Neighbor),
IsNull(Neighbor, bool),
Constant(bool),
Formula(StaticFormula),
Expr(OffsetExpression),
}
impl StaticRule {
pub(crate) fn remap_input(&mut self, indices: &[usize]) {
match self {
Self::Literal(col, ..) | Self::ColumnFormula(col, _) => *col = indices[*col],
Self::NeighborLiteral(neighbor, ..) => {
neighbor.column = indices[neighbor.column]
}
Self::Compare(col, _, neighbor) => {
*col = indices[*col];
neighbor.column = indices[neighbor.column];
}
Self::IsNull(neighbor, _) => neighbor.column = indices[neighbor.column],
Self::Formula(formula) => formula.remap_input(indices),
Self::Expr(expr) => {
for input in &mut expr.inputs {
input.column = indices[input.column];
}
}
Self::Constant(_) => {}
}
}
}
impl Neighbor {
#[inline]
pub(super) fn missing_len(&self, len: usize) -> usize {
let Some(value) = self.default.as_deref() else {
return len;
};
let width = match value {
ScalarValue::Utf8(Some(s)) => s.len(),
ScalarValue::Binary(Some(b)) => b.len(),
_ => 0,
};
len.min(COARSE_WORK_BATCH_SIZE)
.min(i32::MAX as usize / width.max(1))
}
#[inline]
pub(crate) fn span<'a>(
&self,
history: &'a SharedHistoryBuffer,
partition: &Range<usize>,
row: usize,
len: usize,
) -> Result<(Option<(&'a ArrayRef, usize)>, usize)> {
let distance = self.shift.unsigned_abs() as usize;
let target = if self.shift < 0 {
let missing = partition.start.saturating_add(distance).saturating_sub(row);
if missing != 0 {
return Ok((None, self.missing_len(missing.min(len))));
}
row - distance
} else {
let Some(target) = row.checked_add(distance).filter(|&r| r < partition.end)
else {
return Ok((None, self.missing_len(len)));
};
target
};
let (i, offset) = history.locate(target)?;
let batch = history.batch(i);
Ok((
Some((batch.column(self.column), offset)),
len.min(batch.num_rows() - offset)
.min(partition.end - target),
))
}
#[inline]
pub(super) fn valid_span(
&self,
absolute: usize,
partition: &Range<usize>,
len: usize,
) -> Range<usize> {
let distance = self.shift.unsigned_abs() as usize;
let valid = if self.shift < 0 {
partition.start.saturating_add(distance)..partition.end
} else {
partition.start..partition.end.saturating_sub(distance)
};
let lo = valid.start.saturating_sub(absolute).min(len);
let hi = valid.end.saturating_sub(absolute).min(len).max(lo);
lo..hi
}
#[inline]
pub(super) fn visit_shifted_column(
&self,
history: &SharedHistoryBuffer,
batch: &RecordBatch,
local: usize,
absolute: usize,
out: &mut [u64],
mut visit: impl FnMut(usize, &ArrayRef, usize, &mut [u64]) -> Result<()>,
) -> Result<()> {
if out.is_empty() {
return Ok(());
}
let distance = self.shift.unsigned_abs() as usize;
let right = if self.shift < 0 {
local.checked_sub(distance)
} else {
(local + out.len())
.checked_add(distance)
.is_some_and(|end| end <= batch.num_rows())
.then(|| local + distance)
};
if let Some(right) = right {
return visit(local, batch.column(self.column), right, out);
}
let mut at = 0;
while at < out.len() {
let row = absolute + at;
let neighbor_row = if self.shift < 0 {
row - distance
} else {
row + distance
};
let (index, offset) = history.locate(neighbor_row)?;
let other = history.batch(index);
let count = (out.len() - at).min(other.num_rows() - offset);
visit(
local + at,
other.column(self.column),
offset,
&mut out[at..at + count],
)?;
at += count;
}
Ok(())
}
}
#[derive(Debug, Default)]
pub(crate) struct StaticNavigation {
pub(crate) always: u64,
pub(crate) previous: usize,
pub(crate) following: usize,
expressions: Vec<(OffsetExpression, u64)>,
groups: Vec<(Option<usize>, Neighbor, [u64; 4])>,
pending_neighbor_literals: PendingNeighborLiterals,
neighbor_columns: Vec<NeighborThresholds>,
formula_banks: Vec<FormulaBank>,
}
#[derive(Clone, Copy)]
pub(crate) struct NavigationInput<'a> {
pub(crate) origin: usize,
pub(crate) ranges: &'a [Range<usize>],
pub(crate) first_start: usize,
pub(crate) last_end: usize,
}
impl StaticNavigation {
pub(super) fn mark_referenced_input_columns(&self, needed: &mut [bool]) {
for (expr, _) in &self.expressions {
expr.mark_referenced_input_columns(needed);
}
for (left, neighbor, _) in &self.groups {
if let Some(col) = *left
&& let Some(slot) = needed.get_mut(col)
{
*slot = true;
}
if let Some(slot) = needed.get_mut(neighbor.column) {
*slot = true;
}
}
for neighbor in &self.neighbor_columns {
if let Some(slot) = needed.get_mut(neighbor.neighbor.column) {
*slot = true;
}
}
for bank in &self.formula_banks {
for column in bank.referenced_columns() {
if let Some(slot) = needed.get_mut(column) {
*slot = true;
}
}
}
}
pub(super) fn group_count(&self) -> usize {
self.groups.len()
+ self.neighbor_columns.len()
+ self
.formula_banks
.iter()
.map(|b| b.columns.len() + b.neighbor_columns.len() + b.groups.len())
.sum::<usize>()
+ self
.expressions
.iter()
.map(|(e, _)| e.inputs.len())
.sum::<usize>()
}
pub(super) fn is_empty(&self) -> bool {
self.expressions.is_empty()
&& self.groups.is_empty()
&& self.neighbor_columns.is_empty()
&& self.formula_banks.is_empty()
&& self.always == 0
}
pub(super) fn finalize(
&mut self,
literals: BTreeMap<usize, Vec<(ColumnPredicate, u64)>>,
) -> Option<(Vec<ColumnThresholds>, u64)> {
let mut columns = Vec::new();
let mut literal_bits = 0;
for (input, rules) in literals {
let extra_atoms: usize =
rules.iter().map(|(pred, _)| pred.leaf_count()).sum();
let fits_formula_tree = rules
.iter()
.all(|(pred, _)| pred.is_homogeneous() || pred.leaf_count() <= 32);
if (self.previous != 0 || self.following != 0)
&& fits_formula_tree
&& let Some(bank) = self.formula_banks.iter_mut().find(|bank| {
bank.pending_literals.contains_key(&input)
&& bank.pending_atoms.len() + extra_atoms <= 64
})
{
for (pred, bit) in rules {
let formula = pred.into_static_formula(input);
bank.add_formula(formula, bit, &mut |_| None)?;
}
} else {
literal_bits |= rules.iter().fold(0, |bits, (_, bit)| bits | bit);
columns.push(ColumnThresholds::from_predicates(input, rules)?);
}
}
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<_>>>()?;
for bank in &mut self.formula_banks {
bank.finalize()?;
}
Some((columns, literal_bits))
}
pub(super) fn add(&mut self, rule: StaticRule, bit: u64) -> Option<()> {
let (left, neighbor, flags) = match rule {
StaticRule::Constant(value) => {
if value {
self.always |= bit
};
return Some(());
}
StaticRule::NeighborLiteral(neighbor, op, lit) => {
StaticClassification::supports_comparison(op, &lit).then_some(())?;
self.track_offset(&neighbor)?;
push_pending_neighbor_literal(
&mut self.pending_neighbor_literals,
neighbor,
lit,
op,
bit,
);
return Some(());
}
StaticRule::Compare(left, op, neighbor) => {
(Some(left), neighbor, compare_flags(op)?)
}
StaticRule::IsNull(neighbor, null) => {
(None, neighbor, [!null, !null, !null, null])
}
StaticRule::Formula(formula) => {
let needed = formula.atom_count();
if needed > 64 {
return None;
}
let fits_last = self
.formula_banks
.last()
.is_some_and(|b| b.pending_atoms.len() + needed <= 64);
if !fits_last {
self.formula_banks.push(FormulaBank::default());
}
let bank = self.formula_banks.last_mut().expect("pushed bank");
let mut previous = self.previous;
let mut following = self.following;
let mut track = |neighbor: &Neighbor| -> Option<()> {
let offset = usize::try_from(neighbor.shift.unsigned_abs()).ok()?;
if neighbor.shift < 0 {
previous = previous.max(offset);
} else {
following = following.max(offset);
}
Some(())
};
bank.add_formula(formula, bit, &mut track)?;
self.previous = previous;
self.following = following;
return Some(());
}
StaticRule::Expr(expr) => {
for neighbor in &expr.inputs {
self.track_offset(neighbor)?;
}
self.expressions.push((expr, bit));
return Some(());
}
StaticRule::Literal(..) | StaticRule::ColumnFormula(..) => return None,
};
self.track_offset(&neighbor)?;
add_group(&mut self.groups, left, neighbor, flags, bit);
Some(())
}
fn track_offset(&mut self, neighbor: &Neighbor) -> Option<()> {
let offset = usize::try_from(neighbor.shift.unsigned_abs()).ok()?;
if neighbor.shift < 0 {
self.previous = self.previous.max(offset);
} else {
self.following = self.following.max(offset);
}
Some(())
}
pub(super) fn formula_bits(&self) -> u64 {
self.formula_banks
.iter()
.fold(0, |bits, bank| bits | bank.output_bits)
}
pub(super) fn formula_referenced_columns(&self, required: u64, out: &mut Vec<usize>) {
for bank in &self.formula_banks {
if bank.output_bits & required == 0 {
continue;
}
out.extend(bank.referenced_columns());
}
}
pub(super) fn classify_formula_banks(
&self,
batch: &RecordBatch,
start: usize,
masks: &mut [u64],
required: u64,
) -> Result<()> {
debug_assert_eq!((self.previous, self.following), (0, 0));
let mut atom_buf = [0; PACKED_CLASSIFY_CHUNK_ROWS];
for bank in &self.formula_banks {
if bank.output_bits & required != 0 {
bank.classify_current_slice(batch, start, masks, &mut atom_buf)?;
}
}
Ok(())
}
pub(in crate::execution) fn formula_work(&self) -> usize {
self.formula_banks
.iter()
.flat_map(|bank| &bank.formulas)
.map(|formula| match &formula.plan {
FormulaPlan::Tree { nodes, .. } => nodes.len(),
FormulaPlan::AllOf(_) | FormulaPlan::AnyOf(_) => 1,
})
.sum()
}
pub(crate) fn classify_current(
&self,
batch: &RecordBatch,
start: usize,
masks: &mut [u64],
) -> Result<()> {
debug_assert_eq!((self.previous, self.following), (0, 0));
for (expr, bit) in &self.expressions {
let chunk_rows = match expr.int64_compare.as_ref().map(|cmp| cmp.shape) {
Some(Int64ComparisonShape::Offset) => COARSE_WORK_BATCH_SIZE,
_ => PACKED_CLASSIFY_CHUNK_ROWS,
};
for (i, out) in masks.chunks_mut(chunk_rows).enumerate() {
let offset = i * chunk_rows;
if let Some(cmp) = &expr.int64_compare
&& cmp.apply(&expr.inputs, batch, start + offset, out, *bit, None)?
{
continue;
}
let arrays = expr
.inputs
.iter()
.map(|n| batch.column(n.column).slice(start + offset, out.len()))
.collect();
let inputs = RecordBatch::try_new(Arc::clone(&expr.schema), arrays)?;
expr.apply(&inputs, out, *bit)?;
}
}
for neighbor in &self.neighbor_columns {
neighbor.thresholds.classify_array(
batch.column(neighbor.neighbor.column),
start,
masks,
)?;
}
for (column, neighbor, bits) in &self.groups {
apply(
column.map(|c| batch.column(c)),
start,
batch.column(neighbor.column),
start,
bits,
masks,
)?;
}
if !self.formula_banks.is_empty() {
let mut atom_buf = [0; PACKED_CLASSIFY_CHUNK_ROWS];
for bank in &self.formula_banks {
bank.classify_current_slice(batch, start, masks, &mut atom_buf)?;
}
}
Ok(())
}
pub(crate) fn classify(
&self,
history: &SharedHistoryBuffer,
input: NavigationInput,
(batch_start, batch): (usize, &RecordBatch),
start: usize,
masks: &mut [u64],
memory: &MemoryReservation,
) -> Result<()> {
let range = start..start + masks.len();
let mut local = start;
let mut segment = input
.ranges
.partition_point(|r| r.end <= batch_start + local);
let mut segmented = 0;
for (expr, bit) in &self.expressions {
let chunk_rows = match expr.int64_compare.as_ref().map(|cmp| cmp.shape) {
Some(Int64ComparisonShape::Offset) => COARSE_WORK_BATCH_SIZE,
_ => PACKED_CLASSIFY_CHUNK_ROWS,
};
for (i, out) in masks.chunks_mut(chunk_rows).enumerate() {
let offset = i * chunk_rows;
if let Some(cmp) = &expr.int64_compare
&& cmp.apply(
&expr.inputs,
batch,
start + offset,
out,
*bit,
matches!(cmp.shape, Int64ComparisonShape::Arithmetic)
.then_some((history, input, batch_start)),
)?
{
continue;
}
let Some(inputs) = expr.batch_inputs(
input,
batch_start,
batch,
start + offset,
out.len(),
)?
else {
segmented |= bit;
break;
};
expr.apply(&inputs, out, *bit)?;
}
}
if segmented == 0
&& self.groups.is_empty()
&& self.neighbor_columns.is_empty()
&& self.formula_banks.is_empty()
{
return Ok(());
}
let mut atom_buf_storage;
let atom_buf: &mut [u64] = if self.formula_banks.is_empty() {
&mut []
} else {
atom_buf_storage = [0u64; PACKED_CLASSIFY_CHUNK_ROWS];
&mut atom_buf_storage
};
while local < range.end {
let span = &input.ranges[segment];
let len = (span.end - batch_start - local).min(range.end - local);
let absolute = input.origin + batch_start + local;
let first = if segment == 0 {
input.first_start
} else {
input.origin + span.start
};
let end = if segment + 1 == input.ranges.len() {
input.last_end
} else {
input.origin + span.end
};
let out = &mut masks[local - range.start..local - range.start + len];
for (expr, bit) in &self.expressions {
if segmented & bit == 0 {
continue;
}
expr.classify(history, &(first..end), absolute, out, *bit, memory)?;
}
for neighbor in &self.neighbor_columns {
neighbor.classify_span(
history,
batch,
local,
absolute,
first..end,
out,
)?;
}
for (column, neighbor, bits) in &self.groups {
apply_navigation_group(
history,
batch,
local,
absolute,
first..end,
*column,
neighbor,
bits,
out,
memory,
)?;
}
for bank in &self.formula_banks {
let mut offset = 0;
while offset < len {
let chunk = (len - offset).min(atom_buf.len());
let atoms = &mut atom_buf[..chunk];
atoms.fill(bank.always);
for column in &bank.columns {
column.classify(batch, local + offset, atoms)?;
}
for neighbor in &bank.neighbor_columns {
neighbor.classify_span(
history,
batch,
local + offset,
absolute + offset,
first..end,
atoms,
)?;
}
for (column, neighbor, bits) in &bank.groups {
apply_navigation_group(
history,
batch,
local + offset,
absolute + offset,
first..end,
*column,
neighbor,
bits,
atoms,
memory,
)?;
}
bank.evaluate_formulas(atoms, &mut out[offset..offset + chunk]);
offset += chunk;
}
}
local += len;
segment += 1;
}
Ok(())
}
}