use datafusion_common::ScalarValue;
use std::fmt;
mod register_layout;
mod words;
pub use register_layout::{AggregateLayout, RegisterLayout};
pub(crate) use words::i128_from_words;
pub use words::{
compare_i128, is_temporal_word_type, temporal_scalar_from_bits,
temporal_scalar_to_bits, wrapping_add_i128_to_registers,
};
pub const MAX_INLINE_REGISTERS: usize = 16;
pub const MAX_REGISTERS: usize = 64;
pub const MAX_VM_ROW_VALUES: usize = MAX_REGISTERS;
pub const MAX_VM_NAV_VALUES: usize = MAX_NAV_SLOTS + MAX_PREV_BUFFERS;
pub const MAX_VM_NAV_D128_VALUES: usize = MAX_NAV_SLOTS / 2 + MAX_PREV_BUFFERS / 2;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum VmTier {
Compact,
#[default]
Standard,
}
impl fmt::Display for VmTier {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
VmTier::Compact => "Compact",
VmTier::Standard => "Standard",
})
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum SlotValueType {
#[default]
Int64,
UInt64,
Float32,
Float64,
Decimal128,
RetainedRow,
}
impl SlotValueType {
#[inline]
pub fn slot_count(&self) -> usize {
match self {
Self::Int64
| Self::UInt64
| Self::Float32
| Self::Float64
| Self::RetainedRow => 1,
Self::Decimal128 => 2,
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum AggregateKind {
#[default]
Additive,
Min,
Max,
Avg,
Variance,
BoolAnd,
BoolOr,
}
impl AggregateKind {
pub(super) fn state_width(self, value_type: SlotValueType) -> usize {
match self {
Self::Avg => value_type.slot_count() + 1,
Self::Variance => 3,
_ => value_type.slot_count(),
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct SlotInfo {
pub start_slot: usize,
pub slot_count: usize,
pub value_type: SlotValueType,
pub scale: i8,
pub agg_kind: AggregateKind,
}
impl SlotInfo {
#[cfg(test)]
#[inline]
pub fn new(start_slot: usize, value_type: SlotValueType, scale: i8) -> Self {
Self::with_kind(start_slot, value_type, scale, AggregateKind::Additive)
}
#[inline]
pub fn with_kind(
start_slot: usize,
value_type: SlotValueType,
scale: i8,
agg_kind: AggregateKind,
) -> Self {
Self {
start_slot,
slot_count: agg_kind.state_width(value_type),
value_type,
scale,
agg_kind,
}
}
#[inline]
pub fn count_slot(&self) -> Option<usize> {
match self.agg_kind {
AggregateKind::Avg | AggregateKind::Variance => {
Some(self.start_slot + (self.agg_kind.state_width(self.value_type) - 1))
}
_ => None,
}
}
#[cfg(test)]
#[inline]
pub fn int64(start_slot: usize) -> Self {
Self::new(start_slot, SlotValueType::Int64, 0)
}
#[cfg(test)]
#[inline]
pub fn decimal128(start_slot: usize, scale: i8) -> Self {
Self::new(start_slot, SlotValueType::Decimal128, scale)
}
}
pub const MAX_PREV_DEPTH: usize = 31;
pub const MAX_FIRST_OFFSET: usize = u8::MAX as usize;
pub const MAX_NAV_SLOTS: usize = 16;
pub const MAX_PREV_BUFFERS: usize = 16;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NavigationValueDomain {
Primitive,
Decimal128,
Classifier,
}
impl NavigationValueDomain {
pub const fn storage_width(self) -> usize {
match self {
Self::Primitive | Self::Classifier => 1,
Self::Decimal128 => 2,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct NavSlotInfo {
pub symbol_idx: Option<usize>,
pub nav_slot: usize,
pub value_idx: usize,
pub domain: NavigationValueDomain,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PrevBufferInfo {
pub symbol_idx: Option<usize>,
pub depth: usize,
pub buffer_idx: usize,
pub value_idx: usize,
pub domain: NavigationValueDomain,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
pub struct NavigationLayout {
pub num_nav_slots: usize,
pub num_prev_buffers: usize,
pub first_slots: Vec<NavSlotInfo>,
pub first_offsets: Vec<usize>,
pub last_slots: Vec<NavSlotInfo>,
pub prev_slots: Vec<NavSlotInfo>,
pub prev_buffer_slots: Vec<PrevBufferInfo>,
}
impl NavigationLayout {
#[inline]
pub fn first_slot_offset(&self, index: usize) -> usize {
self.first_offsets.get(index).copied().unwrap_or(0)
}
pub fn has_navigation(&self) -> bool {
self.num_nav_slots > 0 || self.num_prev_buffers > 0
}
pub fn has_classifier_navigation(&self) -> bool {
self.first_slots
.iter()
.chain(&self.last_slots)
.chain(&self.prev_slots)
.any(|slot| slot.domain == NavigationValueDomain::Classifier)
|| self
.prev_buffer_slots
.iter()
.any(|buffer| buffer.domain == NavigationValueDomain::Classifier)
}
pub fn vm_tier(&self) -> VmTier {
if self.has_navigation() {
VmTier::Standard
} else {
VmTier::Compact
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum StatisticalPopulation {
Sample,
Population,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum VarianceProjection {
Variance(StatisticalPopulation),
Stddev(StatisticalPopulation),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum StateCellSource<Column, Register, Navigation> {
CandidateStart { column: Column },
Register { slot: Register },
Navigation(Navigation),
Avg {
sum_slot: Register,
count_slot: Register,
},
AvgDecimal128 {
sum_slot: Register,
count_slot: Register,
scale_factor: u32,
},
Variance {
state_slot: Register,
projection: VarianceProjection,
},
RegisterD128 { slot: Register },
RetainedRow { slot: Register, column: Column },
AccumulatorOwned,
}
pub type AggregateValueSource =
StateCellSource<String, usize, NavigationSource<NavigationLocation>>;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct NavigationSource<Location> {
pub location: Location,
pub domain: NavigationValueDomain,
pub default_value: Option<ScalarValue>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NavigationLocation {
First(usize),
Last(usize),
Prev(usize),
PrevBuffer { index: usize, depth: usize },
}
#[derive(Debug, Clone, Copy)]
pub struct NavigationInput<'a> {
pub location: NavigationLocation,
pub domain: NavigationValueDomain,
pub column_name: &'a str,
pub default_value: Option<&'a ScalarValue>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RegisterWriter {
Count {
aggregate: usize,
input: Option<usize>,
},
Accumulate {
aggregate: usize,
input: usize,
nullable: bool,
},
}
impl RegisterWriter {
pub const fn aggregate(&self) -> usize {
match *self {
Self::Count { aggregate, .. } | Self::Accumulate { aggregate, .. } => {
aggregate
}
}
}
pub const fn null_input(&self) -> Option<usize> {
match *self {
Self::Count { input, .. } => input,
Self::Accumulate {
input,
nullable: true,
..
} => Some(input),
Self::Accumulate { .. } => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NavigationKind {
First,
Last,
Prev,
PrevBuffer,
}
impl NavigationKind {
pub(super) const fn label(self) -> &'static str {
match self {
Self::First => "FIRST",
Self::Last => "LAST",
Self::Prev => "PREV",
Self::PrevBuffer => "PREV buffer",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NavigationUpdate {
pub kind: NavigationKind,
pub storage_idx: u8,
pub value_idx: u8,
pub domain: NavigationValueDomain,
pub first_offset: u8,
}
const _: () = {
assert!(MAX_NAV_SLOTS <= 256 && MAX_PREV_BUFFERS <= 256);
assert!(MAX_VM_NAV_VALUES <= 256 && MAX_VM_NAV_D128_VALUES <= 256);
assert!(MAX_FIRST_OFFSET <= u8::MAX as usize);
};
impl fmt::Display for NavigationUpdate {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let operation = match self.kind {
NavigationKind::First => "StoreFirst",
NavigationKind::Last => "StoreLast",
NavigationKind::Prev => "UpdatePrevLast",
NavigationKind::PrevBuffer => "PushPrevBuffer",
};
let suffix = if self.kind == NavigationKind::First && self.first_offset > 0 {
format!("(+{})", self.first_offset)
} else {
String::new()
};
match self.domain {
NavigationValueDomain::Primitive => {
write!(
f,
"{operation}{suffix} {} <- value[{}]",
self.storage_idx, self.value_idx
)
}
NavigationValueDomain::Decimal128 => {
write!(
f,
"{operation}D128{suffix} {} <- decimal[{}]",
self.storage_idx, self.value_idx
)
}
NavigationValueDomain::Classifier => {
write!(
f,
"{operation}Classifier{suffix} {} <- symbol",
self.storage_idx
)
}
}
}
}
impl RegisterLayout {
pub fn validate_symbol_count(&self, symbols_len: usize) -> Result<(), String> {
let Some(layout) = self.navigation_layout() else {
return Ok(());
};
for (kind, symbol_idx, storage_idx) in
layout
.first_slots
.iter()
.map(|info| (NavigationKind::First, info.symbol_idx, info.nav_slot))
.chain(
layout.last_slots.iter().map(|info| {
(NavigationKind::Last, info.symbol_idx, info.nav_slot)
}),
)
.chain(
layout.prev_slots.iter().map(|info| {
(NavigationKind::Prev, info.symbol_idx, info.nav_slot)
}),
)
.chain(layout.prev_buffer_slots.iter().map(|info| {
(NavigationKind::PrevBuffer, info.symbol_idx, info.buffer_idx)
}))
{
if symbol_idx.is_some_and(|idx| idx >= symbols_len) {
return Err(format!(
"navigation {} layout symbol index out of bounds (idx={}, symbols={symbols_len}, storage={storage_idx})",
kind.label(),
symbol_idx.unwrap_or_default()
));
}
}
Ok(())
}
pub fn navigation_writers(&self, symbol_idx: usize) -> Vec<NavigationUpdate> {
let Some(layout) = self.navigation_layout() else {
return Vec::new();
};
let applies = |scope: Option<usize>| scope.is_none_or(|idx| idx == symbol_idx);
let slot_artifact =
|kind, info: &NavSlotInfo, first_offset: u8| NavigationUpdate {
kind,
storage_idx: info.nav_slot as u8,
value_idx: info.value_idx as u8,
domain: info.domain,
first_offset,
};
let mut expected = layout
.first_slots
.iter()
.enumerate()
.filter(|(_, info)| applies(info.symbol_idx))
.map(|(idx, info)| {
slot_artifact(
NavigationKind::First,
info,
layout.first_slot_offset(idx) as u8,
)
})
.collect::<Vec<_>>();
expected.extend(
layout
.last_slots
.iter()
.filter(|info| {
applies(info.symbol_idx)
&& !layout.prev_slots.iter().any(|prev| prev == *info)
})
.map(|info| slot_artifact(NavigationKind::Last, info, 0)),
);
expected.extend(
layout
.prev_slots
.iter()
.filter(|info| applies(info.symbol_idx))
.map(|info| slot_artifact(NavigationKind::Prev, info, 0)),
);
expected.extend(
layout
.prev_buffer_slots
.iter()
.filter(|info| applies(info.symbol_idx))
.map(|info| NavigationUpdate {
kind: NavigationKind::PrevBuffer,
storage_idx: info.buffer_idx as u8,
value_idx: info.value_idx as u8,
domain: info.domain,
first_offset: 0,
}),
);
expected
}
}
pub fn is_retained_row_extrema_type(
data_type: &datafusion::arrow::datatypes::DataType,
) -> bool {
use datafusion::arrow::datatypes::DataType;
matches!(
data_type,
DataType::Utf8
| DataType::LargeUtf8
| DataType::Utf8View
| DataType::Binary
| DataType::LargeBinary
| DataType::BinaryView
| DataType::FixedSizeBinary(_)
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn aggregate_state_widths_match_register_layout_contract() {
for (kind, value_type, expected_width) in [
(AggregateKind::Additive, SlotValueType::Int64, 1),
(AggregateKind::Additive, SlotValueType::Decimal128, 2),
(AggregateKind::Avg, SlotValueType::Int64, 2),
(AggregateKind::Avg, SlotValueType::Decimal128, 3),
(AggregateKind::Variance, SlotValueType::Float64, 3),
] {
let info = SlotInfo::with_kind(0, value_type, 0, kind);
assert_eq!(info.slot_count, expected_width, "{kind:?} {value_type:?}");
}
}
#[test]
fn navigation_input_capacity_includes_slots_and_prev_buffers() {
for (domain, width, limit) in [
(NavigationValueDomain::Primitive, 1, 32),
(NavigationValueDomain::Decimal128, 2, 16),
] {
let mut navigation = NavigationLayout {
num_nav_slots: MAX_NAV_SLOTS,
num_prev_buffers: MAX_PREV_BUFFERS,
..Default::default()
};
for index in 0..MAX_NAV_SLOTS / width {
navigation.first_slots.push(NavSlotInfo {
symbol_idx: None,
nav_slot: index * width,
value_idx: index,
domain,
});
}
for index in 0..MAX_PREV_BUFFERS / width {
navigation.prev_buffer_slots.push(PrevBufferInfo {
symbol_idx: None,
depth: 2,
buffer_idx: index * width,
value_idx: MAX_NAV_SLOTS / width + index,
domain,
});
}
for count in [limit, limit + 1] {
let names = (0..count).map(|i| format!("c{i}")).collect();
let (primitive, decimal) = match domain {
NavigationValueDomain::Primitive => (names, Vec::new()),
NavigationValueDomain::Decimal128 => (Vec::new(), names),
NavigationValueDomain::Classifier => unreachable!(),
};
let result = RegisterLayout::builder(0, Vec::new())
.navigation_inputs(primitive, decimal, Some(navigation.clone()))
.try_build();
assert_eq!(result.is_ok(), count == limit, "{domain:?}: {count}");
}
}
}
}