use crate::core::AbsoluteRow;
pub(crate) use crate::core::vm::i128_from_words;
use crate::core::vm::{
AggregateValueSource, NavigationLocation, NavigationSource, NavigationValueDomain,
RegisterLayout, StateCellSource, temporal_scalar_from_bits,
};
use crate::execution::common::progress::CoarseWorkBatch;
use crate::execution::matching::program::validated_vm::{
NavigationSlotId, PreviousBufferId, RegisterId,
};
use crate::execution::matching::row_loop::row_data::resolve_optional_column;
use crate::execution::matching::row_loop::statistical_state::VarianceState;
use crate::execution::matching::row_loop::types::{
NavigationDatum, NavigationLookup, NavigationReadView,
};
use crate::execution::matching::{ResolvedInputColumn, WinningValue};
use crate::execution::storage::collection::BatchCollection;
use crate::planning::predicate::validate_decimal_scalar_value;
use datafusion::arrow::datatypes::{DataType, Schema};
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::common::{DataFusionError, Result};
use datafusion::scalar::ScalarValue;
#[inline]
pub(crate) fn register_average(sum: u64, count: u64) -> Option<f64> {
(count != 0).then(|| f64::from_bits(sum) / count as f64)
}
#[inline]
pub(crate) fn register_decimal_average(
sum: i128,
count: u64,
scale_factor: u32,
) -> Result<Option<i128>> {
if count == 0 {
return Ok(None);
}
let Some(scaled) = sum.checked_mul(i128::from(scale_factor)) else {
return datafusion::common::exec_err!(
"Decimal128 overflow while materializing VM AVG"
);
};
Ok(Some(scaled / i128::from(count)))
}
#[derive(Debug, Clone)]
pub(crate) struct BoundStateCell {
source: BoundStateSource,
output_type: DataType,
nonnull_count_slot: Option<RegisterId>,
}
impl BoundStateCell {
#[inline]
pub(crate) const fn source(&self) -> &BoundStateSource {
&self.source
}
#[inline]
pub(crate) const fn output_type(&self) -> &DataType {
&self.output_type
}
#[inline]
pub(crate) const fn nonnull_count_slot(&self) -> Option<RegisterId> {
self.nonnull_count_slot
}
#[inline]
pub(crate) fn has_no_nonnull_rows(&self, reg_slice: &[u64]) -> bool {
self.nonnull_count_slot
.is_some_and(|slot| reg_slice[slot.index()] == 0)
}
pub(crate) fn winning_value(
&self,
registers: &[u64],
output_type: &DataType,
) -> Option<WinningValue> {
use datafusion::arrow::datatypes::{Decimal128Type, DecimalType};
if self.output_type != *output_type {
return None;
}
let valid = !self.has_no_nonnull_rows(registers);
let value = match (&self.source, output_type) {
(BoundStateSource::Register { slot }, DataType::Int32) => {
WinningValue::Int32(valid.then(|| registers[slot.index()] as i32))
}
(BoundStateSource::Register { slot }, DataType::Int64) => {
WinningValue::Int64(valid.then(|| registers[slot.index()] as i64))
}
(BoundStateSource::Register { slot }, DataType::Float64) => {
WinningValue::Float64(
valid.then(|| f64::from_bits(registers[slot.index()])),
)
}
(
BoundStateSource::Avg {
sum_slot,
count_slot,
},
DataType::Float64,
) => {
let count = registers[count_slot.index()];
WinningValue::Float64(if valid {
register_average(registers[sum_slot.index()], count)
} else {
None
})
}
(BoundStateSource::RegisterD128 { slot }, DataType::Decimal128(..)) => {
WinningValue::Decimal128(valid.then(|| {
i128_from_words(registers[slot.index()], registers[slot.index() + 1])
}))
}
(
BoundStateSource::AvgDecimal128 {
sum_slot,
count_slot,
scale_factor,
},
DataType::Decimal128(..),
) => {
let count = registers[count_slot.index()];
let value = if valid {
let sum = i128_from_words(
registers[sum_slot.index()],
registers[sum_slot.index() + 1],
);
register_decimal_average(sum, count, *scale_factor).ok()?
} else {
None
};
WinningValue::Decimal128(value)
}
_ => return None,
};
match (value, output_type) {
(WinningValue::Float64(Some(v)), _) if v.is_nan() => None,
(WinningValue::Decimal128(Some(v)), DataType::Decimal128(p, s))
if Decimal128Type::validate_decimal_precision(v, *p, *s).is_err() =>
{
None
}
_ => Some(value),
}
}
#[inline]
pub(crate) const fn is_state_owned(&self) -> bool {
!matches!(self.source, BoundStateSource::AccumulatorOwned)
}
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum BoundStateRead {
Scalar(ScalarValue),
AccumulatorOwned,
CandidateStart(ResolvedInputColumn),
RetainedRow {
column: ResolvedInputColumn,
row: AbsoluteRow,
},
}
#[derive(Clone, Copy)]
pub(crate) struct CandidateInput<'a> {
collection: &'a BatchCollection,
start: AbsoluteRow,
origin: usize,
}
impl<'a> CandidateInput<'a> {
pub(crate) fn new(
collection: &'a BatchCollection,
start: AbsoluteRow,
origin: usize,
) -> Self {
Self {
collection,
start,
origin,
}
}
pub(crate) fn batch_row_at(
self,
target: AbsoluteRow,
) -> Result<(&'a RecordBatch, usize)> {
let row = usize::try_from(target.as_u64())
.ok()
.and_then(|row| row.checked_sub(self.origin))
.filter(|&row| row < self.collection.num_rows())
.ok_or_else(|| {
DataFusionError::Internal(
"MATCH_RECOGNIZE retained candidate row is outside retained input"
.into(),
)
})?;
let (batch, row) = self.collection.locate(row);
Ok((self.collection.batch(batch), row))
}
pub(crate) fn batch_row(self) -> Result<(&'a RecordBatch, usize)> {
self.batch_row_at(self.start)
}
pub(crate) fn scalar_at(
self,
column: ResolvedInputColumn,
target: AbsoluteRow,
) -> Result<ScalarValue> {
let (batch, row) = self.batch_row_at(target)?;
ScalarValue::try_from_array(batch.column(column.index()), row)
}
pub(crate) fn scalar(self, column: ResolvedInputColumn) -> Result<ScalarValue> {
self.scalar_at(column, self.start)
}
}
pub(crate) fn bind_state_cells(
schema: &Schema,
register_layout: &RegisterLayout,
aggregate_data_types: &[DataType],
) -> Result<Vec<BoundStateCell>> {
let aggregate_count = aggregate_data_types.len();
if register_layout.aggregates().len() != aggregate_count {
return Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE VM scratch metadata is not aligned: aggregates={aggregate_count}, layouts={}",
register_layout.aggregates().len()
)));
}
aggregate_data_types
.iter()
.zip(register_layout.aggregates())
.enumerate()
.map(|(agg_idx, (data_type, aggregate))| {
Ok(BoundStateCell {
source: BoundStateSource::try_bind(
&aggregate.value_source,
data_type,
schema,
register_layout,
agg_idx,
)?,
output_type: data_type.clone(),
nonnull_count_slot: aggregate
.nonnull_count_slot
.map(RegisterId::from_validated),
})
})
.collect()
}
pub(crate) fn hydrate_fallback_aggregates(
state_cells: &[BoundStateCell],
registers: &[u64],
nav_state: NavigationReadView<'_>,
candidate_input: Option<CandidateInput<'_>>,
symbol_names: &[Option<String>],
scratch_scalars: &mut Vec<ScalarValue>,
completed: &mut impl FnMut(usize) -> Result<()>,
) -> Result<()> {
let candidate = || {
candidate_input.ok_or_else(|| {
datafusion::common::internal_datafusion_err!(
"MATCH_RECOGNIZE retained candidate projection has no input binding"
)
})
};
let mut work = CoarseWorkBatch::new(completed);
let result = (|| {
for (index, cell) in state_cells.iter().enumerate() {
let decoded = (|| {
let value = cell.read(registers, nav_state, symbol_names)?;
let scalar = match value {
BoundStateRead::Scalar(scalar) => scalar,
BoundStateRead::CandidateStart(column) => {
candidate()?.scalar(column)?
}
BoundStateRead::RetainedRow { column, row } => {
candidate()?.scalar_at(column, row)?
}
BoundStateRead::AccumulatorOwned => {
return datafusion::common::internal_err!(
"MATCH_RECOGNIZE physical scratch hydration requires VM-owned cells"
);
}
};
if scalar.data_type() == *cell.output_type() {
Ok(scalar)
} else {
scalar.cast_to(cell.output_type())
}
})();
let accounting = work.complete_one();
let scalar = decoded?;
accounting?;
if index == scratch_scalars.len() {
scratch_scalars.push(scalar);
} else {
scratch_scalars[index] = scalar;
}
}
scratch_scalars.truncate(state_cells.len());
Ok(())
})();
work.finish_result(result)
}
pub(crate) type BoundStateSource =
StateCellSource<ResolvedInputColumn, RegisterId, BoundNavigation>;
pub(crate) type BoundNavigation = NavigationSource<NavigationLookup>;
impl BoundNavigation {
#[inline]
pub(crate) fn lookup(&self) -> NavigationLookup {
self.location
}
}
impl BoundStateSource {
pub(super) fn try_bind(
source: &AggregateValueSource,
output_type: &DataType,
schema: &Schema,
register_layout: &RegisterLayout,
aggregate_idx: usize,
) -> Result<Self> {
let register = |slot, width, label| {
RegisterId::try_bind(slot, width, register_layout.num_slots(), label)
.map_err(|err| invalid_source(aggregate_idx, err.to_string()))
};
let column = |name: &str| {
let column = resolve_optional_column(schema, name).ok_or_else(|| {
invalid_source(
aggregate_idx,
format!("source column {name:?} is missing from the input schema"),
)
})?;
require_exact_output_type(
source,
output_type,
schema.field(column.index()).data_type(),
aggregate_idx,
)?;
Ok::<_, DataFusionError>(column)
};
let mut bound = match source {
AggregateValueSource::CandidateStart { column: name } => {
Self::CandidateStart {
column: column(name)?,
}
}
AggregateValueSource::RetainedRow { slot, column: name } => {
Self::RetainedRow {
slot: register(*slot, 1, "retained-row register source")?,
column: column(name)?,
}
}
AggregateValueSource::Register { slot } => Self::Register {
slot: register(*slot, 1, "register source")?,
},
AggregateValueSource::Avg {
sum_slot,
count_slot,
} => Self::Avg {
sum_slot: register(*sum_slot, 1, "AVG sum register")?,
count_slot: register(*count_slot, 1, "AVG count register")?,
},
AggregateValueSource::AvgDecimal128 {
sum_slot,
count_slot,
scale_factor,
} => Self::AvgDecimal128 {
sum_slot: register(*sum_slot, 2, "Decimal128 AVG sum register")?,
count_slot: register(*count_slot, 1, "Decimal128 AVG count register")?,
scale_factor: *scale_factor,
},
AggregateValueSource::Variance {
state_slot,
projection,
} => Self::Variance {
state_slot: register(*state_slot, 3, "variance state")?,
projection: *projection,
},
AggregateValueSource::RegisterD128 { slot } => Self::RegisterD128 {
slot: register(*slot, 2, "Decimal128 register source")?,
},
AggregateValueSource::AccumulatorOwned => Self::AccumulatorOwned,
AggregateValueSource::Navigation(_) => {
let input = source
.navigation_input(register_layout)
.map_err(|message| invalid_source(aggregate_idx, message))?
.ok_or_else(|| {
invalid_source(
aggregate_idx,
format!("unsupported source {source:?}"),
)
})?;
let layout = register_layout
.navigation_layout()
.expect("resolved navigation input requires a layout");
match input.domain {
NavigationValueDomain::Classifier => require_exact_output_type(
source,
output_type,
&DataType::Utf8,
aggregate_idx,
)?,
_ => {
column(input.column_name)?;
}
}
let slot = |index| {
NavigationSlotId::try_bind(
index,
input.domain.storage_width(),
layout.num_nav_slots,
"navigation slot",
)
.map(|slot| slot.index())
};
let location = match input.location {
NavigationLocation::First(index) => NavigationLookup::First {
nav_slot: slot(index)?,
},
NavigationLocation::Last(index) => NavigationLookup::Last {
nav_slot: slot(index)?,
},
NavigationLocation::Prev(index) => NavigationLookup::Prev {
nav_slot: slot(index)?,
},
NavigationLocation::PrevBuffer { index, depth } => {
NavigationLookup::PrevBuffer {
buffer_idx: PreviousBufferId::try_bind(
index,
input.domain.storage_width(),
layout.num_prev_buffers,
"PREV buffer",
)?
.index(),
offset: depth + 1,
}
}
};
Self::Navigation(BoundNavigation {
location,
domain: input.domain,
default_value: input.default_value.cloned(),
})
}
};
validate_decimal_output_envelope(output_type).map_err(|err| {
invalid_source(
aggregate_idx,
format!("invalid decimal output type {output_type}: {err}"),
)
})?;
bind_navigation_default(&mut bound, source, output_type, aggregate_idx)?;
Ok(bound)
}
#[inline]
pub(crate) const fn is_register_state_local(&self) -> bool {
matches!(
self,
Self::Register { .. }
| Self::Avg { .. }
| Self::AvgDecimal128 { .. }
| Self::Variance { .. }
| Self::RegisterD128 { .. }
)
}
}
fn bind_navigation_default(
bound: &mut BoundStateSource,
source: &AggregateValueSource,
output_type: &DataType,
aggregate_idx: usize,
) -> Result<()> {
let BoundStateSource::Navigation(navigation) = bound else {
return Ok(());
};
let Some(value) = navigation.default_value.take() else {
return Ok(());
};
if matches!(&value, ScalarValue::FixedSizeBinary(width, Some(bytes)) if usize::try_from(*width).ok() != Some(bytes.len()))
{
return Err(invalid_source(
aggregate_idx,
format!(
"source {source:?} has a fixed binary default with an invalid byte length"
),
));
}
validate_decimal_scalar_value(&value).map_err(|error| {
invalid_source(
aggregate_idx,
format!("source {source:?} has an invalid decimal default: {error}"),
)
})?;
let bound = if value.is_null() {
ScalarValue::try_from(output_type).map_err(|error| {
invalid_source(
aggregate_idx,
format!(
"source {source:?} default could not be typed as {output_type}: {error}"
),
)
})?
} else {
let source_type = value.data_type();
value.cast_to(output_type).map_err(|error| {
invalid_source(
aggregate_idx,
format!(
"source {source:?} default cannot be cast from {source_type} to {output_type}: {error}"
),
)
})?
};
validate_decimal_scalar_value(&bound).map_err(|error| {
invalid_source(
aggregate_idx,
format!(
"source {source:?} default is invalid after binding to {output_type}: {error}"
),
)
})?;
navigation.default_value = Some(bound);
Ok(())
}
fn validate_decimal_output_envelope(
output_type: &DataType,
) -> std::result::Result<(), datafusion::arrow::error::ArrowError> {
let value = match output_type {
DataType::Decimal128(precision, scale) => {
ScalarValue::Decimal128(None, *precision, *scale)
}
DataType::Decimal256(precision, scale) => {
ScalarValue::Decimal256(None, *precision, *scale)
}
_ => return Ok(()),
};
validate_decimal_scalar_value(&value)
}
fn require_exact_output_type(
source: &AggregateValueSource,
output_type: &DataType,
expected: &DataType,
aggregate_idx: usize,
) -> Result<()> {
if output_type != expected {
return Err(invalid_source(
aggregate_idx,
format!(
"source {source:?} uses {expected} encoding, incompatible with aggregate output type {output_type}"
),
));
}
Ok(())
}
fn invalid_source(aggregate_idx: usize, reason: String) -> DataFusionError {
DataFusionError::Internal(format!(
"MATCH_RECOGNIZE VM scratch source binding failed for aggregate {aggregate_idx}: {reason}"
))
}
pub(super) fn word_to_scalar(value: u64, dt: &DataType) -> Result<ScalarValue> {
scalar_from_state_word(value, dt).ok_or_else(|| {
datafusion::common::internal_datafusion_err!(
"unsupported VM state scalar data type {dt}"
)
})
}
pub(crate) fn scalar_from_state_word(value: u64, dt: &DataType) -> Option<ScalarValue> {
match dt {
DataType::Boolean => Some(ScalarValue::Boolean(Some(value != 0))),
DataType::Int8 => Some(ScalarValue::Int8(Some(value as i8))),
DataType::Int16 => Some(ScalarValue::Int16(Some(value as i16))),
DataType::Int32 => Some(ScalarValue::Int32(Some(value as i32))),
DataType::Int64 => Some(ScalarValue::Int64(Some(value as i64))),
DataType::UInt8 => Some(ScalarValue::UInt8(Some(value as u8))),
DataType::UInt16 => Some(ScalarValue::UInt16(Some(value as u16))),
DataType::UInt32 => Some(ScalarValue::UInt32(Some(value as u32))),
DataType::UInt64 => Some(ScalarValue::UInt64(Some(value))),
DataType::Float32 => {
Some(ScalarValue::Float32(Some(f32::from_bits(value as u32))))
}
DataType::Float64 => Some(ScalarValue::Float64(Some(f64::from_bits(value)))),
_ => temporal_scalar_from_bits(value, dt),
}
}
fn decimal_scalar(value: Option<i128>, dt: &DataType) -> Result<ScalarValue> {
match dt {
DataType::Decimal128(precision, scale) => {
Ok(ScalarValue::Decimal128(value, *precision, *scale))
}
_ => datafusion::common::internal_err!(
"unsupported VM Decimal128 state data type {dt}"
),
}
}
pub(super) fn navigation_default_scalar(
default_value: Option<&ScalarValue>,
dt: &DataType,
) -> Result<ScalarValue> {
match default_value {
Some(value) if value.data_type() == *dt => Ok(value.clone()),
Some(value) => datafusion::common::internal_err!(
"bound VM navigation default has type {}, expected {dt}",
value.data_type()
),
None => ScalarValue::try_from(dt),
}
}
impl BoundNavigation {
pub(crate) fn classifier_name(
symbol_id: u64,
symbol_names: &[Option<String>],
) -> Result<&str> {
let index = usize::try_from(symbol_id).map_err(|_| {
datafusion::common::internal_datafusion_err!(
"MATCH_RECOGNIZE classifier navigation symbol ID {symbol_id} overflows usize"
)
})?;
symbol_names
.get(index)
.and_then(Option::as_deref)
.ok_or_else(|| {
datafusion::common::internal_datafusion_err!(
"MATCH_RECOGNIZE classifier navigation symbol ID {index} is out of bounds"
)
})
}
fn scalar(
&self,
state: NavigationReadView<'_>,
dt: &DataType,
symbol_names: &[Option<String>],
) -> Result<ScalarValue> {
fn decode<T>(
datum: NavigationDatum<T>,
navigation: &BoundNavigation,
dt: &DataType,
value: impl FnOnce(T) -> Result<ScalarValue>,
) -> Result<ScalarValue> {
match datum {
NavigationDatum::Missing => {
navigation_default_scalar(navigation.default_value.as_ref(), dt)
}
NavigationDatum::Null => ScalarValue::try_from(dt),
NavigationDatum::Value(bits) => value(bits),
}
}
match self.domain {
NavigationValueDomain::Primitive => {
decode(state.primitive(self.lookup()), self, dt, |word| {
word_to_scalar(word, dt)
})
}
NavigationValueDomain::Decimal128 => {
decode(state.decimal128(self.lookup()), self, dt, |words| {
decimal_scalar(Some(i128_from_words(words.0, words.1)), dt)
})
}
NavigationValueDomain::Classifier => {
decode(state.primitive(self.lookup()), self, dt, |word| {
let name = Self::classifier_name(word, symbol_names)?;
Ok(ScalarValue::Utf8(Some(name.to_string())))
})
}
}
}
}
impl BoundStateCell {
pub(crate) fn read(
&self,
registers: &[u64],
nav_state: NavigationReadView<'_>,
symbol_names: &[Option<String>],
) -> Result<BoundStateRead> {
let dt = &self.output_type;
let register = |slot: &RegisterId| registers[slot.index()];
match &self.source {
BoundStateSource::CandidateStart { column } => {
return Ok(BoundStateRead::CandidateStart(*column));
}
BoundStateSource::AccumulatorOwned => {
return Ok(BoundStateRead::AccumulatorOwned);
}
_ if self.has_no_nonnull_rows(registers) => {
return Ok(BoundStateRead::Scalar(ScalarValue::try_from(dt)?));
}
BoundStateSource::RetainedRow { slot, column } => {
return Ok(BoundStateRead::RetainedRow {
column: *column,
row: AbsoluteRow::new(register(slot)),
});
}
BoundStateSource::Register { slot } => word_to_scalar(register(slot), dt),
BoundStateSource::Navigation(read) => {
read.scalar(nav_state, dt, symbol_names)
}
BoundStateSource::Avg {
sum_slot,
count_slot,
} => Ok(ScalarValue::Float64(register_average(
register(sum_slot),
register(count_slot),
))),
BoundStateSource::AvgDecimal128 {
sum_slot,
count_slot,
scale_factor,
} => {
let slot = sum_slot.index();
decimal_scalar(
register_decimal_average(
i128_from_words(registers[slot], registers[slot + 1]),
register(count_slot),
*scale_factor,
)?,
dt,
)
}
BoundStateSource::Variance {
state_slot,
projection,
} => Ok(ScalarValue::Float64(
VarianceState::from_registers(registers, state_slot.index())
.project(*projection),
)),
BoundStateSource::RegisterD128 { slot } => {
let slot = slot.index();
decimal_scalar(
Some(i128_from_words(registers[slot], registers[slot + 1])),
dt,
)
}
}
.map(BoundStateRead::Scalar)
}
}
#[cfg(test)]
#[path = "vm_scratch_tests.rs"]
mod source_tests;