use std::sync::Arc;
use vortex_array::ArrayRef;
use vortex_array::Columnar;
use vortex_array::ExecutionCtx;
use vortex_array::IntoArray;
use vortex_array::VortexSessionExecute;
use vortex_array::aggregate_fn::AggregateFnRef;
use vortex_array::aggregate_fn::AggregateFnSatisfaction;
use vortex_array::aggregate_fn::fns::all_nan::AllNan;
use vortex_array::aggregate_fn::fns::all_non_nan::AllNonNan;
use vortex_array::aggregate_fn::fns::all_non_null::AllNonNull;
use vortex_array::aggregate_fn::fns::all_null::AllNull;
use vortex_array::aggregate_fn::fns::bounded_max::BOUNDED_MAX_BOUND;
use vortex_array::aggregate_fn::fns::bounded_max::BoundedMax;
use vortex_array::arrays::BoolArray;
use vortex_array::arrays::ConstantArray;
use vortex_array::arrays::PrimitiveArray;
use vortex_array::arrays::RunEnd;
use vortex_array::arrays::StructArray;
use vortex_array::arrays::struct_::StructArrayExt;
use vortex_array::dtype::DType;
use vortex_array::dtype::Nullability;
use vortex_array::dtype::StructFields;
use vortex_array::expr::BoundExpression;
use vortex_array::scalar_fn::EmptyOptions;
use vortex_array::stats::Stat;
use vortex_array::validity::Validity;
use vortex_buffer::buffer;
use vortex_error::VortexResult;
use vortex_error::vortex_bail;
use vortex_error::vortex_ensure_eq;
use vortex_expr::ArrayExprExt;
use vortex_expr::Expression;
use vortex_expr::ScalarFnExprExt;
use vortex_expr::eq;
use vortex_expr::get_item;
use vortex_expr::lambda::row_count::RowCount;
use vortex_expr::lambda::row_count::contains_row_count;
use vortex_expr::lambda::row_count::substitute_row_count;
use vortex_expr::lit;
use vortex_expr::root;
use vortex_expr::stats::bind::StatBinder;
use vortex_expr::stats::bind::bind_stats;
use vortex_mask::Mask;
use vortex_session::VortexSession;
#[derive(Clone)]
pub struct ZoneMap {
column_dtype: DType,
array: StructArray,
aggregate_fns: Arc<[AggregateFnRef]>,
zone_len: u64,
row_count: u64,
}
impl ZoneMap {
pub fn try_new(
column_dtype: DType,
array: StructArray,
aggregate_fns: Arc<[AggregateFnRef]>,
zone_len: u64,
row_count: u64,
) -> VortexResult<Self> {
let expected_dtype = aggregate_stats_table_dtype(&column_dtype, &aggregate_fns);
if &expected_dtype != array.dtype() {
vortex_bail!("Array dtype does not match expected zone map dtype: {expected_dtype}");
}
Ok(unsafe { Self::new_unchecked(column_dtype, array, aggregate_fns, zone_len, row_count) })
}
unsafe fn new_unchecked(
column_dtype: DType,
array: StructArray,
aggregate_fns: Arc<[AggregateFnRef]>,
zone_len: u64,
row_count: u64,
) -> Self {
Self {
column_dtype,
array,
aggregate_fns,
zone_len,
row_count,
}
}
pub fn prune(
&self,
predicate: &BoundExpression,
session: &VortexSession,
) -> VortexResult<Mask> {
let predicate = self.lower_stats(predicate.clone())?;
self.prune_lowered(&predicate, session)
}
pub fn prune_lowered(
&self,
predicate: &BoundExpression,
session: &VortexSession,
) -> VortexResult<Mask> {
let mut ctx = session.create_execution_ctx();
let num_zones = self.array.len();
let array = self.array.clone().into_array();
let applied = array.apply_bound(predicate)?;
if !contains_row_count(&applied) {
return null_as_false_mask(applied, &mut ctx);
}
let row_count_array = row_count_array(self.zone_len, self.row_count, num_zones)?;
let substituted = substitute_row_count(applied, &row_count_array)?;
null_as_false_mask(substituted, &mut ctx)
}
pub fn lower_stats(&self, predicate: BoundExpression) -> VortexResult<BoundExpression> {
let binder = ZoneMapStatsBinder { zone_map: self };
bind_stats(predicate, &binder)
}
}
fn null_as_false_mask(array: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<Mask> {
if !array.dtype().is_nullable() {
return array.execute::<Mask>(ctx);
}
let len = array.len();
Ok(match array.execute::<Columnar>(ctx)? {
Columnar::Constant(c) => Mask::new(len, c.scalar().as_bool().value().unwrap_or(false)),
Columnar::Canonical(c) => {
let bool = c.into_array().execute::<BoolArray>(ctx)?;
match bool.as_ref().validity()? {
Validity::NonNullable | Validity::AllValid => {
Mask::from_buffer(bool.into_bit_buffer())
}
Validity::AllInvalid => Mask::new_false(len),
Validity::Array(v) => {
let validity_bits = v.execute::<BoolArray>(ctx)?.into_bit_buffer();
Mask::from_buffer(bool.into_bit_buffer() & &validity_bits)
}
}
}
})
}
struct ZoneMapStatsBinder<'a> {
zone_map: &'a ZoneMap,
}
impl StatBinder for ZoneMapStatsBinder<'_> {
fn bind_aggregate(
&self,
input: &BoundExpression,
aggregate_fn: &AggregateFnRef,
_stat_dtype: &DType,
) -> VortexResult<Option<BoundExpression>> {
if !input.is_root() {
return Ok(None);
}
vortex_ensure_eq!(
input.dtype(),
&self.zone_map.column_dtype,
"Stats predicate root dtype does not match zone-map column dtype"
);
if let Some(stat_expr) = self.zone_map.aggregate_field_expr(aggregate_fn) {
return Ok(Some(self.bind_target(stat_expr)?));
}
if aggregate_fn.is::<AllNull>() {
return self
.zone_map
.stat_field_expr(Stat::NullCount)
.map(|null_count| self.bind_target(eq(null_count, row_count_expr())))
.transpose();
}
if aggregate_fn.is::<AllNonNull>() {
return self
.zone_map
.stat_field_expr(Stat::NullCount)
.map(|null_count| self.bind_target(eq(null_count, lit(0u64))))
.transpose();
}
if aggregate_fn.is::<AllNan>() {
return self
.zone_map
.stat_field_expr(Stat::NaNCount)
.map(|nan_count| self.bind_target(eq(nan_count, row_count_expr())))
.transpose();
}
if aggregate_fn.is::<AllNonNan>() {
return self
.zone_map
.stat_field_expr(Stat::NaNCount)
.map(|nan_count| self.bind_target(eq(nan_count, lit(0u64))))
.transpose();
}
if let Some(stat) = Stat::from_aggregate_fn(aggregate_fn) {
return self
.zone_map
.stat_field_expr(stat)
.map(|expr| self.bind_target(expr))
.transpose();
}
Ok(None)
}
}
impl ZoneMapStatsBinder<'_> {
fn bind_target(&self, expr: Expression) -> VortexResult<BoundExpression> {
expr.bind(self.zone_map.array.dtype())
}
}
impl ZoneMap {
fn aggregate_field_expr(&self, requested: &AggregateFnRef) -> Option<Expression> {
let field_name = requested.to_string();
if self.array.unmasked_field_by_name_opt(&field_name).is_some() {
return Some(aggregate_result_expr(
requested,
get_item(field_name, root()),
));
}
let mut approximate = None;
for stored in self.aggregate_fns.iter() {
let field_name = stored.to_string();
if self.array.unmasked_field_by_name_opt(&field_name).is_none() {
continue;
}
match stored.can_satisfy(requested) {
AggregateFnSatisfaction::Exact => {
return Some(aggregate_result_expr(stored, get_item(field_name, root())));
}
AggregateFnSatisfaction::Approximate => {
approximate = Some(aggregate_result_expr(stored, get_item(field_name, root())));
}
AggregateFnSatisfaction::No => {}
}
}
approximate
}
fn stat_field_expr(&self, stat: Stat) -> Option<Expression> {
stat.aggregate_fn()
.and_then(|aggregate_fn| self.aggregate_field_expr(&aggregate_fn))
}
}
fn aggregate_result_expr(stored: &AggregateFnRef, state_expr: Expression) -> Expression {
if stored.is::<BoundedMax>() {
get_item(BOUNDED_MAX_BOUND, state_expr)
} else {
state_expr
}
}
fn row_count_expr() -> Expression {
RowCount.new_expr(EmptyOptions, [])
}
fn row_count_array(zone_len: u64, row_count: u64, num_zones: usize) -> VortexResult<ArrayRef> {
if num_zones == 0 {
return Ok(ConstantArray::new(0u64, 0).into_array());
}
let leading_rows = zone_len.saturating_mul((num_zones as u64) - 1);
let Some(last_zone_len) = row_count.checked_sub(leading_rows) else {
vortex_bail!(
"Zone map declares {num_zones} zones of {zone_len} rows, which is more than the \
{row_count} rows of the layout"
);
};
if num_zones == 1 || last_zone_len == zone_len {
return Ok(ConstantArray::new(last_zone_len, num_zones).into_array());
}
let ends = unsafe {
PrimitiveArray::new_unchecked(
buffer![num_zones as u64 - 1, num_zones as u64],
Validity::NonNullable,
)
}
.into_array();
let values = unsafe {
PrimitiveArray::new_unchecked(buffer![zone_len, last_zone_len], Validity::NonNullable)
}
.into_array();
Ok(unsafe { RunEnd::new_unchecked(ends, values, 0, num_zones) }.into_array())
}
fn aggregate_stats_table_dtype(column_dtype: &DType, aggregate_fns: &[AggregateFnRef]) -> DType {
DType::Struct(
StructFields::from_iter(aggregate_fns.iter().filter_map(|aggregate_fn| {
aggregate_state_dtype(column_dtype, aggregate_fn)
.map(|dtype| (aggregate_fn.to_string(), dtype.as_nullable()))
})),
Nullability::NonNullable,
)
}
fn aggregate_state_dtype(column_dtype: &DType, aggregate_fn: &AggregateFnRef) -> Option<DType> {
aggregate_fn.state_dtype(column_dtype).or_else(|| {
if let DType::Extension(ext) = column_dtype {
aggregate_fn.state_dtype(ext.storage_dtype())
} else {
None
}
})
}
#[cfg(test)]
mod tests;