use super::{
BoundStateCell, BoundStateRead, BoundStateSource, bind_state_cells,
hydrate_fallback_aggregates,
};
use crate::core::vm::NavigationSource;
use crate::core::vm::{
AggregateKind, AggregateLayout, AggregateValueSource, NavSlotInfo, NavigationLayout,
NavigationLocation, NavigationValueDomain, PrevBufferInfo, RegisterLayout, SlotInfo,
SlotValueType, StatisticalPopulation, VarianceProjection,
};
use crate::execution::matching::row_loop::types::{
NavigationReadView, PackedNavigationLayout,
};
use datafusion::arrow::datatypes::{DataType, Field, Schema};
use datafusion::common::Result;
use datafusion::scalar::ScalarValue;
fn bind(data_type: DataType, source: AggregateValueSource) -> BoundStateCell {
bind_with_nonnull(data_type, source, None)
}
fn bind_with_nonnull(
data_type: DataType,
source: AggregateValueSource,
nonnull_count_slot: Option<usize>,
) -> BoundStateCell {
let schema = Schema::new(vec![Field::new("value", data_type.clone(), true)]);
let layout = binding_layout(&data_type, &source, nonnull_count_slot);
bind_state_cells(&schema, &layout, &[data_type])
.unwrap()
.pop()
.unwrap()
}
fn binding_layout(
data_type: &DataType,
source: &AggregateValueSource,
nonnull_count_slot: Option<usize>,
) -> RegisterLayout {
let slot_info = slot_info_for_binding(data_type, source);
let mut navigation = NavigationLayout::default();
let nav_info = |nav_slot, domain| NavSlotInfo {
symbol_idx: Some(0),
nav_slot,
value_idx: 0,
domain,
};
let buffer_info = |buffer_idx, depth, domain| PrevBufferInfo {
symbol_idx: Some(0),
depth,
buffer_idx,
value_idx: 0,
domain,
};
let domain = match source {
AggregateValueSource::Navigation(NavigationSource {
location, domain, ..
}) => {
let width = domain.storage_width();
match *location {
NavigationLocation::First(nav_slot) => {
navigation.first_slots.push(nav_info(nav_slot, *domain));
navigation.num_nav_slots = nav_slot + width;
}
NavigationLocation::Last(nav_slot) => {
navigation.last_slots.push(nav_info(nav_slot, *domain));
navigation.num_nav_slots = nav_slot + width;
}
NavigationLocation::Prev(nav_slot) => {
navigation.last_slots.push(nav_info(nav_slot, *domain));
navigation.prev_slots.push(nav_info(nav_slot, *domain));
navigation.num_nav_slots = nav_slot + width;
}
NavigationLocation::PrevBuffer { index, depth } => {
navigation
.prev_buffer_slots
.push(buffer_info(index, depth, *domain));
navigation.num_prev_buffers = index + width;
}
}
Some(*domain)
}
_ => None,
};
let (nav, nav_d128) = match domain {
Some(NavigationValueDomain::Primitive) => (vec!["value".into()], vec![]),
Some(NavigationValueDomain::Decimal128) => (vec![], vec!["value".into()]),
Some(NavigationValueDomain::Classifier) | None => (vec![], vec![]),
};
let num_slots = slot_info
.as_ref()
.map_or(0, |info| info.start_slot + info.slot_count)
.max(nonnull_count_slot.map_or(0, |slot| slot + 1));
RegisterLayout::builder(
num_slots,
vec![AggregateLayout {
slot: slot_info,
value_source: source.clone(),
nonnull_count_slot,
}],
)
.navigation_inputs(nav, nav_d128, domain.map(|_| navigation))
.try_build()
.unwrap()
}
fn slot_info_for_binding(
data_type: &DataType,
source: &AggregateValueSource,
) -> Option<SlotInfo> {
let scale = match data_type {
DataType::Decimal128(_, scale) | DataType::Decimal256(_, scale) => *scale,
_ => 0,
};
let scale = match source {
AggregateValueSource::AvgDecimal128 { scale_factor, .. } => {
scale - scale_factor.ilog10() as i8
}
_ => scale,
};
let (start_slot, kind) = match source {
AggregateValueSource::Register { slot }
| AggregateValueSource::RegisterD128 { slot } => (*slot, AggregateKind::Additive),
AggregateValueSource::Avg { sum_slot, .. }
| AggregateValueSource::AvgDecimal128 { sum_slot, .. } => {
(*sum_slot, AggregateKind::Avg)
}
AggregateValueSource::Variance { state_slot, .. } => {
(*state_slot, AggregateKind::Variance)
}
_ => return None,
};
let value_type = match source {
AggregateValueSource::RegisterD128 { .. }
| AggregateValueSource::AvgDecimal128 { .. } => SlotValueType::Decimal128,
AggregateValueSource::Register { .. } => match data_type {
DataType::UInt64 => SlotValueType::UInt64,
DataType::Float32 => SlotValueType::Float32,
DataType::Float64 => SlotValueType::Float64,
_ => SlotValueType::Int64,
},
AggregateValueSource::Avg { .. } | AggregateValueSource::Variance { .. } => {
SlotValueType::Float64
}
_ => SlotValueType::Int64,
};
Some(SlotInfo::with_kind(start_slot, value_type, scale, kind))
}
fn i128_words(value: i128) -> (u64, u64) {
let bytes = value.to_le_bytes();
(
u64::from_le_bytes(bytes[..8].try_into().unwrap()),
u64::from_le_bytes(bytes[8..].try_into().unwrap()),
)
}
#[test]
fn register_readers_and_hydration_preserve_unsigned_max_and_signed_decimal_words()
-> Result<()> {
let (low, high) = i128_words(-12_345);
for (data_type, source, words, scalar) in [
(
DataType::UInt64,
AggregateValueSource::Register { slot: 0 },
(u64::MAX, 0),
ScalarValue::UInt64(Some(u64::MAX)),
),
(
DataType::Decimal128(20, 2),
AggregateValueSource::RegisterD128 { slot: 0 },
(low, high),
ScalarValue::Decimal128(Some(-12_345), 20, 2),
),
] {
let cell = bind(data_type, source);
let mut registers = [0; 16];
registers[..2].copy_from_slice(&[words.0, words.1]);
assert_eq!(
cell.read(®isters, NavigationReadView::Empty, &[])?,
BoundStateRead::Scalar(scalar.clone())
);
let mut scalars = Vec::new();
hydrate_fallback_aggregates(
&[cell],
®isters,
NavigationReadView::Empty,
None,
&[],
&mut scalars,
&mut |_| Ok(()),
)?;
assert_eq!(scalars, [scalar]);
}
Ok(())
}
#[test]
fn temporal_register_and_navigation_readers_preserve_metadata_and_nulls() -> Result<()> {
use crate::core::vm::temporal_scalar_from_bits;
use datafusion::arrow::datatypes::TimeUnit;
let mut types = vec![
DataType::Date32,
DataType::Date64,
DataType::Time32(TimeUnit::Second),
DataType::Time32(TimeUnit::Millisecond),
DataType::Time64(TimeUnit::Microsecond),
DataType::Time64(TimeUnit::Nanosecond),
];
for unit in [
TimeUnit::Second,
TimeUnit::Millisecond,
TimeUnit::Microsecond,
TimeUnit::Nanosecond,
] {
types.push(DataType::Duration(unit));
types.push(DataType::Timestamp(unit, Some("Europe/Berlin".into())));
}
let raw = (-7_i64) as u64;
for data_type in types {
let value = temporal_scalar_from_bits(raw, &data_type).unwrap();
let null = ScalarValue::try_from(&data_type)?;
let schema = Schema::new(vec![Field::new("value", data_type.clone(), true)]);
let layout = RegisterLayout::builder(
2,
vec![AggregateLayout {
slot: Some(SlotInfo::with_kind(
0,
SlotValueType::Int64,
0,
AggregateKind::Min,
)),
value_source: AggregateValueSource::Register { slot: 0 },
nonnull_count_slot: Some(1),
}],
)
.try_build()
.unwrap();
let cells = bind_state_cells(&schema, &layout, std::slice::from_ref(&data_type))?;
assert_eq!(
cells[0].read(&[raw, 0], NavigationReadView::Empty, &[])?,
BoundStateRead::Scalar(null.clone())
);
assert_eq!(
cells[0].read(&[raw, 1], NavigationReadView::Empty, &[])?,
BoundStateRead::Scalar(value.clone())
);
if !matches!(
data_type,
DataType::Date32 | DataType::Timestamp(TimeUnit::Nanosecond, Some(_))
) {
continue;
}
let first = bind(
data_type.clone(),
AggregateValueSource::Navigation(NavigationSource {
location: NavigationLocation::First(0),
domain: NavigationValueDomain::Primitive,
default_value: None,
}),
);
let last = bind(
data_type.clone(),
AggregateValueSource::Navigation(NavigationSource {
location: NavigationLocation::Last(0),
domain: NavigationValueDomain::Primitive,
default_value: Some(value.clone()),
}),
);
let prev = bind(
data_type.clone(),
AggregateValueSource::Navigation(NavigationSource {
location: NavigationLocation::Prev(0),
domain: NavigationValueDomain::Primitive,
default_value: Some(value.clone()),
}),
);
let deep_prev = bind(
data_type.clone(),
AggregateValueSource::Navigation(NavigationSource {
location: NavigationLocation::PrevBuffer { index: 0, depth: 2 },
domain: NavigationValueDomain::Primitive,
default_value: Some(value.clone()),
}),
);
let registers = [0; 16];
assert_eq!(
first.read(®isters, NavigationReadView::Empty, &[])?,
BoundStateRead::Scalar(null.clone())
);
for cell in [&last, &prev, &deep_prev] {
assert_eq!(
cell.read(®isters, NavigationReadView::Empty, &[])?,
BoundStateRead::Scalar(value.clone())
);
}
let mut navigation = TestNavigation::new(NavigationValueDomain::Primitive);
navigation.store_first(0, raw, false);
navigation.store_last(0, raw, false);
for cell in [&first, &last] {
assert_eq!(
cell.read(®isters, navigation.view(), &[])?,
BoundStateRead::Scalar(value.clone())
);
}
let mut null_navigation = TestNavigation::new(NavigationValueDomain::Primitive);
null_navigation.store_first(0, raw, true);
null_navigation.store_last(0, raw, true);
for cell in [&first, &last] {
assert_eq!(
cell.read(®isters, null_navigation.view(), &[])?,
BoundStateRead::Scalar(null.clone())
);
}
}
Ok(())
}
#[test]
fn temporal_navigation_binding_requires_exact_unit_and_timezone() {
use datafusion::arrow::datatypes::TimeUnit;
let input = DataType::Timestamp(TimeUnit::Nanosecond, Some("Europe/Berlin".into()));
let schema = Schema::new(vec![Field::new("value", input.clone(), true)]);
let layout = binding_layout(
&input,
&AggregateValueSource::Navigation(NavigationSource {
location: NavigationLocation::First(0),
domain: NavigationValueDomain::Primitive,
default_value: None,
}),
None,
);
for output in [
DataType::Timestamp(TimeUnit::Nanosecond, None),
DataType::Timestamp(TimeUnit::Nanosecond, Some("UTC".into())),
DataType::Timestamp(TimeUnit::Microsecond, Some("Europe/Berlin".into())),
] {
assert!(bind_state_cells(&schema, &layout, &[output]).is_err());
}
}
#[test]
fn first_float32_rejects_float64_output() {
let schema = Schema::new(vec![Field::new("value", DataType::Float32, true)]);
let error = bind_state_cells(
&schema,
&binding_layout(
&DataType::Float32,
&AggregateValueSource::Navigation(NavigationSource {
location: NavigationLocation::First(0),
domain: NavigationValueDomain::Primitive,
default_value: None,
}),
None,
),
&[DataType::Float64],
)
.unwrap_err();
assert!(
error.to_string().contains("uses Float32 encoding")
&& error.to_string().contains("aggregate output type Float64"),
"{error}"
);
}
#[test]
fn managed_float_register_reads_preserve_width_and_exact_payload_bits() -> Result<()> {
for (data_type, bits) in [
(DataType::Float32, u64::from(0x7fa1_2345_u32)),
(DataType::Float64, 0x7ff8_0000_0000_0042),
] {
let cell = bind(
data_type.clone(),
AggregateValueSource::Register { slot: 0 },
);
let mut registers = [0; 16];
registers[0] = bits;
let BoundStateRead::Scalar(value) =
cell.read(®isters, NavigationReadView::Empty, &[])?
else {
panic!("expected managed float scalar");
};
assert_eq!(value.data_type(), data_type);
let actual = match value {
ScalarValue::Float32(Some(value)) => u64::from(value.to_bits()),
ScalarValue::Float64(Some(value)) => value.to_bits(),
other => panic!("expected non-null float: {other:?}"),
};
assert_eq!(actual, bits);
}
Ok(())
}
#[test]
fn nonnull_rule_returns_an_output_typed_null() -> Result<()> {
let cell = bind_with_nonnull(
DataType::UInt64,
AggregateValueSource::Register { slot: 0 },
Some(1),
);
let mut registers = [0; 16];
registers[0] = u64::MAX;
for (count, value) in [(0, None), (1, Some(u64::MAX))] {
registers[1] = count;
assert_eq!(
cell.read(®isters, NavigationReadView::Empty, &[])?,
BoundStateRead::Scalar(ScalarValue::UInt64(value))
);
}
Ok(())
}
#[test]
fn navigation_readers_preserve_missing_null_values_and_bound_defaults() -> Result<()> {
let registers = [0; 16];
let first = bind(
DataType::Int32,
AggregateValueSource::Navigation(NavigationSource {
location: NavigationLocation::First(0),
domain: NavigationValueDomain::Primitive,
default_value: None,
}),
);
let last = bind(
DataType::Int32,
AggregateValueSource::Navigation(NavigationSource {
location: NavigationLocation::Last(0),
domain: NavigationValueDomain::Primitive,
default_value: None,
}),
);
let mut navigation = TestNavigation::new(NavigationValueDomain::Primitive);
for (stage, expected) in [(0, None), (1, Some(11)), (2, None)] {
if expected.is_some() {
navigation.store_first(0, 11, false);
navigation.store_last(0, 11, false);
} else if stage == 2 {
navigation = TestNavigation::new(NavigationValueDomain::Primitive);
navigation.store_first(0, 11, true);
navigation.store_last(0, 11, true);
}
for cell in [&first, &last] {
assert_eq!(
cell.read(®isters, navigation.view(), &[])?,
BoundStateRead::Scalar(ScalarValue::Int32(expected))
);
}
}
for (data_type, source, expected) in [
(
DataType::Int32,
AggregateValueSource::Navigation(NavigationSource {
location: NavigationLocation::Prev(0),
domain: NavigationValueDomain::Primitive,
default_value: Some(ScalarValue::Int64(Some(7))),
}),
ScalarValue::Int32(Some(7)),
),
(
DataType::Int32,
AggregateValueSource::Navigation(NavigationSource {
location: NavigationLocation::Prev(0),
domain: NavigationValueDomain::Primitive,
default_value: Some(ScalarValue::Int64(None)),
}),
ScalarValue::Int32(None),
),
(
DataType::Decimal128(10, 0),
AggregateValueSource::Navigation(NavigationSource {
location: NavigationLocation::PrevBuffer { index: 0, depth: 4 },
domain: NavigationValueDomain::Decimal128,
default_value: Some(ScalarValue::Int64(Some(7))),
}),
ScalarValue::Decimal128(Some(7), 10, 0),
),
(
DataType::UInt64,
AggregateValueSource::Navigation(NavigationSource {
location: NavigationLocation::Prev(0),
domain: NavigationValueDomain::Primitive,
default_value: Some(ScalarValue::UInt64(Some(u64::MAX))),
}),
ScalarValue::UInt64(Some(u64::MAX)),
),
] {
assert_eq!(
bind(data_type, source).read(®isters, NavigationReadView::Empty, &[])?,
BoundStateRead::Scalar(expected)
);
}
for bits in [0x8000_0000_u32, 0x7fa1_2345_u32] {
let cell = bind(
DataType::Float32,
AggregateValueSource::Navigation(NavigationSource {
location: NavigationLocation::Prev(0),
domain: NavigationValueDomain::Primitive,
default_value: Some(ScalarValue::Float32(Some(f32::from_bits(bits)))),
}),
);
let BoundStateRead::Scalar(ScalarValue::Float32(Some(value))) =
cell.read(®isters, NavigationReadView::Empty, &[])?
else {
panic!("expected Float32 PREV default");
};
assert_eq!(value.to_bits(), bits);
}
Ok(())
}
#[test]
fn managed_defaults_validate_source_encoding_before_target_typed_default() {
for (data_type, source, fragment) in [
(
DataType::Decimal128(2, 0),
AggregateValueSource::Navigation(NavigationSource {
location: NavigationLocation::Prev(0),
domain: NavigationValueDomain::Decimal128,
default_value: Some(ScalarValue::Decimal128(Some(100), 2, 0)),
}),
"invalid decimal default",
),
(
DataType::Int32,
AggregateValueSource::Navigation(NavigationSource {
location: NavigationLocation::Prev(0),
domain: NavigationValueDomain::Primitive,
default_value: Some(ScalarValue::Utf8(Some("not-an-int".into()))),
}),
"default cannot be cast from Utf8 to Int32",
),
] {
let schema = Schema::new(vec![Field::new("value", data_type.clone(), true)]);
let layout_source = match &source {
AggregateValueSource::Navigation(NavigationSource {
location,
domain,
..
}) => AggregateValueSource::Navigation(NavigationSource {
location: *location,
domain: *domain,
default_value: None,
}),
_ => unreachable!("default validation uses PREV sources"),
};
let layout = binding_layout(&data_type, &layout_source, None);
let source_error =
BoundStateSource::try_bind(&source, &DataType::Float64, &schema, &layout, 0)
.unwrap_err()
.to_string();
assert!(
source_error.contains("encoding") && !source_error.contains(fragment),
"{source_error}"
);
let error = BoundStateSource::try_bind(&source, &data_type, &schema, &layout, 0)
.unwrap_err()
.to_string();
assert!(
error.contains("VM scratch source binding failed for aggregate 0")
&& error.contains(fragment),
"{error}"
);
}
}
#[test]
fn managed_decimal_sources_reject_invalid_output_metadata_without_a_default() {
for (data_type, source) in [
(
DataType::Decimal128(0, 0),
AggregateValueSource::AccumulatorOwned,
),
(
DataType::Decimal256(77, 0),
AggregateValueSource::AccumulatorOwned,
),
] {
let schema = Schema::new(vec![Field::new("value", data_type.clone(), true)]);
let layout = binding_layout(&data_type, &source, None);
let error = bind_state_cells(&schema, &layout, &[data_type])
.unwrap_err()
.to_string();
assert!(error.contains("invalid decimal output type"), "{error}");
}
}
#[test]
fn avg_readers_preserve_float_and_decimal_state() -> Result<()> {
let mut registers = [0; 16];
registers[0] = (-9.0_f64).to_bits();
registers[1] = 2;
let negative_avg = bind(
DataType::Float64,
AggregateValueSource::Avg {
sum_slot: 0,
count_slot: 1,
},
);
assert_eq!(
negative_avg.read(®isters, NavigationReadView::Empty, &[])?,
BoundStateRead::Scalar(ScalarValue::Float64(Some(-4.5)))
);
registers[0] = 9.0_f64.to_bits();
let float_avg = bind(
DataType::Float64,
AggregateValueSource::Avg {
sum_slot: 0,
count_slot: 1,
},
);
assert_eq!(
float_avg.read(®isters, NavigationReadView::Empty, &[])?,
BoundStateRead::Scalar(ScalarValue::Float64(Some(4.5)))
);
let (low, high) = i128_words(-246);
registers[0] = low;
registers[1] = high;
registers[2] = 2;
let decimal_avg = bind(
DataType::Decimal128(20, 2),
AggregateValueSource::AvgDecimal128 {
sum_slot: 0,
count_slot: 2,
scale_factor: 1,
},
);
assert_eq!(
decimal_avg.read(®isters, NavigationReadView::Empty, &[])?,
BoundStateRead::Scalar(ScalarValue::Decimal128(Some(-123), 20, 2))
);
Ok(())
}
#[test]
fn winning_register_values_preserve_nulls_and_decline_inexact_results() {
use crate::execution::matching::WinningValue;
let integer = bind_with_nonnull(
DataType::Int64,
AggregateValueSource::Register { slot: 0 },
Some(1),
);
assert_eq!(
integer.winning_value(&[42, 0], &DataType::Int64),
Some(WinningValue::Int64(None))
);
assert_eq!(
integer.winning_value(&[42, 1], &DataType::Int64),
Some(WinningValue::Int64(Some(42)))
);
assert_eq!(integer.winning_value(&[42, 1], &DataType::Float64), None);
let avg = bind(
DataType::Float64,
AggregateValueSource::Avg {
sum_slot: 0,
count_slot: 1,
},
);
assert_eq!(
avg.winning_value(&[9.0_f64.to_bits(), 2], &DataType::Float64),
Some(WinningValue::Float64(Some(4.5)))
);
assert_eq!(
avg.winning_value(&[f64::NAN.to_bits(), 1], &DataType::Float64),
None
);
let output = DataType::Decimal128(14, 6);
let avg = bind(
output.clone(),
AggregateValueSource::AvgDecimal128 {
sum_slot: 0,
count_slot: 2,
scale_factor: 10_000,
},
);
let (lo, hi) = i128_words(-511);
assert_eq!(
avg.winning_value(&[lo, hi, 3], &output),
Some(WinningValue::Decimal128(Some(-1_703_333)))
);
for sum in [10_000_000_000, i128::MAX] {
let (lo, hi) = i128_words(sum);
assert_eq!(avg.winning_value(&[lo, hi, 1], &output), None);
}
}
#[test]
fn statistical_register_reader_preserves_empty_singleton_and_sample_population_projection()
-> Result<()> {
let mut registers = [0; 16];
registers[0] = 42.0_f64.to_bits();
for (projection, singleton, second) in [
(
VarianceProjection::Variance(StatisticalPopulation::Population),
Some(0.0),
4.0,
),
(
VarianceProjection::Variance(StatisticalPopulation::Sample),
None,
8.0,
),
(
VarianceProjection::Stddev(StatisticalPopulation::Population),
Some(0.0),
2.0,
),
(
VarianceProjection::Stddev(StatisticalPopulation::Sample),
None,
8.0_f64.sqrt(),
),
] {
let cell = bind(
DataType::Float64,
AggregateValueSource::Variance {
state_slot: 0,
projection,
},
);
for (count, m2, expected) in [
(0, 0.0_f64, None),
(1, 0.0, singleton),
(2, 8.0, Some(second)),
] {
registers[1] = m2.to_bits();
registers[2] = count;
assert_eq!(
cell.read(®isters, NavigationReadView::Empty, &[])?,
BoundStateRead::Scalar(ScalarValue::Float64(expected))
);
}
}
Ok(())
}
#[test]
fn offset_zero_prev_defaults_apply_only_to_missing_positions() -> Result<()> {
let registers = [0; 16];
let primitive = bind(
DataType::Int32,
AggregateValueSource::Navigation(NavigationSource {
location: NavigationLocation::Last(0),
domain: NavigationValueDomain::Primitive,
default_value: Some(ScalarValue::Int64(Some(7))),
}),
);
let decimal128 = bind(
DataType::Decimal128(10, 0),
AggregateValueSource::Navigation(NavigationSource {
location: NavigationLocation::Last(0),
domain: NavigationValueDomain::Decimal128,
default_value: Some(ScalarValue::Int64(Some(8))),
}),
);
assert_eq!(
primitive.read(®isters, NavigationReadView::Empty, &[])?,
BoundStateRead::Scalar(ScalarValue::Int32(Some(7)))
);
assert_eq!(
decimal128.read(®isters, NavigationReadView::Empty, &[])?,
BoundStateRead::Scalar(ScalarValue::Decimal128(Some(8), 10, 0))
);
let mut primitive_null = TestNavigation::new(NavigationValueDomain::Primitive);
primitive_null.store_last(0, 0, true);
assert_eq!(
primitive.read(®isters, primitive_null.view(), &[])?,
BoundStateRead::Scalar(ScalarValue::Int32(None))
);
let mut decimal128_null = TestNavigation::new(NavigationValueDomain::Decimal128);
decimal128_null.store_last_words(0, [0, 0], true);
assert_eq!(
decimal128.read(®isters, decimal128_null.view(), &[])?,
BoundStateRead::Scalar(ScalarValue::Decimal128(None, 10, 0))
);
Ok(())
}
#[test]
fn classifier_navigation_readers_decode_symbol_names_and_defaults() -> Result<()> {
let registers = [0; 16];
let symbol_names = vec![None, Some("URGENT".to_string()), Some("NORMAL".to_string())];
let layout = RegisterLayout::builder(
0,
vec![
AggregateLayout {
value_source: AggregateValueSource::Navigation(NavigationSource {
location: NavigationLocation::First(0),
domain: NavigationValueDomain::Classifier,
default_value: None,
}),
..Default::default()
},
AggregateLayout {
value_source: AggregateValueSource::Navigation(NavigationSource {
location: NavigationLocation::Prev(1),
domain: NavigationValueDomain::Classifier,
default_value: Some(ScalarValue::Utf8(Some("NONE".to_string()))),
}),
..Default::default()
},
],
)
.navigation_inputs(
vec![],
vec![],
Some(NavigationLayout {
num_nav_slots: 2,
first_slots: vec![NavSlotInfo {
symbol_idx: None,
nav_slot: 0,
value_idx: 0,
domain: NavigationValueDomain::Classifier,
}],
last_slots: vec![NavSlotInfo {
symbol_idx: None,
nav_slot: 1,
value_idx: 0,
domain: NavigationValueDomain::Classifier,
}],
prev_slots: vec![NavSlotInfo {
symbol_idx: None,
nav_slot: 1,
value_idx: 0,
domain: NavigationValueDomain::Classifier,
}],
..Default::default()
}),
)
.try_build()
.unwrap();
let cells =
bind_state_cells(&Schema::empty(), &layout, &[DataType::Utf8, DataType::Utf8])?;
assert_eq!(
cells[0].read(®isters, NavigationReadView::Empty, &symbol_names)?,
BoundStateRead::Scalar(ScalarValue::Utf8(None))
);
assert_eq!(
cells[1].read(®isters, NavigationReadView::Empty, &symbol_names)?,
BoundStateRead::Scalar(ScalarValue::Utf8(Some("NONE".to_string())))
);
let mut nav = TestNavigation::new(NavigationValueDomain::Classifier);
nav.store_first(0, 1, false);
nav.update_prev_last(1, 1, false);
nav.update_prev_last(1, 2, false);
assert_eq!(
cells[0].read(®isters, nav.view(), &symbol_names)?,
BoundStateRead::Scalar(ScalarValue::Utf8(Some("URGENT".to_string())))
);
assert_eq!(
cells[1].read(®isters, nav.view(), &symbol_names)?,
BoundStateRead::Scalar(ScalarValue::Utf8(Some("URGENT".to_string())))
);
Ok(())
}
struct TestNavigation {
layout: PackedNavigationLayout,
words: Vec<u64>,
domain: NavigationValueDomain,
}
impl TestNavigation {
fn new(domain: NavigationValueDomain) -> Self {
let slot = |nav_slot| NavSlotInfo {
symbol_idx: None,
nav_slot,
value_idx: 0,
domain,
};
let slots = if domain == NavigationValueDomain::Decimal128 {
vec![slot(0)]
} else {
vec![slot(0), slot(1)]
};
let layout = PackedNavigationLayout::try_new(&NavigationLayout {
num_nav_slots: 2,
first_slots: slots.clone(),
last_slots: slots.clone(),
prev_slots: slots,
..Default::default()
})
.unwrap();
let words = vec![0; layout.frame_words()];
Self {
layout,
words,
domain,
}
}
fn view(&self) -> NavigationReadView<'_> {
NavigationReadView::Packed(self.layout.view(&self.words).unwrap())
}
fn store(
&mut self,
slot: usize,
kind: crate::core::vm::NavigationKind,
words: [u64; 2],
null: bool,
) {
self.layout
.view_mut(&mut self.words)
.unwrap()
.apply_update(
crate::core::vm::NavigationUpdate {
kind,
storage_idx: slot as u8,
value_idx: 0,
first_offset: 0,
domain: self.domain,
},
words,
null,
)
.unwrap();
}
fn store_first(&mut self, slot: usize, value: u64, null: bool) {
self.store(
slot,
crate::core::vm::NavigationKind::First,
[value, 0],
null,
);
}
fn store_last(&mut self, slot: usize, value: u64, null: bool) {
self.store(
slot,
crate::core::vm::NavigationKind::Last,
[value, 0],
null,
);
}
fn store_last_words(&mut self, slot: usize, value: [u64; 2], null: bool) {
self.store(slot, crate::core::vm::NavigationKind::Last, value, null);
}
fn update_prev_last(&mut self, slot: usize, value: u64, null: bool) {
self.store(
slot,
crate::core::vm::NavigationKind::Prev,
[value, 0],
null,
);
}
}
#[test]
fn long_register_hydration_cancels_coarsely_and_retries_exactly() {
let cells =
vec![bind(DataType::Int64, AggregateValueSource::Register { slot: 0 }); 65];
let mut scalars = vec![ScalarValue::Int64(Some(-1)); 65];
for cancel in [true, false] {
let mut reports = Vec::new();
let result = hydrate_fallback_aggregates(
&cells,
&[7],
NavigationReadView::Empty,
None,
&[],
&mut scalars,
&mut |units| {
reports.push(units);
if cancel {
datafusion::common::exec_err!("cancelled")
} else {
Ok(())
}
},
);
if cancel {
assert!(result.unwrap_err().to_string().contains("cancelled"));
assert_eq!(reports, [64]);
assert_eq!(scalars[0], ScalarValue::Int64(Some(7)));
} else {
result.unwrap();
assert_eq!(reports, [64, 1]);
assert_eq!(scalars, vec![ScalarValue::Int64(Some(7)); 65]);
}
}
}
#[test]
fn fallback_hydration_rejects_accumulator_owned_cells() {
let cell = bind(DataType::Int64, AggregateValueSource::AccumulatorOwned);
let error = hydrate_fallback_aggregates(
&[cell],
&[],
NavigationReadView::Empty,
None,
&[],
&mut vec![ScalarValue::Int64(Some(7))],
&mut |_| Ok(()),
)
.unwrap_err();
assert!(error.to_string().contains("requires VM-owned cells"));
}
#[test]
fn state_cell_binding_requires_output_alignment() {
let error = bind_state_cells(
&Schema::empty(),
&RegisterLayout::default(),
&[DataType::Int64],
)
.unwrap_err();
assert!(error.to_string().contains("not aligned"));
}
#[test]
fn retained_input_hydration_preserves_absolute_rows_and_nulls() -> Result<()> {
use super::{CandidateInput, hydrate_fallback_aggregates};
use crate::core::AbsoluteRow;
use crate::execution::storage::collection::BatchCollection;
use datafusion::arrow::array::StringArray;
use datafusion::arrow::record_batch::RecordBatch;
use std::sync::Arc;
let schema = Arc::new(Schema::new(vec![Field::new("value", DataType::Utf8, true)]));
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![Arc::new(StringArray::from(vec![
None,
Some("start"),
Some("last"),
]))],
)?;
let collection = BatchCollection::try_new(vec![batch], Arc::clone(&schema))?;
let input = CandidateInput::new(&collection, AbsoluteRow::new(11), 10);
let layout = RegisterLayout::builder(
2,
vec![
AggregateLayout {
value_source: AggregateValueSource::CandidateStart {
column: "value".into(),
},
..Default::default()
},
AggregateLayout {
slot: Some(SlotInfo::int64(0)),
value_source: AggregateValueSource::RetainedRow {
slot: 0,
column: "value".into(),
},
nonnull_count_slot: Some(1),
},
],
)
.try_build()
.unwrap();
let cells = bind_state_cells(&schema, &layout, &[DataType::Utf8, DataType::Utf8])?;
let mut scalars = vec![];
for (row, count, expected) in [(12, 1, Some("last")), (10, 1, None), (999, 0, None)] {
let mut work = 0;
hydrate_fallback_aggregates(
&cells,
&[row, count],
NavigationReadView::Empty,
Some(input),
&[],
&mut scalars,
&mut |units| {
work += units;
Ok(())
},
)?;
assert_eq!(
scalars,
[
ScalarValue::Utf8(Some("start".into())),
ScalarValue::Utf8(expected.map(str::to_owned))
]
);
assert_eq!(work, 2); }
for candidate in [None, Some(input)] {
let error = hydrate_fallback_aggregates(
&cells,
&[999, 1],
NavigationReadView::Empty,
candidate,
&[],
&mut scalars,
&mut |_| Ok(()),
)
.unwrap_err();
assert!(
error.to_string().contains(if candidate.is_some() {
"outside retained input"
} else {
"no input binding"
}),
"{error}"
);
}
for schema in [
Schema::empty(),
Schema::new(vec![Field::new("value", DataType::Int64, true)]),
] {
assert!(
bind_state_cells(&schema, &layout, &[DataType::Utf8, DataType::Utf8])
.is_err()
);
}
Ok(())
}
#[test]
fn decimal_hydration_overflow_precedes_cancellation_and_empty_average_is_null()
-> Result<()> {
let cell = bind(
DataType::Decimal128(38, 4),
AggregateValueSource::AvgDecimal128 {
sum_slot: 0,
count_slot: 2,
scale_factor: 10_000,
},
);
let (lo, hi) = i128_words(10_i128.pow(37));
assert_eq!(
cell.read(&[lo, hi, 0], NavigationReadView::Empty, &[])?,
BoundStateRead::Scalar(ScalarValue::Decimal128(None, 38, 4))
);
let mut cells =
vec![bind(DataType::Int64, AggregateValueSource::Register { slot: 2 }); 63];
cells.push(cell);
let mut scalars = vec![ScalarValue::Int64(Some(7)); 63];
let mut reports = vec![];
let error = hydrate_fallback_aggregates(
&cells,
&[lo, hi, 10_000],
NavigationReadView::Empty,
None,
&[],
&mut scalars,
&mut |units| {
reports.push(units);
datafusion::common::exec_err!("cancelled")
},
)
.unwrap_err();
assert!(
error
.to_string()
.contains("Decimal128 overflow while materializing VM AVG"),
"{error}"
);
assert_eq!(reports, [64]);
assert_eq!(scalars.len(), 63);
Ok(())
}