use datafusion::arrow::array::{Array, ArrayRef, AsArray};
use datafusion::arrow::buffer::{BooleanBuffer, NullBuffer, ScalarBuffer};
use datafusion::arrow::datatypes::*;
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::common::Result;
use datafusion::execution::memory_pool::MemoryReservation;
use crate::execution::common::memory::reserved_vec;
#[cold]
#[inline(never)]
fn decode_decimal128_to_f64_bits_slow(raw: i128, scale: i8) -> u64 {
Decimal128Type::format_decimal(raw, u8::MAX, scale)
.parse::<f64>()
.unwrap_or_else(|_| (raw as f64) / 10_f64.powi(i32::from(scale)))
.to_bits()
}
#[inline]
pub(crate) fn decode_decimal128_to_f64_bits(raw: i128, scale: i8) -> u64 {
if raw.unsigned_abs() <= (1_u128 << 53) && (0..=22).contains(&scale) {
((raw as f64) / 10_f64.powi(i32::from(scale))).to_bits()
} else {
decode_decimal128_to_f64_bits_slow(raw, scale)
}
}
pub(crate) fn unbound_word(array: &ArrayRef, row: usize, force_float: bool) -> u64 {
if array.is_null(row) {
return 0;
}
assert!(
!force_float || !crate::core::vm::is_temporal_word_type(array.data_type()),
"temporal values require a native signed-word binding"
);
Column::bind(array)
.word(row, force_float)
.unwrap_or_else(|| {
unreachable!(
"unsupported {} reached a validated VM row binding",
array.data_type()
)
})
}
#[derive(Debug)]
enum Values {
I8(ScalarBuffer<i8>),
I16(ScalarBuffer<i16>),
I32(ScalarBuffer<i32>),
I64(ScalarBuffer<i64>),
U8(ScalarBuffer<u8>),
U16(ScalarBuffer<u16>),
U32(ScalarBuffer<u32>),
U64(ScalarBuffer<u64>),
F32(ScalarBuffer<f32>),
F64(ScalarBuffer<f64>),
Decimal(ScalarBuffer<i128>, i8),
Boolean(BooleanBuffer),
Generic,
}
#[derive(Debug)]
struct Column {
values: Values,
nulls: Validity,
}
#[derive(Debug)]
enum Validity {
Bitmap(Option<NullBuffer>),
Encoded(ArrayRef),
}
impl Column {
fn bind(array: &ArrayRef) -> Self {
macro_rules! primitive {
($variant:ident, $ty:ty) => {
Values::$variant(array.as_primitive::<$ty>().values().clone())
};
}
let values = match array.data_type() {
DataType::Int8 => primitive!(I8, Int8Type),
DataType::Int16 => primitive!(I16, Int16Type),
DataType::Int32 => primitive!(I32, Int32Type),
DataType::Int64 => primitive!(I64, Int64Type),
DataType::UInt8 => primitive!(U8, UInt8Type),
DataType::UInt16 => primitive!(U16, UInt16Type),
DataType::UInt32 => primitive!(U32, UInt32Type),
DataType::UInt64 => primitive!(U64, UInt64Type),
DataType::Float32 => primitive!(F32, Float32Type),
DataType::Float64 => primitive!(F64, Float64Type),
DataType::Decimal128(_, scale) => Values::Decimal(
array.as_primitive::<Decimal128Type>().values().clone(),
*scale,
),
DataType::Boolean => Values::Boolean(array.as_boolean().values().clone()),
DataType::Date32 => primitive!(I32, Date32Type),
DataType::Date64 => primitive!(I64, Date64Type),
DataType::Time32(TimeUnit::Second) => primitive!(I32, Time32SecondType),
DataType::Time32(TimeUnit::Millisecond) => {
primitive!(I32, Time32MillisecondType)
}
DataType::Time64(TimeUnit::Microsecond) => {
primitive!(I64, Time64MicrosecondType)
}
DataType::Time64(TimeUnit::Nanosecond) => {
primitive!(I64, Time64NanosecondType)
}
DataType::Timestamp(TimeUnit::Second, _) => {
primitive!(I64, TimestampSecondType)
}
DataType::Timestamp(TimeUnit::Millisecond, _) => {
primitive!(I64, TimestampMillisecondType)
}
DataType::Timestamp(TimeUnit::Microsecond, _) => {
primitive!(I64, TimestampMicrosecondType)
}
DataType::Timestamp(TimeUnit::Nanosecond, _) => {
primitive!(I64, TimestampNanosecondType)
}
DataType::Duration(TimeUnit::Second) => primitive!(I64, DurationSecondType),
DataType::Duration(TimeUnit::Millisecond) => {
primitive!(I64, DurationMillisecondType)
}
DataType::Duration(TimeUnit::Microsecond) => {
primitive!(I64, DurationMicrosecondType)
}
DataType::Duration(TimeUnit::Nanosecond) => {
primitive!(I64, DurationNanosecondType)
}
_ => Values::Generic,
};
let nulls = match array.data_type() {
DataType::Null
| DataType::Dictionary(..)
| DataType::RunEndEncoded(..)
| DataType::Union(..) => Validity::Encoded(array.clone()),
_ => Validity::Bitmap(array.nulls().cloned()),
};
Self { values, nulls }
}
#[inline]
fn is_null(&self, local: usize) -> bool {
match &self.nulls {
Validity::Bitmap(nulls) => nulls.as_ref().is_some_and(|v| v.is_null(local)),
Validity::Encoded(array) => {
crate::execution::common::nulls::is_logically_null(array.as_ref(), local)
}
}
}
#[inline]
fn word(&self, local: usize, force_float: bool) -> Option<u64> {
macro_rules! integer {
($values:expr) => {{
let value = $values[local];
if force_float {
(value as f64).to_bits()
} else {
value as u64
}
}};
}
Some(match &self.values {
Values::I8(v) => integer!(v),
Values::I16(v) => integer!(v),
Values::I32(v) => integer!(v),
Values::I64(v) => integer!(v),
Values::U8(v) => integer!(v),
Values::U16(v) => integer!(v),
Values::U32(v) => integer!(v),
Values::U64(v) => integer!(v),
Values::F32(v) if force_float => f64::from(v[local]).to_bits(),
Values::F32(v) => u64::from(v[local].to_bits()),
Values::F64(v) => v[local].to_bits(),
Values::Boolean(v) if force_float => {
f64::from(u8::from(v.value(local))).to_bits()
}
Values::Boolean(v) => u64::from(v.value(local)),
Values::Decimal(v, scale) => decode_decimal128_to_f64_bits(v[local], *scale),
Values::Generic => return None,
})
}
#[inline]
fn decimal(&self, local: usize) -> Option<i128> {
match &self.values {
Values::Decimal(v, _) => Some(v[local]),
_ => None,
}
}
}
#[derive(Debug)]
pub(crate) struct BoundBatchColumns {
slots: Vec<Option<Column>>,
rows: usize,
has_any_nulls: bool,
}
impl BoundBatchColumns {
pub(super) fn new(
width: usize,
rows: usize,
memory: &MemoryReservation,
) -> Result<Self> {
let slots = reserved_vec(width, memory, "bound input columns")?;
Ok(Self {
slots,
rows,
has_any_nulls: false,
})
}
pub(super) fn bind_chunk(
&mut self,
batch: &RecordBatch,
selected: &[usize],
width: usize,
) -> usize {
use crate::execution::common::progress::COARSE_WORK_BATCH_SIZE;
let start = self.slots.len();
let end = start.saturating_add(COARSE_WORK_BATCH_SIZE).min(width);
let mut next = selected.partition_point(|&column| column < start);
for column in start..end {
self.slots.push(if selected.get(next) == Some(&column) {
next += 1;
let bound = Column::bind(batch.column(column));
self.has_any_nulls |= match &bound.nulls {
Validity::Encoded(_) => true,
Validity::Bitmap(nulls) => {
nulls.as_ref().is_some_and(|n| n.null_count() != 0)
}
};
Some(bound)
} else {
None
});
}
end - start
}
pub(crate) fn all_bound_non_null(&self) -> bool {
!self.has_any_nulls
}
pub(super) fn width(&self) -> usize {
self.slots.len()
}
#[inline]
pub(crate) fn row(&self, local: usize) -> Option<BoundBatchRow<'_>> {
(local < self.rows).then_some(BoundBatchRow {
columns: self,
local,
})
}
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct BoundBatchRow<'a> {
columns: &'a BoundBatchColumns,
local: usize,
}
impl BoundBatchRow<'_> {
#[inline]
fn column(&self, slot: usize) -> Option<&Column> {
self.columns.slots.get(slot)?.as_ref()
}
#[inline]
pub(crate) fn is_null(&self, slot: usize) -> Option<bool> {
Some(self.column(slot)?.is_null(self.local))
}
#[inline]
pub(crate) fn word(&self, slot: usize, force_float: bool) -> Option<u64> {
self.column(slot)?.word(self.local, force_float)
}
#[inline]
pub(crate) fn decimal(&self, slot: usize) -> Option<i128> {
self.column(slot)?.decimal(self.local)
}
#[inline]
fn read_checked<T>(
&self,
slot: usize,
value: impl FnOnce(&Column) -> Option<T>,
) -> Option<Option<T>> {
let column = self.column(slot)?;
if column.is_null(self.local) {
Some(None)
} else {
value(column).map(Some)
}
}
#[inline]
pub(crate) fn read_word_checked(
&self,
slot: usize,
force_float: bool,
) -> Option<Option<u64>> {
self.read_checked(slot, |c| c.word(self.local, force_float))
}
#[inline]
pub(crate) fn read_decimal_checked(&self, slot: usize) -> Option<Option<i128>> {
self.read_checked(slot, |c| c.decimal(self.local))
}
#[inline]
pub(crate) fn read_word_non_null(
&self,
slot: usize,
force_float: bool,
) -> Option<u64> {
debug_assert!(self.columns.all_bound_non_null());
self.word(slot, force_float)
}
#[inline]
pub(crate) fn read_decimal_non_null(&self, slot: usize) -> Option<i128> {
debug_assert!(self.columns.all_bound_non_null());
self.decimal(slot)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::execution::common::memory::new_unbounded_state_memory;
use datafusion::arrow::array::{
BooleanArray, Date32Array, Decimal128Array, DictionaryArray, Float32Array,
Float64Array, Int8Array, Int16Array, Int32Array, Int64Array, StringArray,
TimestampNanosecondArray, UInt8Array, UInt16Array, UInt32Array, UInt64Array,
};
use std::sync::Arc;
#[test]
fn typed_words_exact_decimals_and_logical_validity_follow_sliced_arrays() -> Result<()>
{
let nan = f32::from_bits(0x7fc0_0009);
let exact = (1_i128 << 102) + 11;
macro_rules! values {
($array:ty, $value:expr) => {
Arc::new(<$array>::from(vec![None, Some($value), None])) as ArrayRef
};
}
let columns = vec![
values!(Int8Array, i8::MIN),
values!(Int16Array, i16::MIN),
values!(Int32Array, i32::MIN),
values!(Int64Array, i64::MIN),
values!(UInt8Array, u8::MAX),
values!(UInt16Array, u16::MAX),
values!(UInt32Array, u32::MAX),
values!(UInt64Array, u64::MAX),
values!(Float32Array, nan),
values!(Float64Array, -0.0),
values!(BooleanArray, true),
values!(Date32Array, -123),
values!(TimestampNanosecondArray, -1234),
Arc::new(
Decimal128Array::from(vec![None, Some(exact), None])
.with_precision_and_scale(38, -2)?,
),
Arc::new(DictionaryArray::<Int8Type>::try_new(
Int8Array::from(vec![None, Some(0), Some(1)]),
Arc::new(StringArray::from(vec![Some("ok"), None])),
)?),
]
.into_iter()
.map(|a| a.slice(1, 2))
.collect::<Vec<_>>();
let schema = Arc::new(Schema::new(
columns
.iter()
.enumerate()
.map(|(i, a)| Field::new(i.to_string(), a.data_type().clone(), true))
.collect::<Vec<_>>(),
));
let batch = RecordBatch::try_new(schema, columns)?;
let slots = (0..batch.num_columns()).collect::<Vec<_>>();
let memory = new_unbounded_state_memory();
let mut bound =
BoundBatchColumns::new(batch.num_columns(), batch.num_rows(), &memory)?;
assert_eq!(
bound.bind_chunk(&batch, &slots, batch.num_columns()),
slots.len()
);
let row = bound.row(0).unwrap();
let null = bound.row(1).unwrap();
assert!(!bound.all_bound_non_null());
for &slot in &slots {
assert_eq!(row.is_null(slot), Some(false));
assert_eq!(null.is_null(slot), Some(true));
assert_eq!(null.read_word_checked(slot, false), Some(None));
}
let valid = batch.slice(0, 1);
assert_eq!(valid.column(0).nulls().unwrap().null_count(), 0);
let mut native = BoundBatchColumns::new(slots.len(), 1, &memory)?;
let dict = slots.len() - 1;
native.bind_chunk(&valid, &slots[..dict], slots.len());
assert!(native.all_bound_non_null());
let no_nulls = native.row(0).unwrap();
let mut encoded = BoundBatchColumns::new(slots.len(), 1, &memory)?;
encoded.bind_chunk(&valid, &slots[dict..], slots.len());
assert!(!encoded.all_bound_non_null());
for (slot, expected) in [
i8::MIN as u64,
i16::MIN as u64,
i32::MIN as u64,
i64::MIN as u64,
u64::from(u8::MAX),
u64::from(u16::MAX),
u64::from(u32::MAX),
u64::MAX,
u64::from(nan.to_bits()),
(-0.0_f64).to_bits(),
1,
(-123_i64) as u64,
(-1234_i64) as u64,
]
.into_iter()
.enumerate()
{
assert_eq!(no_nulls.read_word_non_null(slot, false), Some(expected));
assert_eq!(row.read_word_checked(slot, false), Some(Some(expected)));
assert_eq!(
no_nulls.read_word_non_null(slot, true),
row.word(slot, true)
);
}
assert_eq!(row.word(7, true), Some((u64::MAX as f64).to_bits()));
assert_eq!(row.word(8, true), Some(f64::from(nan).to_bits()));
assert_eq!(row.word(10, true), Some(1.0_f64.to_bits()));
assert_eq!(
row.word(13, true),
Some(decode_decimal128_to_f64_bits(exact, -2))
);
assert_eq!(no_nulls.read_decimal_non_null(13), Some(exact));
assert_eq!(row.read_decimal_checked(13), Some(Some(exact)));
assert_eq!(null.read_decimal_checked(13), Some(None));
assert_eq!(row.read_word_checked(dict, false), None);
assert_eq!(no_nulls.read_word_non_null(dict, false), None);
assert_eq!(row.read_word_checked(slots.len(), false), None);
assert!(bound.row(2).is_none());
Ok(())
}
#[test]
fn nullable_count_binds_two_giant_runs_under_a_small_pool() -> Result<()> {
use crate::execution::storage::collection::BatchCollection;
use datafusion::arrow::array::RunArray;
use datafusion::execution::memory_pool::{
GreedyMemoryPool, MemoryConsumer, MemoryPool,
};
let boundary = 1_000_000_000;
let run_ends = Int32Array::from(vec![boundary, 2 * boundary]);
let values = Int32Array::from(vec![Some(5), None]);
let runs = RunArray::<Int32Type>::try_new(&run_ends, &values)?;
let runs: ArrayRef =
Arc::new(runs.slice(boundary as usize - 1, boundary as usize));
let schema = Arc::new(Schema::new(vec![Field::new(
"r",
runs.data_type().clone(),
true,
)]));
let batch = RecordBatch::try_new(schema.clone(), vec![runs])?;
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(4096));
let memory = MemoryConsumer::new("bound-runs").register(&pool);
let mut head = BatchCollection::try_new(vec![batch], schema)?;
assert!(head.bind_input_chunk(0, &[0], &memory, &mut |_| Ok(()))?);
assert!(!head.bound_batch(0).unwrap().all_bound_non_null());
assert_eq!(
head.bound_row(0, 1).unwrap().read_word_checked(0, false),
Some(None)
);
assert_eq!(head.bound_row(0, 0).unwrap().is_null(0), Some(false));
assert_eq!(head.bound_row(0, 1).unwrap().is_null(0), Some(true));
assert_eq!(
head.bound_row(0, boundary as usize - 1).unwrap().is_null(0),
Some(true)
);
drop(head);
drop(memory);
assert_eq!(pool.reserved(), 0);
Ok(())
}
#[test]
fn sparse_wide_binding_charges_one_quantum_per_step() -> Result<()> {
use crate::execution::common::progress::COARSE_WORK_BATCH_SIZE;
use crate::execution::storage::collection::BatchCollection;
let width = COARSE_WORK_BATCH_SIZE * 3 + 2;
let schema = Arc::new(Schema::new(
(0..width)
.map(|i| Field::new(i.to_string(), DataType::Int32, true))
.collect::<Vec<_>>(),
));
let col: ArrayRef = Arc::new(Int32Array::from(vec![42]));
let batch = RecordBatch::try_new(schema.clone(), vec![col; width])?;
let mut head = BatchCollection::try_new(vec![batch], schema)?;
let memory = new_unbounded_state_memory();
let mut steps = vec![];
while !head.bind_input_chunk(
0,
&[0, width - 1, width + 2],
&memory,
&mut |work| {
steps.push(work);
Ok(())
},
)? {}
assert_eq!(
steps,
[
COARSE_WORK_BATCH_SIZE,
COARSE_WORK_BATCH_SIZE,
COARSE_WORK_BATCH_SIZE,
2
]
);
let row = head.bound_row(0, 0).unwrap();
assert_eq!(row.word(0, false), Some(42));
assert_eq!(row.word(1, false), None);
assert_eq!(row.word(width - 1, false), Some(42));
assert_eq!(row.word(width + 2, false), None);
Ok(())
}
}