use std::mem::{size_of, size_of_val};
use std::sync::Arc;
use datafusion::arrow::array::{
Array, ArrayRef, AsArray, BooleanArray, ListArray, new_empty_array,
};
use datafusion::arrow::buffer::{OffsetBuffer, ScalarBuffer};
use datafusion::arrow::datatypes::{DataType, Field};
use datafusion::arrow::row::{Row, Rows};
use datafusion::logical_expr::groups_accumulator::{EmitTo, GroupsAccumulator};
use datafusion_common::utils::memory::RecordBatchMemoryTracker;
use datafusion_common::utils::offset_span;
use datafusion_common::{DataFusionError, HashMap, Result, ScalarValue};
use datafusion_hash_grouped_order::gather::interleave_compact_with_memory;
use crate::functions::navigation_common::{
LogicalAnchor, NavigationKind, resolve_navigation_default,
};
use super::helpers::{
NavigationOrdering, NavigationStateLists, base_state_fields,
decode_navigation_batch_args, evaluate_navigation_target,
normalize_state_history_array, state_history_data_type,
};
fn row_passes_filter(filter: Option<&BooleanArray>, row_idx: usize) -> bool {
filter.is_none_or(|filter| filter.is_valid(row_idx) && filter.value(row_idx))
}
fn navigation_list_offset(row_count: usize) -> Result<i32> {
i32::try_from(row_count).map_err(|_| {
DataFusionError::ResourcesExhausted(
"navigation aggregate state exceeds Arrow List offset capacity".to_string(),
)
})
}
fn last_navigation_row_index(len: usize) -> Result<u32> {
u32::try_from(len.saturating_sub(1)).map_err(|_| {
DataFusionError::ResourcesExhausted(
"navigation aggregate row index exceeds u32 capacity".to_string(),
)
})
}
#[derive(Debug)]
struct RetainedNavigationBatch {
value: ArrayRef,
symbol: Option<ArrayRef>,
orderings: Vec<ArrayRef>,
ordering_rows: Option<Rows>,
live_rows: usize,
}
impl RetainedNavigationBatch {
fn arrays(&self) -> impl Iterator<Item = &ArrayRef> {
std::iter::once(&self.value)
.chain(self.symbol.as_ref())
.chain(&self.orderings)
}
fn extra_overhead_bytes(&self) -> usize {
let orderings_vec_bytes = self.orderings.capacity() * size_of::<ArrayRef>();
let rows_bytes = self
.ordering_rows
.as_ref()
.map_or(0, |rows| rows.size() - size_of_val(rows));
orderings_vec_bytes + rows_bytes
}
fn ordering_row(&self, row_idx: u32) -> Row<'_> {
self.ordering_rows
.as_ref()
.expect("ordered navigation batch must retain encoded ordering rows")
.row(row_idx as usize)
}
}
fn batch_ordering_row(
batches: &[Option<RetainedNavigationBatch>],
batch_idx: u32,
row_idx: u32,
) -> Row<'_> {
batches[batch_idx as usize]
.as_ref()
.expect("navigation row reference points to a live batch")
.ordering_row(row_idx)
}
#[derive(Debug)]
pub struct NavigationGroupsAccumulator {
kind: NavigationKind,
anchor: LogicalAnchor,
fixed_arg_count: usize,
group_row_refs: Vec<Vec<(u32, u32)>>,
row_refs_capacity: usize,
batches: Vec<Option<RetainedNavigationBatch>>,
free_batch_indices: Vec<u32>,
batch_buffers: RecordBatchMemoryTracker,
batch_array_overhead: usize,
ordering: Option<NavigationOrdering>,
offset: usize,
default_value: ScalarValue,
data_type: DataType,
}
impl NavigationGroupsAccumulator {
#[cfg(test)]
pub fn new(
kind: NavigationKind,
data_type: DataType,
offset: usize,
default_value: ScalarValue,
) -> Self {
Self::try_new(kind, data_type, offset, default_value)
.expect("test navigation default must cast to the result type")
}
#[cfg(test)]
pub(crate) fn try_new(
kind: NavigationKind,
data_type: DataType,
offset: usize,
default_value: ScalarValue,
) -> Result<Self> {
Self::try_new_with_ordering(kind, data_type, offset, default_value, None)
}
#[cfg(test)]
pub(crate) fn try_new_with_ordering(
kind: NavigationKind,
data_type: DataType,
offset: usize,
default_value: ScalarValue,
ordering: Option<NavigationOrdering>,
) -> Result<Self> {
Self::try_new_configured(
kind,
data_type,
LogicalAnchor::Last(0),
offset,
default_value,
super::helpers::NAVIGATION_UDAF_ARG_COUNT,
ordering,
)
}
pub(crate) fn try_new_configured(
kind: NavigationKind,
data_type: DataType,
anchor: LogicalAnchor,
offset: usize,
default_value: ScalarValue,
fixed_arg_count: usize,
ordering: Option<NavigationOrdering>,
) -> Result<Self> {
let default_value = resolve_navigation_default(&default_value, &data_type)?;
Ok(Self {
kind,
anchor,
fixed_arg_count,
group_row_refs: Vec::new(),
row_refs_capacity: 0,
batches: Vec::new(),
free_batch_indices: Vec::new(),
batch_buffers: RecordBatchMemoryTracker::new(),
batch_array_overhead: 0,
ordering,
offset,
default_value,
data_type,
})
}
fn batch(&self, batch_idx: u32) -> &RetainedNavigationBatch {
self.batches[batch_idx as usize]
.as_ref()
.expect("navigation row reference points to a live batch")
}
fn retain_batch(&mut self, batch: RetainedNavigationBatch) -> Result<u32> {
let batch_idx = match self.free_batch_indices.pop() {
Some(index) => index,
None => {
let index = u32::try_from(self.batches.len()).map_err(|_| {
DataFusionError::ResourcesExhausted(
"navigation aggregate batch index exceeds u32 capacity"
.to_string(),
)
})?;
self.batches.push(None);
index
}
};
for array in batch.arrays() {
self.batch_buffers.count_array(array.as_ref());
self.batch_array_overhead +=
array.get_array_memory_size() - array.get_buffer_memory_size();
}
self.batch_array_overhead += batch.extra_overhead_bytes();
self.batches[batch_idx as usize] = Some(batch);
Ok(batch_idx)
}
fn release_groups(&mut self, emit_to: EmitTo) {
if matches!(emit_to, EmitTo::All) {
self.group_row_refs.clear();
self.row_refs_capacity = 0;
self.batch_buffers = RecordBatchMemoryTracker::new();
self.batches.clear();
self.free_batch_indices.clear();
self.batch_array_overhead = 0;
return;
}
let taken = match emit_to {
EmitTo::All => unreachable!("EmitTo::All returned above"),
EmitTo::First(n) => EmitTo::First(n.min(self.group_row_refs.len()))
.take_needed(&mut self.group_row_refs),
};
for rows in taken {
self.row_refs_capacity -= rows.capacity();
for (batch_idx, _) in rows {
let retained = &mut self.batches[batch_idx as usize];
let batch = retained
.as_mut()
.expect("navigation row reference points to a live batch");
batch.live_rows -= 1;
if batch.live_rows == 0 {
for array in batch.arrays() {
self.batch_buffers.uncount_array(array.as_ref());
self.batch_array_overhead -= array.get_array_memory_size()
- array.get_buffer_memory_size();
}
self.batch_array_overhead -= batch.extra_overhead_bytes();
*retained = None;
self.free_batch_indices.push(batch_idx);
}
}
}
if self.batches.len() == self.free_batch_indices.len() {
self.batches.clear();
self.free_batch_indices.clear();
self.batch_buffers = RecordBatchMemoryTracker::new();
}
}
fn sort_groups_prefix(&mut self, num_groups: usize) {
if self.ordering.is_none() {
return;
}
let limit = num_groups.min(self.group_row_refs.len());
let batches = &self.batches;
for rows in &mut self.group_row_refs[..limit] {
if rows.len() <= 1 {
continue;
}
let already_sorted = rows.windows(2).all(|pair| {
let (b0, r0) = pair[0];
let (b1, r1) = pair[1];
batch_ordering_row(batches, b0, r0) <= batch_ordering_row(batches, b1, r1)
});
if !already_sorted {
rows.sort_by(|&(b0, r0), &(b1, r1)| {
batch_ordering_row(batches, b0, r0)
.cmp(&batch_ordering_row(batches, b1, r1))
});
}
}
}
fn evaluate_group(&self, group_idx: usize) -> Result<ScalarValue> {
let rows = match self.group_row_refs.get(group_idx) {
Some(r) => r,
None => return Ok(self.default_value.clone()),
};
if rows.is_empty() {
return Ok(self.default_value.clone());
}
if self.kind.is_edge() {
return match self.anchor.resolve_unmasked(rows.len()) {
Some(target) => {
let (batch_idx, row_idx) = rows[target];
ScalarValue::try_from_array(
&self.batch(batch_idx).value,
row_idx as usize,
)
}
None => Ok(self.default_value.clone()),
};
}
let anchor_idx = self.anchor.resolve_masked(rows.len(), |i| {
let (batch_idx, row_idx) = rows[i];
let symbol_arr = self
.batch(batch_idx)
.symbol
.as_ref()
.expect("shift navigation batch must retain classifier mask")
.as_boolean();
symbol_arr.is_valid(row_idx as usize) && symbol_arr.value(row_idx as usize)
});
evaluate_navigation_target(
self.kind,
anchor_idx,
self.offset,
rows.len(),
&self.default_value,
|target| {
let (batch_idx, row_idx) = rows[target];
ScalarValue::try_from_array(
&self.batch(batch_idx).value,
row_idx as usize,
)
},
)
}
fn list_state_array(
&self,
data_type: &DataType,
offsets: &OffsetBuffer<i32>,
interleave_indices: &[(usize, usize)],
used_batches: &[usize],
array: impl Fn(&RetainedNavigationBatch) -> &ArrayRef,
) -> Result<ArrayRef> {
let data_type = state_history_data_type(data_type);
let values = if interleave_indices.is_empty() {
new_empty_array(&data_type)
} else {
let sources = used_batches
.iter()
.map(|&batch_idx| {
let batch = self.batches[batch_idx]
.as_ref()
.expect("navigation row reference points to a live batch");
normalize_state_history_array(array(batch), &data_type)
})
.collect::<Result<Vec<_>>>()?;
let sources: Vec<&dyn Array> =
sources.iter().map(|array| array.as_ref()).collect();
interleave_compact_with_memory(&sources, interleave_indices, None)?
};
Ok(Arc::new(ListArray::new(
Arc::new(Field::new("item", data_type.clone(), true)),
offsets.clone(),
values,
None,
)))
}
fn list_state_array_for_selected_rows(
data_type: &DataType,
source: &ArrayRef,
selected_rows: &[(usize, usize)],
offsets: &OffsetBuffer<i32>,
) -> Result<ArrayRef> {
let data_type = state_history_data_type(data_type);
let values = if selected_rows.is_empty() {
new_empty_array(&data_type)
} else {
let source = normalize_state_history_array(source, &data_type)?;
interleave_compact_with_memory(&[source.as_ref()], selected_rows, None)?
};
Ok(Arc::new(ListArray::new(
Arc::new(Field::new("item", data_type.clone(), true)),
offsets.clone(),
values,
None,
)))
}
}
impl GroupsAccumulator for NavigationGroupsAccumulator {
fn update_batch(
&mut self,
values: &[ArrayRef],
group_indices: &[usize],
opt_filter: Option<&BooleanArray>,
total_num_groups: usize,
) -> Result<()> {
let batch_args = decode_navigation_batch_args(
self.kind,
self.fixed_arg_count,
&self.data_type,
values,
self.ordering.as_ref(),
self.kind.aggregate_name(),
)?;
let last_row = last_navigation_row_index(group_indices.len())?;
last_navigation_row_index(batch_args.batch_len)?;
if self.group_row_refs.len() < total_num_groups {
self.group_row_refs.resize(total_num_groups, Vec::new());
}
if batch_args.batch_len == 0 {
return Ok(());
}
let live_rows = opt_filter.map_or(batch_args.batch_len, BooleanArray::true_count);
if live_rows == 0 {
return Ok(());
}
let orderings: Vec<ArrayRef> =
batch_args.ordering_arrays.iter().map(Arc::clone).collect();
let ordering_rows = self
.ordering
.as_ref()
.map(|ordering| ordering.convert_columns(&orderings))
.transpose()?;
let batch_idx = self.retain_batch(RetainedNavigationBatch {
value: batch_args.value_array,
symbol: batch_args.symbol_mask,
orderings,
ordering_rows,
live_rows,
})?;
for (row_idx, &group_id) in (0..=last_row).zip(group_indices) {
if !row_passes_filter(opt_filter, row_idx as usize) {
continue;
}
let rows = &mut self.group_row_refs[group_id];
let capacity = rows.capacity();
rows.push((batch_idx, row_idx));
self.row_refs_capacity += rows.capacity() - capacity;
}
Ok(())
}
fn evaluate(&mut self, emit_to: EmitTo) -> Result<ArrayRef> {
let num_groups = match emit_to {
EmitTo::All => self.group_row_refs.len(),
EmitTo::First(n) => n,
};
if num_groups == 0 {
return Ok(new_empty_array(&self.data_type));
}
self.sort_groups_prefix(num_groups);
let history_type = state_history_data_type(&self.data_type);
let results: Vec<ScalarValue> = (0..num_groups)
.map(|g| {
let scalar = self.evaluate_group(g)?;
if scalar.data_type() == history_type {
return Ok(scalar);
}
let normalized =
normalize_state_history_array(&scalar.to_array()?, &history_type)?;
ScalarValue::try_from_array(&normalized, 0)
})
.collect::<Result<_>>()?;
let result = ScalarValue::iter_to_array(results)?;
let result = normalize_state_history_array(&result, &self.data_type)?;
self.release_groups(emit_to);
Ok(result)
}
fn state(&mut self, emit_to: EmitTo) -> Result<Vec<ArrayRef>> {
let num_groups = match emit_to {
EmitTo::All => self.group_row_refs.len(),
EmitTo::First(n) => n,
};
self.sort_groups_prefix(num_groups);
let mut offsets = Vec::with_capacity(num_groups + 1);
let mut interleave_indices = Vec::new();
let mut used_batches = Vec::new();
let mut batch_indices = HashMap::new();
offsets.push(0_i32);
for group_idx in 0..num_groups {
let rows = self
.group_row_refs
.get(group_idx)
.map(Vec::as_slice)
.unwrap_or_default();
let row_count = interleave_indices.len().saturating_add(rows.len());
offsets.push(navigation_list_offset(row_count)?);
for &(batch_idx, row_idx) in rows {
let source = *batch_indices.entry(batch_idx).or_insert_with(|| {
let source = used_batches.len();
used_batches.push(batch_idx as usize);
source
});
interleave_indices.push((source, row_idx as usize));
}
}
let offsets = OffsetBuffer::new(ScalarBuffer::from(offsets));
let values = self.list_state_array(
&self.data_type,
&offsets,
&interleave_indices,
&used_batches,
|batch| &batch.value,
)?;
let ordering_count = self
.ordering
.as_ref()
.map_or(0, NavigationOrdering::num_columns);
let mut result =
Vec::with_capacity(base_state_fields(self.kind) + ordering_count);
result.push(values);
if self.kind.is_shift() {
let symbol_matched = self.list_state_array(
&DataType::Boolean,
&offsets,
&interleave_indices,
&used_batches,
|batch| {
batch
.symbol
.as_ref()
.expect("shift navigation batch must retain classifier mask")
},
)?;
result.push(symbol_matched);
}
if let Some(ordering) = &self.ordering {
for (idx, data_type) in ordering.data_types().iter().enumerate() {
result.push(self.list_state_array(
data_type,
&offsets,
&interleave_indices,
&used_batches,
|batch| &batch.orderings[idx],
)?);
}
}
self.release_groups(emit_to);
Ok(result)
}
fn merge_batch(
&mut self,
values: &[ArrayRef],
group_indices: &[usize],
total_num_groups: usize,
) -> Result<()> {
if self.group_row_refs.len() < total_num_groups {
self.group_row_refs.resize(total_num_groups, Vec::new());
}
if values.is_empty() {
return Ok(());
}
let state_lists = NavigationStateLists::decode(
values,
self.kind,
&self.data_type,
self.ordering.as_ref(),
Some(group_indices.len()),
)?;
let value_offsets: &[i32] = state_lists.values.offsets();
let same_offsets = !group_indices.is_empty()
&& state_lists
.symbols
.is_none_or(|symbols| value_offsets == symbols.offsets().as_ref())
&& state_lists
.orderings
.iter()
.all(|list| value_offsets == list.offsets().as_ref());
if same_offsets {
let offsets = state_lists.values.offsets();
let mut live_rows = 0usize;
for row_idx in 0..group_indices.len() {
if !state_lists.row_is_present(row_idx)? {
continue;
}
let start = offsets[row_idx] as usize;
let end = offsets[row_idx + 1] as usize;
live_rows += end - start;
}
if live_rows == 0 {
return Ok(());
}
let (span_start, span_len) = offset_span(offsets);
last_navigation_row_index(span_len)?;
let value = state_lists.values.values().slice(span_start, span_len);
let symbol = state_lists
.symbols
.map(|symbols| symbols.values().slice(span_start, span_len));
let orderings: Vec<ArrayRef> = state_lists
.orderings
.iter()
.map(|list| list.values().slice(span_start, span_len))
.collect();
let ordering_rows = self
.ordering
.as_ref()
.map(|ordering| ordering.convert_columns(&orderings))
.transpose()?;
let batch_idx = self.retain_batch(RetainedNavigationBatch {
value,
symbol,
orderings,
ordering_rows,
live_rows,
})?;
for (row_idx, &group_id) in group_indices.iter().enumerate() {
if state_lists.values.is_null(row_idx) {
continue;
}
let start = (offsets[row_idx] as usize - span_start) as u32;
let end = (offsets[row_idx + 1] as usize - span_start) as u32;
if start == end {
continue;
}
let rows = &mut self.group_row_refs[group_id];
let capacity = rows.capacity();
rows.extend((start..end).map(|row| (batch_idx, row)));
self.row_refs_capacity += rows.capacity() - capacity;
}
return Ok(());
}
for (row_idx, &group_id) in group_indices.iter().enumerate() {
if !state_lists.row_is_present(row_idx)? {
continue;
}
let (value_state, symbol_state, orderings) =
state_lists.row_slices(row_idx)?;
if value_state.is_empty() {
continue;
}
let live_rows = value_state.len();
let last_row = last_navigation_row_index(live_rows)?;
let ordering_rows = self
.ordering
.as_ref()
.map(|ordering| ordering.convert_columns(&orderings))
.transpose()?;
let batch_idx = self.retain_batch(RetainedNavigationBatch {
value: value_state,
symbol: symbol_state,
orderings,
ordering_rows,
live_rows,
})?;
let rows = &mut self.group_row_refs[group_id];
let capacity = rows.capacity();
rows.extend((0..=last_row).map(|row| (batch_idx, row)));
self.row_refs_capacity += rows.capacity() - capacity;
}
Ok(())
}
fn convert_to_state(
&self,
values: &[ArrayRef],
opt_filter: Option<&BooleanArray>,
) -> Result<Vec<ArrayRef>> {
let batch_args = decode_navigation_batch_args(
self.kind,
self.fixed_arg_count,
&self.data_type,
values,
self.ordering.as_ref(),
self.kind.aggregate_name(),
)?;
let mut offsets = Vec::with_capacity(batch_args.batch_len + 1);
let mut selected_rows = Vec::with_capacity(batch_args.batch_len);
offsets.push(0_i32);
for row_idx in 0..batch_args.batch_len {
if row_passes_filter(opt_filter, row_idx) {
selected_rows.push((0, row_idx));
}
offsets.push(navigation_list_offset(selected_rows.len())?);
}
let offsets = OffsetBuffer::new(ScalarBuffer::from(offsets));
let values = Self::list_state_array_for_selected_rows(
&self.data_type,
&batch_args.value_array,
&selected_rows,
&offsets,
)?;
let mut state = Vec::with_capacity(
base_state_fields(self.kind) + batch_args.ordering_arrays.len(),
);
state.push(values);
if let Some(ref symbol_mask) = batch_args.symbol_mask {
let symbol_matched = Self::list_state_array_for_selected_rows(
&DataType::Boolean,
symbol_mask,
&selected_rows,
&offsets,
)?;
state.push(symbol_matched);
}
if let Some(ordering) = &self.ordering {
for (ordering_array, data_type) in
batch_args.ordering_arrays.iter().zip(ordering.data_types())
{
state.push(Self::list_state_array_for_selected_rows(
data_type,
ordering_array,
&selected_rows,
&offsets,
)?);
}
}
Ok(state)
}
fn size(&self) -> usize {
let vector_storage_size = self.group_row_refs.capacity()
* size_of::<Vec<(u32, u32)>>()
+ self.batches.capacity() * size_of::<Option<RetainedNavigationBatch>>()
+ self.free_batch_indices.capacity() * size_of::<u32>();
let ordering_meta_size = self
.ordering
.as_ref()
.map_or(0, NavigationOrdering::heap_size);
size_of_val(self)
+ vector_storage_size
+ self.row_refs_capacity * size_of::<(u32, u32)>()
+ self.batch_buffers.memory_usage()
+ self.batch_array_overhead
+ ordering_meta_size
+ (self.default_value.size() - size_of_val(&self.default_value))
+ (self.data_type.size() - size_of_val(&self.data_type))
}
}
#[cfg(test)]
mod tests {
use super::super::accumulator::NavigationAccumulator;
use super::*;
use crate::functions::navigation_common::test_support::{
assert_run_values, custom_run_array,
};
use datafusion::arrow::array::{Int32Array, Int64Array};
use datafusion::logical_expr::Accumulator;
#[test]
fn navigation_accumulators_preserve_custom_run_defaults() -> Result<()> {
for nullable in [false, true] {
let data = custom_run_array(nullable);
let data_type = data.data_type().clone();
let values: Vec<ArrayRef> = vec![
data,
Arc::new(Int64Array::from(vec![1; 2])),
Arc::new(Int32Array::from(vec![7; 2])),
Arc::new(BooleanArray::from(vec![true; 2])),
Arc::new(BooleanArray::from(vec![true; 2])),
];
let default = ScalarValue::Int32(Some(7));
let mut grouped = NavigationGroupsAccumulator::try_new(
NavigationKind::Prev,
data_type.clone(),
1,
default.clone(),
)?;
grouped.update_batch(&values, &[0, 0], None, 2)?;
let result = grouped.evaluate(EmitTo::All)?;
assert_eq!(result.data_type(), &data_type);
assert_run_values(&result, &[Some(10), Some(7)]);
let mut single = NavigationAccumulator::try_new(
NavigationKind::Prev,
data_type.clone(),
1,
default,
)?;
let empty = single.evaluate()?;
assert_eq!(empty.data_type(), data_type);
assert_run_values(&empty.to_array()?, &[Some(7)]);
single.update_batch(&values)?;
let selected = single.evaluate()?;
assert_eq!(selected.data_type(), data_type);
assert_run_values(&selected.to_array()?, &[Some(10)]);
}
Ok(())
}
}