use std::cmp::Ordering;
use std::sync::Arc;
use arrow::array::ArrayRef;
use arrow::compute::SortOptions;
use arrow_ord::partition::partition;
use datafusion_common::utils::{compare_rows, get_row_at_idx};
use datafusion_common::{Result, ScalarValue};
use datafusion_execution::memory_pool::proxy::VecAllocExt;
use datafusion_expr::EmitTo;
#[derive(Debug)]
pub struct GroupClusteringPartial {
state: State,
grouping_indices: Vec<usize>,
}
#[derive(Debug, Default, PartialEq)]
enum State {
#[default]
Taken,
Start,
InProgress {
current_run_start: usize,
group_key: Vec<ScalarValue>,
current: usize,
},
Complete,
}
impl State {
fn heap_size(&self) -> usize {
match self {
State::Taken => 0,
State::Start => 0,
State::InProgress { group_key, .. } => group_key
.iter()
.map(|scalar_value| scalar_value.size())
.sum(),
State::Complete => 0,
}
}
}
impl GroupClusteringPartial {
pub fn try_new(grouping_indices: Vec<usize>) -> Result<Self> {
debug_assert!(!grouping_indices.is_empty());
Ok(Self {
state: State::Start,
grouping_indices,
})
}
fn compute_group_keys(&mut self, group_values: &[ArrayRef]) -> Vec<ArrayRef> {
self.grouping_indices
.iter()
.map(|&idx| Arc::clone(&group_values[idx]))
.collect()
}
pub fn emit_to(&self) -> Option<EmitTo> {
match &self.state {
State::Taken => unreachable!("State previously taken"),
State::Start => None,
State::InProgress {
current_run_start, ..
} => {
if *current_run_start == 0 {
None
} else {
Some(EmitTo::First(*current_run_start))
}
}
State::Complete => Some(EmitTo::All),
}
}
pub fn remove_groups(&mut self, n: usize) {
match &mut self.state {
State::Taken => unreachable!("State previously taken"),
State::Start => panic!("invalid state: start"),
State::InProgress {
current_run_start,
current,
group_key: _,
} => {
assert!(*current >= n);
*current -= n;
assert!(*current_run_start >= n);
*current_run_start -= n;
}
State::Complete => panic!("invalid state: complete"),
}
}
pub fn input_done(&mut self) {
self.state = match self.state {
State::Taken => unreachable!("State previously taken"),
_ => State::Complete,
};
}
pub fn reset(&mut self) {
self.state = State::Start;
}
fn updated_group_key(
current_run_start: usize,
group_key: Option<Vec<ScalarValue>>,
range_current_run_start: usize,
range_group_key: Vec<ScalarValue>,
) -> Result<(usize, Vec<ScalarValue>)> {
if let Some(group_key) = group_key {
let sort_options = vec![SortOptions::new(false, false); group_key.len()];
let ordering = compare_rows(&group_key, &range_group_key, &sort_options)?;
if ordering == Ordering::Equal {
return Ok((current_run_start, group_key));
}
}
Ok((range_current_run_start, range_group_key))
}
pub fn new_groups(
&mut self,
batch_group_values: &[ArrayRef],
group_indices: &[usize],
total_num_groups: usize,
) -> Result<()> {
assert!(total_num_groups > 0);
assert!(!batch_group_values.is_empty());
let max_group_index = total_num_groups - 1;
let (current_run_start, group_key) = match std::mem::take(&mut self.state) {
State::Taken => unreachable!("State previously taken"),
State::Start => (0, None),
State::InProgress {
current_run_start,
group_key,
..
} => (current_run_start, Some(group_key)),
State::Complete => {
panic!("Saw new group after the end of input");
}
};
let group_keys = self.compute_group_keys(batch_group_values);
let ranges = partition(&group_keys)?.ranges();
let last_range = ranges.last().unwrap();
let range_current_run_start = group_indices[last_range.start];
let range_group_key = get_row_at_idx(&group_keys, last_range.start)?;
let (current_run_start, group_key) = if last_range.start == 0 {
Self::updated_group_key(
current_run_start,
group_key,
range_current_run_start,
range_group_key,
)?
} else {
(range_current_run_start, range_group_key)
};
self.state = State::InProgress {
current_run_start,
current: max_group_index,
group_key,
};
Ok(())
}
pub(crate) fn heap_size(&self) -> usize {
self.grouping_indices.allocated_size() + self.state.heap_size()
}
}
#[cfg(test)]
mod tests {
use super::*;
use arrow::array::Int32Array;
#[rstest::rstest]
#[case::sorted([1, 2, 3, 4])]
#[case::clustered([3, 1, 4, 2])]
fn test_group_clustering_partial(#[case] keys: [i32; 4]) -> Result<()> {
let [first, second, third, fourth] = keys;
let grouping_indices = vec![0];
let mut group_clustering = GroupClusteringPartial::try_new(grouping_indices)?;
let batch_group_values: Vec<ArrayRef> = vec![
Arc::new(Int32Array::from(vec![first, second, third])),
Arc::new(Int32Array::from(vec![2, 1, 3])),
];
let group_indices = vec![0, 1, 2];
let total_num_groups = 3;
group_clustering.new_groups(
&batch_group_values,
&group_indices,
total_num_groups,
)?;
assert_eq!(
group_clustering.state,
State::InProgress {
current_run_start: 2,
group_key: vec![ScalarValue::Int32(Some(third))],
current: 2
}
);
assert_eq!(group_clustering.emit_to(), Some(EmitTo::First(2)));
let batch_group_values: Vec<ArrayRef> = vec![
Arc::new(Int32Array::from(vec![third, third, third])),
Arc::new(Int32Array::from(vec![2, 1, 7])),
];
let group_indices = vec![3, 4, 5];
let total_num_groups = 6;
group_clustering.new_groups(
&batch_group_values,
&group_indices,
total_num_groups,
)?;
assert_eq!(
group_clustering.state,
State::InProgress {
current_run_start: 2,
group_key: vec![ScalarValue::Int32(Some(third))],
current: 5
}
);
assert_eq!(group_clustering.emit_to(), Some(EmitTo::First(2)));
let batch_group_values: Vec<ArrayRef> = vec![
Arc::new(Int32Array::from(vec![fourth, fourth, fourth])),
Arc::new(Int32Array::from(vec![1, 2, 3])),
];
let group_indices = vec![6, 7, 8];
let total_num_groups = 9;
group_clustering.new_groups(
&batch_group_values,
&group_indices,
total_num_groups,
)?;
assert_eq!(
group_clustering.state,
State::InProgress {
current_run_start: 6,
group_key: vec![ScalarValue::Int32(Some(fourth))],
current: 8
}
);
assert_eq!(group_clustering.emit_to(), Some(EmitTo::First(6)));
Ok(())
}
}