use arrow::{
array::{Array, AsArray},
compute::{
FilterBuilder, interleave_record_batch, prep_null_mask_filter, take_record_batch,
},
row::{RowConverter, Rows, SortField},
};
use datafusion_expr::{ColumnarValue, Operator};
use std::borrow::Borrow;
use std::mem::size_of;
use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};
use std::{cmp::Ordering, collections::BinaryHeap, sync::Arc};
use super::metrics::{
BaselineMetrics, Count, ExecutionPlanMetricsSet, MetricBuilder, MetricCategory,
RecordOutput,
};
use crate::{SendableRecordBatchStream, stream::RecordBatchStreamAdapter};
use arrow::array::{ArrayRef, RecordBatch, UInt32Array, UInt64Array};
use arrow::datatypes::{FieldRef, Schema, SchemaRef};
use datafusion_common::utils::memory::RecordBatchMemoryTracker;
use datafusion_common::{
HashMap, Result, ScalarValue, internal_datafusion_err, internal_err,
};
use datafusion_execution::{
memory_pool::{MemoryConsumer, MemoryReservation, proxy::VecAllocExt},
runtime_env::RuntimeEnv,
};
use datafusion_physical_expr::{
PhysicalExpr,
expressions::{BinaryExpr, DynamicFilterPhysicalExpr, is_not_null, is_null, lit},
};
use datafusion_physical_expr_common::sort_expr::{LexOrdering, PhysicalSortExpr};
use parking_lot::RwLock;
pub struct TopK {
schema: SchemaRef,
metrics: TopKMetrics,
reservation: MemoryReservation,
batch_size: usize,
expr: LexOrdering,
row_converter: RowConverter,
scratch_rows: Rows,
heap: TopKHeap,
common_sort_prefix_converter: Option<RowConverter>,
common_sort_prefix: Arc<[PhysicalSortExpr]>,
filter: Arc<RwLock<TopKDynamicFilters>>,
pub(crate) finished: bool,
}
#[derive(Debug)]
pub struct TopKDynamicFilters {
shared_threshold: Option<TopKThreshold>,
expr: Arc<DynamicFilterPhysicalExpr>,
remaining_topk_emitters: AtomicUsize,
}
#[derive(Debug, Clone)]
struct TopKThreshold {
full_sort_key_row: Vec<u8>,
common_prefix_row: Option<Vec<u8>>,
}
impl TopKThreshold {
fn new(full_sort_key_row: Vec<u8>, common_prefix_row: Option<Vec<u8>>) -> Self {
Self {
full_sort_key_row,
common_prefix_row,
}
}
fn full_sort_key_row(&self) -> &[u8] {
self.full_sort_key_row.as_slice()
}
fn common_prefix_row(&self) -> Option<&[u8]> {
self.common_prefix_row.as_deref()
}
fn is_more_selective_than(&self, current: &Self) -> bool {
self.full_sort_key_row() < current.full_sort_key_row()
}
}
#[derive(Clone, Copy)]
struct TopKHeapBoundaryRow<'a> {
row: &'a TopKRow,
}
impl<'a> TopKHeapBoundaryRow<'a> {
fn new(row: &'a TopKRow) -> Self {
Self { row }
}
fn full_sort_key_row(&self) -> &[u8] {
self.row.row()
}
fn is_more_selective_than(&self, current: Option<&TopKThreshold>) -> bool {
current
.map(|current| self.full_sort_key_row() < current.full_sort_key_row())
.unwrap_or(true)
}
}
#[derive(Clone, Copy)]
struct TopKHeapBoundary<'a> {
row: &'a TopKRow,
batch: &'a RecordBatch,
}
impl<'a> TopKHeapBoundary<'a> {
fn new(row: &'a TopKRow, batch: &'a RecordBatch) -> Self {
Self { row, batch }
}
fn threshold_values(
&self,
sort_exprs: &[PhysicalSortExpr],
) -> Result<Vec<ScalarValue>> {
let mut scalar_values = Vec::with_capacity(sort_exprs.len());
let row = self.batch.slice(self.row.index, 1);
for sort_expr in sort_exprs {
let value = sort_expr.expr.evaluate(&row)?;
let scalar = match value {
ColumnarValue::Scalar(scalar) => scalar,
ColumnarValue::Array(array) if array.len() == 1 => {
ScalarValue::try_from_array(&array, 0)?
}
array => {
return internal_err!("Expected a scalar value, got {:?}", array);
}
};
scalar_values.push(scalar);
}
Ok(scalar_values)
}
fn threshold(&self, common_prefix_row: Option<Vec<u8>>) -> TopKThreshold {
TopKThreshold::new(self.row.row().to_vec(), common_prefix_row)
}
}
impl TopKDynamicFilters {
pub fn new(expr: Arc<DynamicFilterPhysicalExpr>) -> Self {
Self::new_with_topk_emitter_count(expr, 1)
}
pub fn new_with_topk_emitter_count(
expr: Arc<DynamicFilterPhysicalExpr>,
topk_emitter_count: usize,
) -> Self {
debug_assert!(topk_emitter_count > 0);
Self {
shared_threshold: None,
expr,
remaining_topk_emitters: AtomicUsize::new(topk_emitter_count),
}
}
pub fn expr(&self) -> Arc<DynamicFilterPhysicalExpr> {
Arc::clone(&self.expr)
}
fn mark_topk_emitted(&self) {
let previous = self
.remaining_topk_emitters
.try_update(
AtomicOrdering::AcqRel,
AtomicOrdering::Acquire,
|remaining| remaining.checked_sub(1),
)
.unwrap_or(0);
debug_assert!(
previous > 0,
"TopK dynamic filter emitter completed more times than expected"
);
if previous == 1 {
self.expr.mark_complete();
}
}
}
const ESTIMATED_BYTES_PER_ROW: usize = 20;
pub(crate) fn build_sort_fields(
ordering: &[PhysicalSortExpr],
schema: &SchemaRef,
) -> Result<Vec<SortField>> {
ordering
.iter()
.map(|e| {
Ok(SortField::new_with_options(
e.expr.data_type(schema)?,
e.options,
))
})
.collect::<Result<_>>()
}
impl TopK {
#[expect(clippy::too_many_arguments)]
#[expect(clippy::needless_pass_by_value)]
pub fn try_new(
partition_id: usize,
schema: SchemaRef,
common_sort_prefix: Vec<PhysicalSortExpr>,
expr: LexOrdering,
k: usize,
batch_size: usize,
runtime: Arc<RuntimeEnv>,
metrics: &ExecutionPlanMetricsSet,
filter: Arc<RwLock<TopKDynamicFilters>>,
) -> Result<Self> {
let reservation = MemoryConsumer::new(format!("TopK[{partition_id}]"))
.register(&runtime.memory_pool);
let sort_fields = build_sort_fields(&expr, &schema)?;
let row_converter = RowConverter::new(sort_fields)?;
let scratch_rows =
row_converter.empty_rows(batch_size, ESTIMATED_BYTES_PER_ROW * batch_size);
let common_prefix_row_converter = if common_sort_prefix.is_empty() {
None
} else {
let input_sort_fields = build_sort_fields(&common_sort_prefix, &schema)?;
Some(RowConverter::new(input_sort_fields)?)
};
Ok(Self {
schema: Arc::clone(&schema),
metrics: TopKMetrics::new(metrics, partition_id),
reservation,
batch_size,
expr,
row_converter,
scratch_rows,
heap: TopKHeap::new(k),
common_sort_prefix_converter: common_prefix_row_converter,
common_sort_prefix: Arc::from(common_sort_prefix),
finished: false,
filter,
})
}
pub fn insert_batch(&mut self, batch: RecordBatch) -> Result<()> {
let elapsed_compute = self.metrics.baseline.elapsed_compute().clone();
let _timer = elapsed_compute.timer();
let mut selected_rows = None;
let filter = self.filter.read().expr.current()?;
let filtered = filter.evaluate(&batch)?;
let num_rows = batch.num_rows();
let array = filtered.into_array(num_rows)?;
let mut filter = array.as_boolean().clone();
if !filter.has_true() {
self.attempt_early_completion(&batch)?;
return Ok(());
}
let mut sort_keys: Vec<ArrayRef> = self
.expr
.iter()
.map(|expr| {
let value = expr.expr.evaluate(&batch)?;
value.into_array(num_rows)
})
.collect::<Result<Vec<_>>>()?;
if filter.null_count() > 0 || filter.has_false() {
if filter.nulls().is_some() {
filter = prep_null_mask_filter(&filter);
}
let filter_predicate = FilterBuilder::new(&filter);
let filter_predicate = if sort_keys.len() > 1 {
filter_predicate.optimize().build()
} else {
filter_predicate.build()
};
selected_rows = Some(filter);
sort_keys = sort_keys
.iter()
.map(|key| filter_predicate.filter(key).map_err(|x| x.into()))
.collect::<Result<Vec<_>>>()?;
}
let rows = &mut self.scratch_rows;
rows.clear();
self.row_converter.append(rows, &sort_keys)?;
let mut batch_entry = self.heap.register_batch(batch);
let replacements = match selected_rows {
Some(filter) => {
self.find_new_topk_items(filter.values().set_indices(), &mut batch_entry)
}
None => self.find_new_topk_items(0..sort_keys[0].len(), &mut batch_entry),
};
if replacements > 0 {
self.metrics.row_replacements.add(replacements);
let last_row_prefix = self.last_row_common_prefix(&batch_entry.batch)?;
self.heap.insert_batch_entry(batch_entry);
self.heap.maybe_compact()?;
self.reservation.try_resize(self.size())?;
self.finish_if_prefix_past_boundary(last_row_prefix.as_ref())?;
self.update_filter()?;
} else {
self.attempt_early_completion(&batch_entry.batch)?;
}
Ok(())
}
fn find_new_topk_items(
&mut self,
items: impl Iterator<Item = usize>,
batch_entry: &mut RecordBatchEntry,
) -> usize {
let mut replacements = 0;
let rows = &mut self.scratch_rows;
for (index, row) in items.zip(rows.iter()) {
match self.heap.max() {
Some(max_row) if row.as_ref() >= max_row.row() => {}
None | Some(_) => {
self.heap.add(batch_entry, row, index);
replacements += 1;
}
}
}
replacements
}
fn current_heap_boundary_row(&self) -> Option<TopKHeapBoundaryRow<'_>> {
self.heap.max().map(TopKHeapBoundaryRow::new)
}
fn current_heap_boundary(&self) -> Result<Option<TopKHeapBoundary<'_>>> {
let Some(row) = self.heap.max() else {
return Ok(None);
};
self.heap_boundary(row).map(Some)
}
fn heap_boundary<'a>(&'a self, row: &'a TopKRow) -> Result<TopKHeapBoundary<'a>> {
let batch_entry = self
.heap
.store
.get(row.batch_id)
.ok_or_else(|| internal_datafusion_err!("Invalid batch ID in TopKRow"))?;
Ok(TopKHeapBoundary::new(row, &batch_entry.batch))
}
fn update_filter(&mut self) -> Result<()> {
let Some(boundary_row) = self.current_heap_boundary_row() else {
return Ok(());
};
let needs_update = {
let filter = self.filter.read();
boundary_row.is_more_selective_than(filter.shared_threshold.as_ref())
};
if !needs_update {
return Ok(());
}
let boundary = self.heap_boundary(boundary_row.row)?;
let thresholds = boundary.threshold_values(&self.expr)?;
let predicate = Self::build_filter_expression(&self.expr, &thresholds)?;
let new_threshold =
boundary.threshold(self.encode_topk_common_prefix_row(boundary)?);
let mut filter = self.filter.write();
let still_needs_update = filter
.shared_threshold
.as_ref()
.map(|current| new_threshold.is_more_selective_than(current))
.unwrap_or(true);
if !still_needs_update {
return Ok(());
}
filter.shared_threshold = Some(new_threshold);
if let Some(pred) = predicate
&& !pred.eq(&lit(true))
{
filter.expr.update(pred)?;
}
Ok(())
}
fn build_filter_expression(
sort_exprs: &[PhysicalSortExpr],
thresholds: &[ScalarValue],
) -> Result<Option<Arc<dyn PhysicalExpr>>> {
let mut filters: Vec<Arc<dyn PhysicalExpr>> =
Vec::with_capacity(thresholds.len());
let mut prev_sort_expr: Option<Arc<dyn PhysicalExpr>> = None;
for (sort_expr, value) in sort_exprs.iter().zip(thresholds.iter()) {
if value.data_type().is_nested() {
if let Some(prev) = prev_sort_expr.take() {
filters.push(prev);
}
break;
}
let op = if sort_expr.options.descending {
Operator::Gt
} else {
Operator::Lt
};
let value_null = value.is_null();
let comparison = Arc::new(BinaryExpr::new(
Arc::clone(&sort_expr.expr),
op,
lit(value.clone()),
));
let comparison_with_null = match (sort_expr.options.nulls_first, value_null) {
(true, true) => lit(false),
(true, false) => Arc::new(BinaryExpr::new(
is_null(Arc::clone(&sort_expr.expr))?,
Operator::Or,
comparison,
)),
(false, true) => is_not_null(Arc::clone(&sort_expr.expr))?,
(false, false) => comparison,
};
let mut eq_expr = Arc::new(BinaryExpr::new(
Arc::clone(&sort_expr.expr),
Operator::Eq,
lit(value.clone()),
));
if value_null {
eq_expr = Arc::new(BinaryExpr::new(
is_null(Arc::clone(&sort_expr.expr))?,
Operator::Or,
eq_expr,
));
}
match prev_sort_expr.take() {
None => {
prev_sort_expr = Some(eq_expr);
filters.push(comparison_with_null);
}
Some(p) => {
filters.push(Arc::new(BinaryExpr::new(
Arc::clone(&p),
Operator::And,
comparison_with_null,
)));
prev_sort_expr =
Some(Arc::new(BinaryExpr::new(p, Operator::And, eq_expr)));
}
}
}
let dynamic_predicate = filters
.into_iter()
.reduce(|a, b| Arc::new(BinaryExpr::new(a, Operator::Or, b)));
Ok(dynamic_predicate)
}
fn attempt_early_completion(&mut self, batch: &RecordBatch) -> Result<()> {
let last_row_prefix = self.last_row_common_prefix(batch)?;
self.finish_if_prefix_past_boundary(last_row_prefix.as_ref())
}
fn last_row_common_prefix(&self, batch: &RecordBatch) -> Result<Option<Rows>> {
if batch.num_rows() == 0 {
return Ok(None);
}
let Some(prefix_converter) = &self.common_sort_prefix_converter else {
return Ok(None);
};
let last_row_idx = batch.num_rows() - 1;
let mut batch_prefix_scratch =
prefix_converter.empty_rows(1, ESTIMATED_BYTES_PER_ROW);
self.append_common_prefix_row(
prefix_converter,
batch,
last_row_idx,
&mut batch_prefix_scratch,
)?;
Ok(Some(batch_prefix_scratch))
}
fn finish_if_prefix_past_boundary(
&mut self,
last_row_prefix: Option<&Rows>,
) -> Result<()> {
let Some(batch_prefix_rows) = last_row_prefix else {
return Ok(());
};
let batch_common_prefix_row = batch_prefix_rows.row(0);
let batch_common_prefix = batch_common_prefix_row.as_ref();
let finished_by_shared_threshold = self
.filter
.read()
.shared_threshold
.as_ref()
.and_then(TopKThreshold::common_prefix_row)
.map(|common_prefix_row| batch_common_prefix > common_prefix_row)
.unwrap_or(false);
if finished_by_shared_threshold {
self.finished = true;
return Ok(());
}
let Some(boundary) = self.current_heap_boundary()? else {
return Ok(());
};
if self.batch_prefix_exceeds_heap_boundary(batch_common_prefix, boundary)? {
self.finished = true;
}
Ok(())
}
fn batch_prefix_exceeds_heap_boundary(
&self,
batch_common_prefix: &[u8],
boundary: TopKHeapBoundary<'_>,
) -> Result<bool> {
let Some(heap_common_prefix_row) =
self.encode_topk_common_prefix_row(boundary)?
else {
return Ok(false);
};
Ok(batch_common_prefix > heap_common_prefix_row.as_slice())
}
fn encode_topk_common_prefix_row(
&self,
boundary: TopKHeapBoundary<'_>,
) -> Result<Option<Vec<u8>>> {
let Some(prefix_converter) = &self.common_sort_prefix_converter else {
return Ok(None);
};
let mut scratch = prefix_converter.empty_rows(1, ESTIMATED_BYTES_PER_ROW);
self.append_common_prefix_row(
prefix_converter,
boundary.batch,
boundary.row.index,
&mut scratch,
)?;
Ok(Some(scratch.row(0).as_ref().to_vec()))
}
fn append_common_prefix_row(
&self,
prefix_converter: &RowConverter,
batch: &RecordBatch,
row_idx: usize,
scratch: &mut Rows,
) -> Result<()> {
let row = batch.slice(row_idx, 1);
let prefix_columns: Vec<ArrayRef> = self
.common_sort_prefix
.iter()
.map(|expr| expr.expr.evaluate(&row)?.into_array(1))
.collect::<Result<_>>()?;
prefix_converter.append(scratch, &prefix_columns)?;
Ok(())
}
pub fn emit(self) -> Result<SendableRecordBatchStream> {
let Self {
schema,
metrics,
reservation: _,
batch_size,
expr: _,
row_converter: _,
scratch_rows: _,
mut heap,
common_sort_prefix_converter: _,
common_sort_prefix: _,
finished: _,
filter,
} = self;
let _timer = metrics.baseline.elapsed_compute().timer();
filter.read().mark_topk_emitted();
let mut batches = vec![];
if let Some(mut batch) = heap.emit()? {
loop {
if batch.num_rows() <= batch_size {
(&batch).record_output(&metrics.baseline);
batches.push(Ok(batch));
break;
} else {
let head = batch.slice(0, batch_size);
(&head).record_output(&metrics.baseline);
batches.push(Ok(head));
let remaining_length = batch.num_rows() - batch_size;
batch = batch.slice(batch_size, remaining_length);
}
}
}
Ok(Box::pin(RecordBatchStreamAdapter::new(
schema,
futures::stream::iter(batches),
)))
}
fn size(&self) -> usize {
size_of::<Self>()
+ self.row_converter.size()
+ self
.common_sort_prefix_converter
.as_ref()
.map_or(0, RowConverter::size)
+ self.scratch_rows.size()
+ self.heap.size()
}
}
struct TopKMetrics {
pub baseline: BaselineMetrics,
pub row_replacements: Count,
}
impl TopKMetrics {
fn new(metrics: &ExecutionPlanMetricsSet, partition: usize) -> Self {
Self {
baseline: BaselineMetrics::new(metrics, partition),
row_replacements: MetricBuilder::new(metrics)
.with_category(MetricCategory::Rows)
.counter("row_replacements", partition),
}
}
}
const STORE_COMPACTION_RATIO: usize = 2;
struct TopKHeap {
k: usize,
inner: BinaryHeap<TopKRow>,
store: RecordBatchStore,
owned_bytes: usize,
}
impl TopKHeap {
fn new(k: usize) -> Self {
assert!(k > 0);
Self {
k,
inner: BinaryHeap::new(),
store: RecordBatchStore::new(),
owned_bytes: 0,
}
}
pub fn register_batch(&mut self, batch: RecordBatch) -> RecordBatchEntry {
self.store.register(batch)
}
pub fn insert_batch_entry(&mut self, entry: RecordBatchEntry) {
self.store.insert(entry)
}
fn max(&self) -> Option<&TopKRow> {
if self.inner.len() < self.k {
None
} else {
self.inner.peek()
}
}
fn add(
&mut self,
batch_entry: &mut RecordBatchEntry,
row: impl AsRef<[u8]>,
index: usize,
) {
let batch_id = batch_entry.id;
batch_entry.uses += 1;
assert!(self.inner.len() <= self.k);
let row = row.as_ref();
if self.inner.len() == self.k {
let mut prev_min = self.inner.peek_mut().unwrap();
if prev_min.batch_id == batch_entry.id {
batch_entry.uses -= 1;
} else {
self.store.unuse(prev_min.batch_id);
}
self.owned_bytes -= prev_min.owned_size();
prev_min.replace_with(row, batch_id, index);
self.owned_bytes += prev_min.owned_size();
} else {
let new_row = TopKRow::new(row, batch_id, index);
self.owned_bytes += new_row.owned_size();
self.inner.push(new_row);
}
}
pub fn emit(&mut self) -> Result<Option<RecordBatch>> {
Ok(self.emit_with_state()?.0)
}
fn emit_with_state(&mut self) -> Result<(Option<RecordBatch>, Vec<TopKRow>)> {
let topk_rows = std::mem::take(&mut self.inner).into_sorted_vec();
if self.store.is_empty() {
return Ok((None, topk_rows));
}
let (record_batches, batch_id_array_pos) = self.store.positional();
let indices: Vec<_> = topk_rows
.iter()
.map(|k| (batch_id_array_pos[&k.batch_id], k.index))
.collect();
let new_batch = interleave_record_batch(&record_batches, &indices)?;
Ok((Some(new_batch), topk_rows))
}
pub fn maybe_compact(&mut self) -> Result<()> {
if self.store.len() <= 1 {
return Ok(());
}
let total_rows = self.store.total_rows;
let num_rows = self.inner.len();
if total_rows <= num_rows * STORE_COMPACTION_RATIO {
return Ok(());
}
let (new_batch, mut topk_rows) = self.emit_with_state()?;
let Some(new_batch) = new_batch else {
return Ok(());
};
self.store.clear();
let mut batch_entry = self.register_batch(new_batch);
batch_entry.uses = num_rows;
for (i, topk_row) in topk_rows.iter_mut().enumerate() {
topk_row.batch_id = batch_entry.id;
topk_row.index = i;
}
self.insert_batch_entry(batch_entry);
self.inner = BinaryHeap::from(topk_rows);
Ok(())
}
fn size(&self) -> usize {
size_of::<Self>()
+ (self.inner.capacity() * size_of::<TopKRow>())
+ self.store.size()
+ self.owned_bytes
}
}
#[derive(Debug, PartialEq)]
struct TopKRow {
row: Vec<u8>,
batch_id: u32,
index: usize,
}
impl TopKRow {
fn new(row: impl AsRef<[u8]>, batch_id: u32, index: usize) -> Self {
Self {
row: row.as_ref().to_vec(),
batch_id,
index,
}
}
fn replace_with(&mut self, new_row: impl AsRef<[u8]>, batch_id: u32, index: usize) {
self.row.clear();
self.row.extend_from_slice(new_row.as_ref());
self.batch_id = batch_id;
self.index = index;
}
fn owned_size(&self) -> usize {
self.row.capacity()
}
fn row(&self) -> &[u8] {
self.row.as_slice()
}
}
impl Eq for TopKRow {}
impl PartialOrd for TopKRow {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for TopKRow {
fn cmp(&self, other: &Self) -> Ordering {
self.row.cmp(&other.row)
}
}
#[derive(Debug)]
struct RecordBatchEntry {
id: u32,
batch: RecordBatch,
uses: usize,
}
#[derive(Debug)]
struct RecordBatchStore {
next_id: u32,
batches: HashMap<u32, RecordBatchEntry>,
batch_memory: RecordBatchMemoryTracker,
batches_size: usize,
total_rows: usize,
}
impl RecordBatchStore {
fn new() -> Self {
Self {
next_id: 0,
batches: HashMap::new(),
batch_memory: RecordBatchMemoryTracker::new(),
batches_size: 0,
total_rows: 0,
}
}
pub fn register(&mut self, batch: RecordBatch) -> RecordBatchEntry {
let id = self.next_id;
self.next_id += 1;
RecordBatchEntry { id, batch, uses: 0 }
}
fn next_batch_id(&self) -> u32 {
self.next_id
}
fn pending(&self) -> PendingEntry {
PendingEntry {
id: self.next_batch_id(),
uses: 0,
}
}
fn release(&mut self, pending: &mut PendingEntry, id: u32) {
if id == pending.id {
pending.uses -= 1;
} else {
self.unuse(id);
}
}
pub fn insert(&mut self, entry: RecordBatchEntry) {
if entry.uses > 0 {
self.batches_size += self.batch_memory.count_batch(&entry.batch);
self.total_rows += entry.batch.num_rows();
self.batches.insert(entry.id, entry);
}
}
#[expect(clippy::needless_pass_by_value)]
fn insert_rows(
&mut self,
batch: &RecordBatch,
rows: &[u32],
pending: PendingEntry,
) -> Result<()> {
let PendingEntry { id, uses } = pending;
if uses == 0 {
return Ok(());
}
let gather_idx = UInt32Array::from_iter_values(rows.iter().copied());
let mut entry = self.register(take_record_batch(batch, &gather_idx)?);
debug_assert_eq!(
entry.id, id,
"the id handed to the slots must be the id the gather got"
);
entry.uses = uses;
self.insert(entry);
Ok(())
}
fn clear(&mut self) {
self.batches.clear();
self.batch_memory = RecordBatchMemoryTracker::new();
self.batches_size = 0;
self.total_rows = 0;
}
fn get(&self, id: u32) -> Option<&RecordBatchEntry> {
self.batches.get(&id)
}
fn len(&self) -> usize {
self.batches.len()
}
fn positional(&self) -> (Vec<&RecordBatch>, HashMap<u32, usize>) {
let mut batches = Vec::with_capacity(self.batches.len());
let mut positions = HashMap::with_capacity(self.batches.len());
for (pos, (batch_id, entry)) in self.batches.iter().enumerate() {
batches.push(&entry.batch);
positions.insert(*batch_id, pos);
}
(batches, positions)
}
fn is_empty(&self) -> bool {
self.batches.is_empty()
}
pub fn unuse(&mut self, id: u32) {
let remove = if let Some(batch_entry) = self.batches.get_mut(&id) {
batch_entry.uses = batch_entry.uses.checked_sub(1).expect("underflow");
batch_entry.uses == 0
} else {
panic!("No entry for id {id}");
};
if remove {
let old_entry = self.batches.remove(&id).unwrap();
self.batches_size = self
.batches_size
.checked_sub(self.batch_memory.uncount_batch(&old_entry.batch))
.unwrap();
self.total_rows = self
.total_rows
.checked_sub(old_entry.batch.num_rows())
.unwrap();
}
}
pub fn size(&self) -> usize {
size_of::<Self>()
+ self.batches.capacity() * (size_of::<u32>() + size_of::<RecordBatchEntry>())
+ self.batches_size
}
fn compact<P: StoreSlots>(
&mut self,
partitions: &mut HashMap<Vec<u8>, P>,
live_slots: usize,
batch_size: usize,
) -> Result<()> {
if self.total_rows <= live_slots * STORE_COMPACTION_RATIO {
return Ok(());
}
let first_id = self.next_batch_id();
#[cfg(debug_assertions)]
let mut walked: Vec<StoreRef> = Vec::with_capacity(live_slots);
let chunks = {
let (old, array_pos) = self.positional();
let mut coords: Vec<(usize, usize)> = Vec::with_capacity(live_slots);
for at in partitions.values().flat_map(P::store_rows) {
let pos = *array_pos
.get(&at.batch_id)
.expect("a live slot's batch_id is present in the store");
coords.push((pos, at.row as usize));
#[cfg(debug_assertions)]
walked.push(at);
}
debug_assert_eq!(
coords.len(),
live_slots,
"live_slots must count exactly the slots that reference the store"
);
#[cfg(debug_assertions)]
debug_assert_eq!(
walked
.iter()
.collect::<std::collections::HashSet<_>>()
.len(),
walked.len(),
"two slots must not share a store row"
);
let mut chunks: Vec<(RecordBatch, usize)> =
Vec::with_capacity(coords.len().div_ceil(batch_size));
let mut remap = vec![usize::MAX; old.len()];
for chunk in coords.chunks(batch_size) {
chunks
.push((interleave_referenced(&old, chunk, &mut remap)?, chunk.len()));
}
chunks
};
let mut moved_to = 0usize;
for partition in partitions.values_mut() {
partition.repoint(|at| {
#[cfg(debug_assertions)]
assert_eq!(
walked[moved_to], at,
"store_rows and repoint must visit slots in the same order"
);
#[cfg(not(debug_assertions))]
let _ = at;
let new_place = StoreRef {
batch_id: first_id + (moved_to / batch_size) as u32,
row: (moved_to % batch_size) as u32,
};
moved_to += 1;
new_place
});
}
debug_assert_eq!(moved_to, live_slots, "repoint must visit every slot");
self.clear();
for (chunk_idx, (batch, uses)) in chunks.into_iter().enumerate() {
let mut entry = self.register(batch);
debug_assert_eq!(
entry.id,
first_id + chunk_idx as u32,
"the ids handed to the slots must be the ids the chunks got"
);
entry.uses = uses;
self.insert(entry);
}
Ok(())
}
}
fn interleave_referenced<B: Borrow<RecordBatch>>(
batches: &[B],
indices: &[(usize, usize)],
remap: &mut [usize],
) -> Result<RecordBatch> {
debug_assert_eq!(remap.len(), batches.len());
let mut used: Vec<usize> = Vec::new();
let local: Vec<(usize, usize)> = indices
.iter()
.map(|&(pos, row)| {
if remap[pos] == usize::MAX {
remap[pos] = used.len();
used.push(pos);
}
(remap[pos], row)
})
.collect();
let refs: Vec<&RecordBatch> = used.iter().map(|&pos| batches[pos].borrow()).collect();
let batch = interleave_record_batch(&refs, &local);
for pos in used {
remap[pos] = usize::MAX;
}
Ok(batch?)
}
trait StoreSlots {
fn store_rows(&self) -> impl Iterator<Item = StoreRef> + '_;
fn repoint(&mut self, moved_to: impl FnMut(StoreRef) -> StoreRef);
}
#[derive(Debug)]
struct PendingEntry {
id: u32,
uses: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct StoreRef {
batch_id: u32,
row: u32,
}
#[derive(Debug)]
struct PartitionSlot {
key: Vec<u8>,
at: StoreRef,
}
impl PartialEq for PartitionSlot {
fn eq(&self, other: &Self) -> bool {
self.key == other.key
}
}
impl Eq for PartitionSlot {}
impl PartialOrd for PartitionSlot {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for PartitionSlot {
fn cmp(&self, other: &Self) -> Ordering {
self.key.cmp(&other.key)
}
}
#[derive(Debug, Default)]
struct PartitionHeap {
inner: BinaryHeap<PartitionSlot>,
}
impl PartitionHeap {
fn qualifies(&self, k: usize, key: &[u8]) -> bool {
matches!(self.classify(k, key), None | Some(Ordering::Less))
}
fn classify(&self, k: usize, key: &[u8]) -> Option<Ordering> {
if self.inner.len() < k {
return None;
}
self.inner.peek().map(|worst| key.cmp(worst.key.as_slice()))
}
fn worst_key(&self) -> Option<&[u8]> {
self.inner.peek().map(|worst| worst.key.as_slice())
}
fn add(&mut self, k: usize, key: &[u8], at: StoreRef) -> (Option<StoreRef>, usize) {
debug_assert!(self.inner.len() <= k);
if self.inner.len() == k {
let mut worst = self.inner.peek_mut().expect("heap is full");
let before = worst.key.capacity();
worst.key.clear();
worst.key.extend_from_slice(key);
let grown = worst.key.capacity() - before;
let evicted = std::mem::replace(&mut worst.at, at);
drop(worst);
(Some(evicted), grown)
} else {
let slot = PartitionSlot {
key: key.to_vec(),
at,
};
let key_bytes = slot.key.capacity();
let inner_before = self.inner.capacity();
self.inner.push(slot);
let grown = key_bytes
+ (self.inner.capacity() - inner_before) * size_of::<PartitionSlot>();
(None, grown)
}
}
fn replace_worst(
&mut self,
key: &[u8],
at: StoreRef,
evicted_key: &mut Vec<u8>,
) -> (StoreRef, usize) {
let before = evicted_key.capacity();
evicted_key.clear();
evicted_key.extend_from_slice(key);
let grown = evicted_key.capacity() - before;
let mut worst = self.inner.peek_mut().expect("heap is full");
std::mem::swap(&mut worst.key, evicted_key);
let evicted = std::mem::replace(&mut worst.at, at);
drop(worst);
(evicted, grown)
}
fn slots(&self) -> impl Iterator<Item = &PartitionSlot> + '_ {
self.inner.iter()
}
fn drain_sorted(&mut self) -> Vec<PartitionSlot> {
std::mem::take(&mut self.inner).into_sorted_vec()
}
}
impl StoreSlots for PartitionHeap {
fn store_rows(&self) -> impl Iterator<Item = StoreRef> + '_ {
self.slots().map(|slot| slot.at)
}
fn repoint(&mut self, mut moved_to: impl FnMut(StoreRef) -> StoreRef) {
let mut slots = std::mem::take(&mut self.inner).into_vec();
for slot in &mut slots {
slot.at = moved_to(slot.at);
}
self.inner = BinaryHeap::from(slots);
}
}
pub(crate) fn partitioned_topk_output_schema(
input_schema: &SchemaRef,
ranking_field: Option<&FieldRef>,
) -> SchemaRef {
let Some(field) = ranking_field else {
return Arc::clone(input_schema);
};
let mut fields = input_schema.fields().to_vec();
fields.push(Arc::clone(field));
Arc::new(Schema::new_with_metadata(
fields,
input_schema.metadata().clone(),
))
}
struct PartitionedTopKCore<S> {
output_schema: SchemaRef,
emit_ranks: bool,
metrics: TopKMetrics,
reservation: MemoryReservation,
expr: LexOrdering,
row_converter: RowConverter,
scratch_rows: Rows,
partition_exprs: Vec<Arc<dyn PhysicalExpr>>,
partition_converter: RowConverter,
partition_scratch_rows: Rows,
partitions: HashMap<Vec<u8>, S>,
store: RecordBatchStore,
admitted_rows: Vec<u32>,
live_slots: usize,
heaps_bytes: usize,
index_bytes: usize,
k: usize,
batch_size: usize,
}
impl<S: StoreSlots> PartitionedTopKCore<S> {
#[expect(clippy::too_many_arguments)]
fn try_new(
name: &str,
partition_id: usize,
schema: &SchemaRef,
partition_exprs: Vec<Arc<dyn PhysicalExpr>>,
partition_sort_fields: Vec<SortField>,
order_expr: LexOrdering,
k: usize,
batch_size: usize,
runtime: &Arc<RuntimeEnv>,
metrics: &ExecutionPlanMetricsSet,
ranked_schema: Option<SchemaRef>,
) -> Result<Self> {
assert!(k > 0, "{name} requires k > 0");
let reservation = MemoryConsumer::new(format!("{name}[{partition_id}]"))
.register(&runtime.memory_pool);
let order_sort_fields = build_sort_fields(&order_expr, schema)?;
let row_converter = RowConverter::new(order_sort_fields)?;
let scratch_rows =
row_converter.empty_rows(batch_size, ESTIMATED_BYTES_PER_ROW * batch_size);
let partition_converter = RowConverter::new(partition_sort_fields)?;
let partition_scratch_rows = partition_converter
.empty_rows(batch_size, ESTIMATED_BYTES_PER_ROW * batch_size);
Ok(Self {
emit_ranks: ranked_schema.is_some(),
output_schema: ranked_schema.unwrap_or_else(|| Arc::clone(schema)),
metrics: TopKMetrics::new(metrics, partition_id),
reservation,
expr: order_expr,
row_converter,
scratch_rows,
partition_exprs,
partition_converter,
partition_scratch_rows,
partitions: HashMap::new(),
store: RecordBatchStore::new(),
admitted_rows: Vec::new(),
live_slots: 0,
heaps_bytes: 0,
index_bytes: 0,
k,
batch_size,
})
}
fn encode(&mut self, batch: &RecordBatch) -> Result<()> {
let num_rows = batch.num_rows();
let pk_arrays: Vec<ArrayRef> = self
.partition_exprs
.iter()
.map(|e| e.evaluate(batch).and_then(|v| v.into_array(num_rows)))
.collect::<Result<_>>()?;
self.partition_scratch_rows.clear();
self.partition_converter
.append(&mut self.partition_scratch_rows, &pk_arrays)?;
let ob_arrays: Vec<ArrayRef> = self
.expr
.iter()
.map(|e| e.expr.evaluate(batch).and_then(|v| v.into_array(num_rows)))
.collect::<Result<_>>()?;
self.scratch_rows.clear();
self.row_converter
.append(&mut self.scratch_rows, &ob_arrays)?;
Ok(())
}
fn finish_batch(
&mut self,
batch: &RecordBatch,
pending: PendingEntry,
replacements: usize,
) -> Result<()> {
self.store
.insert_rows(batch, &self.admitted_rows, pending)?;
if replacements > 0 {
self.metrics.row_replacements.add(replacements);
}
self.store
.compact(&mut self.partitions, self.live_slots, self.batch_size)
}
fn emit_with<I: IntoIterator<Item = (StoreRef, u64)>>(
self,
drain: impl FnMut(S) -> I,
) -> Result<SendableRecordBatchStream> {
let Self {
output_schema,
emit_ranks,
metrics,
reservation,
partitions,
store,
live_slots,
batch_size,
..
} = self;
let timer = metrics.baseline.elapsed_compute().timer();
let mut sorted: Vec<(Vec<u8>, S)> = partitions.into_iter().collect();
sorted.sort_unstable_by(|(a, _), (b, _)| a.cmp(b));
drop(timer);
let slots = sorted
.into_iter()
.map(|(_key, state)| state)
.flat_map(drain);
EmitState::stream(
output_schema,
emit_ranks,
metrics,
reservation,
batch_size,
&store,
slots,
live_slots,
)
}
fn allocated_size(&self) -> usize {
self.row_converter.size()
+ self.partition_converter.size()
+ self.scratch_rows.size()
+ self.partition_scratch_rows.size()
+ self.admitted_rows.allocated_size()
+ self.partitions.capacity() * (size_of::<Vec<u8>>() + size_of::<S>())
+ self.heaps_bytes
+ self.index_bytes
+ self.store.size()
}
}
pub(crate) struct PartitionedTopK {
core: PartitionedTopKCore<PartitionHeap>,
}
impl PartitionedTopK {
#[expect(clippy::too_many_arguments)]
pub(crate) fn try_new(
partition_id: usize,
schema: &SchemaRef,
partition_exprs: Vec<Arc<dyn PhysicalExpr>>,
partition_sort_fields: Vec<SortField>,
order_expr: LexOrdering,
k: usize,
batch_size: usize,
runtime: &Arc<RuntimeEnv>,
metrics: &ExecutionPlanMetricsSet,
ranked_schema: Option<SchemaRef>,
) -> Result<Self> {
Ok(Self {
core: PartitionedTopKCore::try_new(
"PartitionedTopK",
partition_id,
schema,
partition_exprs,
partition_sort_fields,
order_expr,
k,
batch_size,
runtime,
metrics,
ranked_schema,
)?,
})
}
pub(crate) fn insert_batch(&mut self, batch: &RecordBatch) -> Result<()> {
let elapsed_compute = self.core.metrics.baseline.elapsed_compute().clone();
let _timer = elapsed_compute.timer();
let num_rows = batch.num_rows();
if num_rows == 0 {
return Ok(());
}
self.core.encode(batch)?;
let core = &mut self.core;
let k = core.k;
let mut replacements: usize = 0;
core.admitted_rows.clear();
let mut pending = core.store.pending();
{
let pk_rows = &core.partition_scratch_rows;
let ob_rows = &core.scratch_rows;
let heaps = &mut core.partitions;
let admitted_rows = &mut core.admitted_rows;
let store = &mut core.store;
let mut interned_bytes = 0usize;
let mut admitted_bytes = 0usize;
let mut new_slots = 0usize;
for row in 0..num_rows {
let pk = pk_rows.row(row);
let mut interned = false;
let heap = heaps.entry_ref(pk.as_ref()).or_insert_with(|| {
interned = true;
PartitionHeap::default()
});
if interned {
interned_bytes += pk.as_ref().len();
}
let key = ob_rows.row(row);
if !heap.qualifies(k, key.as_ref()) {
continue;
}
let at = StoreRef {
batch_id: pending.id,
row: admitted_rows.len() as u32,
};
pending.uses += 1;
let (evicted, grown) = heap.add(k, key.as_ref(), at);
admitted_bytes += grown;
match evicted {
Some(evicted) => store.release(&mut pending, evicted.batch_id),
None => new_slots += 1,
}
admitted_rows.push(row as u32);
replacements += 1;
}
core.index_bytes += interned_bytes;
core.heaps_bytes += admitted_bytes;
core.live_slots += new_slots;
}
core.finish_batch(batch, pending, replacements)?;
self.core.reservation.try_resize(self.size())?;
Ok(())
}
pub(crate) fn emit(self) -> Result<SendableRecordBatchStream> {
self.core.emit_with(|mut heap| {
heap.drain_sorted()
.into_iter()
.zip(1u64..)
.map(|(slot, row_number)| (slot.at, row_number))
})
}
fn size(&self) -> usize {
size_of::<Self>() + self.core.allocated_size()
}
}
struct EmitState {
output_schema: SchemaRef,
metrics: TopKMetrics,
_reservation: MemoryReservation,
batch_size: usize,
batches: Vec<RecordBatch>,
ordered: Vec<(usize, usize)>,
ranks: Option<Vec<u64>>,
remap: Vec<usize>,
pos: usize,
}
impl EmitState {
#[expect(clippy::too_many_arguments)]
fn stream(
output_schema: SchemaRef,
emit_ranks: bool,
metrics: TopKMetrics,
reservation: MemoryReservation,
batch_size: usize,
store: &RecordBatchStore,
slots: impl Iterator<Item = (StoreRef, u64)>,
len: usize,
) -> Result<SendableRecordBatchStream> {
let timer = metrics.baseline.elapsed_compute().timer();
let (batches, batch_id_array_pos) = store.positional();
let batches: Vec<RecordBatch> = batches.into_iter().cloned().collect();
let mut ordered: Vec<(usize, usize)> = Vec::with_capacity(len);
let mut ranks: Option<Vec<u64>> = emit_ranks.then(|| Vec::with_capacity(len));
for (slot, rank) in slots {
let array_pos = *batch_id_array_pos
.get(&slot.batch_id)
.expect("a retained slot's batch_id is present in the store");
ordered.push((array_pos, slot.row as usize));
if let Some(ranks) = &mut ranks {
ranks.push(rank);
}
}
drop(timer);
reservation.try_resize(
size_of::<EmitState>()
+ store.batches_size
+ batches.capacity() * size_of::<RecordBatch>()
+ ordered.capacity() * size_of::<(usize, usize)>()
+ ranks
.as_ref()
.map_or(0, |r| r.capacity() * size_of::<u64>())
+ batches.len() * size_of::<usize>(),
)?;
let state = EmitState {
output_schema: Arc::clone(&output_schema),
metrics,
_reservation: reservation,
batch_size,
remap: vec![usize::MAX; batches.len()],
batches,
ordered,
ranks,
pos: 0,
};
Ok(Box::pin(RecordBatchStreamAdapter::new(
output_schema,
futures::stream::try_unfold(state, |mut state| async move {
Ok(state.next_batch()?.map(|batch| (batch, state)))
}),
)))
}
fn next_batch(&mut self) -> Result<Option<RecordBatch>> {
if self.pos == self.ordered.len() {
return Ok(None);
}
let _timer = self.metrics.baseline.elapsed_compute().timer();
let start = self.pos;
let end = (start + self.batch_size).min(self.ordered.len());
self.pos = end;
let batch = interleave_referenced(
&self.batches,
&self.ordered[start..end],
&mut self.remap,
)?;
let ranks = self.ranks.as_ref().map(|r| r[start..end].iter().copied());
finish_chunk(batch, ranks, &self.output_schema, &self.metrics).map(Some)
}
}
fn finish_chunk(
batch: RecordBatch,
ranks: Option<impl IntoIterator<Item = u64>>,
output_schema: &SchemaRef,
metrics: &TopKMetrics,
) -> Result<RecordBatch> {
let batch = match ranks {
None => batch,
Some(ranks) => {
let mut columns = batch.columns().to_vec();
columns.push(Arc::new(UInt64Array::from_iter_values(ranks)));
RecordBatch::try_new(Arc::clone(output_schema), columns)?
}
};
(&batch).record_output(&metrics.baseline);
Ok(batch)
}
#[derive(Debug, Default)]
struct RankPartitionState {
heap: PartitionHeap,
ties: Vec<StoreRef>,
}
impl RankPartitionState {
fn push_tie(&mut self, at: StoreRef) -> usize {
let before = self.ties.capacity();
self.ties.push(at);
(self.ties.capacity() - before) * size_of::<StoreRef>()
}
}
impl StoreSlots for RankPartitionState {
fn store_rows(&self) -> impl Iterator<Item = StoreRef> + '_ {
self.heap.store_rows().chain(self.ties.iter().copied())
}
fn repoint(&mut self, mut moved_to: impl FnMut(StoreRef) -> StoreRef) {
self.heap.repoint(&mut moved_to);
for tie in &mut self.ties {
*tie = moved_to(*tie);
}
}
}
pub(crate) struct PartitionedTopKRank {
core: PartitionedTopKCore<RankPartitionState>,
evicted_key: Vec<u8>,
ties_bytes: usize,
}
impl PartitionedTopKRank {
#[expect(clippy::too_many_arguments)]
pub(crate) fn try_new(
partition_id: usize,
schema: &SchemaRef,
partition_exprs: Vec<Arc<dyn PhysicalExpr>>,
partition_sort_fields: Vec<SortField>,
order_expr: LexOrdering,
k: usize,
batch_size: usize,
runtime: &Arc<RuntimeEnv>,
metrics: &ExecutionPlanMetricsSet,
ranked_schema: Option<SchemaRef>,
) -> Result<Self> {
Ok(Self {
core: PartitionedTopKCore::try_new(
"PartitionedTopKRank",
partition_id,
schema,
partition_exprs,
partition_sort_fields,
order_expr,
k,
batch_size,
runtime,
metrics,
ranked_schema,
)?,
evicted_key: Vec::new(),
ties_bytes: 0,
})
}
pub(crate) fn insert_batch(&mut self, batch: &RecordBatch) -> Result<()> {
let elapsed_compute = self.core.metrics.baseline.elapsed_compute().clone();
let _timer = elapsed_compute.timer();
let num_rows = batch.num_rows();
if num_rows == 0 {
return Ok(());
}
self.core.encode(batch)?;
let core = &mut self.core;
let k = core.k;
let mut replacements: usize = 0;
core.admitted_rows.clear();
let mut pending = core.store.pending();
{
let pk_rows = &core.partition_scratch_rows;
let ob_rows = &core.scratch_rows;
let states = &mut core.partitions;
let admitted_rows = &mut core.admitted_rows;
let store = &mut core.store;
let evicted_key = &mut self.evicted_key;
let mut interned_bytes = 0usize;
let mut admitted_bytes = 0usize;
let mut ties_grown = 0usize;
let mut ties_freed = 0usize;
let mut new_slots = 0usize;
let mut released_slots = 0usize;
for row in 0..num_rows {
let pk = pk_rows.row(row);
let mut interned = false;
let state = states.entry_ref(pk.as_ref()).or_insert_with(|| {
interned = true;
RankPartitionState::default()
});
if interned {
interned_bytes += pk.as_ref().len();
}
let key = ob_rows.row(row);
let key = key.as_ref();
let at = StoreRef {
batch_id: pending.id,
row: admitted_rows.len() as u32,
};
match state.heap.classify(k, key) {
Some(Ordering::Greater) => continue,
Some(Ordering::Equal) => {
ties_grown += state.push_tie(at);
new_slots += 1;
}
None => {
let (evicted, grown) = state.heap.add(k, key, at);
debug_assert!(
evicted.is_none(),
"a heap that is not full evicts nothing"
);
admitted_bytes += grown;
new_slots += 1;
}
Some(Ordering::Less) => {
let (evicted, grown) =
state.heap.replace_worst(key, at, evicted_key);
admitted_bytes += grown;
if state.heap.worst_key() == Some(evicted_key.as_slice()) {
ties_grown += state.push_tie(evicted);
new_slots += 1;
} else {
store.release(&mut pending, evicted.batch_id);
for tie in &state.ties {
store.release(&mut pending, tie.batch_id);
}
released_slots += state.ties.len();
ties_freed += state.ties.capacity() * size_of::<StoreRef>();
state.ties = Vec::new();
}
}
}
pending.uses += 1;
admitted_rows.push(row as u32);
replacements += 1;
}
core.index_bytes += interned_bytes;
core.heaps_bytes += admitted_bytes;
self.ties_bytes = self.ties_bytes + ties_grown - ties_freed;
core.live_slots = core.live_slots + new_slots - released_slots;
}
core.finish_batch(batch, pending, replacements)?;
self.core.reservation.try_resize(self.size())?;
Ok(())
}
pub(crate) fn emit(self) -> Result<SendableRecordBatchStream> {
self.core.emit_with(|mut state| {
let heap = state.heap.drain_sorted();
let boundary_rank = heap.last().map_or(0, |worst| {
heap.partition_point(|slot| slot.key < worst.key) as u64 + 1
});
let mut prev: Option<Vec<u8>> = None;
let mut rank = 0;
let heap = heap.into_iter().zip(1u64..).map(move |(slot, position)| {
if prev.as_ref() != Some(&slot.key) {
rank = position;
}
prev = Some(slot.key);
(slot.at, rank)
});
heap.chain(state.ties.into_iter().map(move |at| (at, boundary_rank)))
})
}
fn size(&self) -> usize {
size_of::<Self>() + self.core.allocated_size() + self.ties_bytes
}
}
#[derive(Debug)]
struct GroupEntry {
row_indices: Vec<u32>,
batch_id: u32,
}
#[derive(Default)]
struct DenseRankPartitionState {
groups: HashMap<Vec<u8>, Vec<GroupEntry>>,
keys: BinaryHeap<Vec<u8>>,
contents_bytes: usize,
}
impl DenseRankPartitionState {
fn size(&self) -> usize {
let table_overhead = self.groups.capacity()
* (size_of::<Vec<u8>>() + size_of::<Vec<GroupEntry>>());
let keys_overhead = self.keys.capacity() * size_of::<Vec<u8>>();
table_overhead + self.contents_bytes + keys_overhead
}
fn entry_bytes(entry: &GroupEntry) -> usize {
entry.row_indices.capacity() * size_of::<u32>()
}
fn insert_new_group(
&mut self,
ob_key: Vec<u8>,
run_indices: Vec<u32>,
batch_id: u32,
) {
let key_copy = ob_key.clone();
self.contents_bytes += key_copy.capacity() + ob_key.capacity();
self.keys.push(key_copy);
let entry = GroupEntry {
row_indices: run_indices,
batch_id,
};
self.contents_bytes += Self::entry_bytes(&entry);
let entries = vec![entry];
self.contents_bytes += entries.capacity() * size_of::<GroupEntry>();
self.groups.insert(ob_key, entries);
}
#[cfg(test)]
fn recompute_contents_bytes(&self) -> usize {
let groups: usize = self
.groups
.iter()
.map(|(key, entries)| {
key.capacity()
+ entries.capacity() * size_of::<GroupEntry>()
+ entries.iter().map(Self::entry_bytes).sum::<usize>()
})
.sum();
groups + self.keys.iter().map(|k| k.capacity()).sum::<usize>()
}
}
pub(crate) struct PartitionedTopKDenseRank {
metrics: TopKMetrics,
reservation: MemoryReservation,
expr: LexOrdering,
row_converter: RowConverter,
scratch_rows: Rows,
partition_exprs: Vec<Arc<dyn PhysicalExpr>>,
partition_converter: RowConverter,
partition_scratch_rows: Rows,
states: HashMap<Vec<u8>, DenseRankPartitionState>,
partition_groups: HashMap<Vec<u8>, Vec<u32>>,
ob_runs: HashMap<Vec<u8>, Vec<u32>>,
store: RecordBatchStore,
emit_ranks: bool,
output_schema: SchemaRef,
k: usize,
batch_size: usize,
}
impl PartitionedTopKDenseRank {
#[expect(clippy::too_many_arguments)]
pub(crate) fn try_new(
partition_id: usize,
schema: &SchemaRef,
partition_exprs: Vec<Arc<dyn PhysicalExpr>>,
partition_sort_fields: Vec<SortField>,
order_expr: LexOrdering,
k: usize,
batch_size: usize,
runtime: &Arc<RuntimeEnv>,
metrics: &ExecutionPlanMetricsSet,
ranked_schema: Option<SchemaRef>,
) -> Result<Self> {
assert!(k > 0, "PartitionedTopKDenseRank requires k > 0");
let reservation =
MemoryConsumer::new(format!("PartitionedTopKDenseRank[{partition_id}]"))
.register(&runtime.memory_pool);
let order_sort_fields = build_sort_fields(&order_expr, schema)?;
let row_converter = RowConverter::new(order_sort_fields)?;
let scratch_rows =
row_converter.empty_rows(batch_size, ESTIMATED_BYTES_PER_ROW * batch_size);
let partition_converter = RowConverter::new(partition_sort_fields)?;
let partition_scratch_rows = partition_converter
.empty_rows(batch_size, ESTIMATED_BYTES_PER_ROW * batch_size);
Ok(Self {
emit_ranks: ranked_schema.is_some(),
output_schema: ranked_schema.unwrap_or_else(|| Arc::clone(schema)),
metrics: TopKMetrics::new(metrics, partition_id),
reservation,
expr: order_expr,
row_converter,
scratch_rows,
partition_exprs,
partition_converter,
partition_scratch_rows,
states: HashMap::new(),
partition_groups: HashMap::new(),
ob_runs: HashMap::new(),
store: RecordBatchStore::new(),
k,
batch_size,
})
}
pub(crate) fn insert_batch(&mut self, batch: &RecordBatch) -> Result<()> {
let elapsed_compute = self.metrics.baseline.elapsed_compute().clone();
let _timer = elapsed_compute.timer();
let num_rows = batch.num_rows();
if num_rows == 0 {
return Ok(());
}
let mut batch_entry = self.store.register(batch.clone());
let batch_id = batch_entry.id;
let pk_arrays: Vec<ArrayRef> = self
.partition_exprs
.iter()
.map(|e| e.evaluate(batch).and_then(|v| v.into_array(num_rows)))
.collect::<Result<_>>()?;
self.partition_scratch_rows.clear();
self.partition_converter
.append(&mut self.partition_scratch_rows, &pk_arrays)?;
let mut groups = std::mem::take(&mut self.partition_groups);
groups.clear();
{
let pk_rows = &self.partition_scratch_rows;
for i in 0..num_rows {
groups
.entry_ref(pk_rows.row(i).as_ref())
.or_default()
.push(i as u32);
}
}
let ob_arrays: Vec<ArrayRef> = self
.expr
.iter()
.map(|e| e.expr.evaluate(batch).and_then(|v| v.into_array(num_rows)))
.collect::<Result<_>>()?;
self.scratch_rows.clear();
self.row_converter
.append(&mut self.scratch_rows, &ob_arrays)?;
let k = self.k;
let mut replacements: usize = 0;
for (pk, indices) in groups.drain() {
let state = self
.states
.entry(pk)
.or_insert_with(DenseRankPartitionState::default);
let mut runs = std::mem::take(&mut self.ob_runs);
runs.clear();
let boundary: Option<&[u8]> = if state.groups.len() == k {
state.keys.peek().map(Vec::as_slice)
} else {
None
};
for &orig_idx in &indices {
let ob_row = self.scratch_rows.row(orig_idx as usize);
if boundary.is_some_and(|b| ob_row.as_ref() > b) {
continue;
}
runs.entry_ref(ob_row.as_ref()).or_default().push(orig_idx);
}
for (ob_key, run_indices) in runs.drain() {
if let Some(entries) = state.groups.get_mut(&ob_key) {
batch_entry.uses += 1;
let before = entries.capacity() * size_of::<GroupEntry>();
let entry = GroupEntry {
row_indices: run_indices,
batch_id,
};
state.contents_bytes += DenseRankPartitionState::entry_bytes(&entry);
entries.push(entry);
state.contents_bytes +=
entries.capacity() * size_of::<GroupEntry>() - before;
continue;
}
if state.groups.len() < k {
batch_entry.uses += 1;
state.insert_new_group(ob_key, run_indices, batch_id);
continue;
}
let max_key = state.keys.peek().expect("state.groups has k >= 1 keys");
if ob_key.as_slice() < max_key.as_slice() {
let evicted_key = state.keys.pop().expect("max key present");
let (map_key, evicted) = state
.groups
.remove_entry(&evicted_key)
.expect("keys mirrors groups");
state.contents_bytes -= evicted_key.capacity()
+ map_key.capacity()
+ evicted.capacity() * size_of::<GroupEntry>()
+ evicted
.iter()
.map(DenseRankPartitionState::entry_bytes)
.sum::<usize>();
for e in &evicted {
replacements += e.row_indices.len();
if e.batch_id == batch_id {
batch_entry.uses -= 1;
} else {
self.store.unuse(e.batch_id);
}
}
batch_entry.uses += 1;
state.insert_new_group(ob_key, run_indices, batch_id);
}
}
self.ob_runs = runs;
}
self.partition_groups = groups;
self.store.insert(batch_entry);
if replacements > 0 {
self.metrics.row_replacements.add(replacements);
}
self.reservation.try_resize(self.size())?;
Ok(())
}
pub(crate) fn emit(self) -> Result<SendableRecordBatchStream> {
let Self {
output_schema,
emit_ranks,
metrics,
reservation: _,
expr: _,
row_converter: _,
scratch_rows: _,
partition_exprs: _,
partition_converter: _,
partition_scratch_rows: _,
mut states,
partition_groups: _,
ob_runs: _,
store,
k: _,
batch_size,
} = self;
let _timer = metrics.baseline.elapsed_compute().timer();
let mut sorted_pks: Vec<Vec<u8>> = states.keys().cloned().collect();
sorted_pks.sort();
let mut out: Vec<Result<RecordBatch>> = Vec::new();
let mut batch_refs: Vec<&RecordBatch> = Vec::new();
let mut batch_id_pos: HashMap<u32, usize> = HashMap::new();
let mut indices: Vec<(usize, usize)> = Vec::with_capacity(batch_size);
let mut sorted_obs: Vec<(Vec<u8>, Vec<GroupEntry>)> = Vec::new();
let mut ranks: Option<Vec<u64>> =
emit_ranks.then(|| Vec::with_capacity(batch_size));
for pk in sorted_pks {
let DenseRankPartitionState {
groups,
keys: _,
contents_bytes: _,
} = states.remove(&pk).expect("key from states.keys()");
sorted_obs.extend(groups);
sorted_obs.sort_by(|a, b| a.0.cmp(&b.0));
for (dense_rank, (_ob, entries)) in (1u64..).zip(sorted_obs.drain(..)) {
for entry in entries {
let batch = &store
.get(entry.batch_id)
.expect("retained batch_id present in store")
.batch;
let mut array_pos = None;
for row in entry.row_indices {
let pos = *array_pos.get_or_insert_with(|| {
*batch_id_pos.entry(entry.batch_id).or_insert_with(|| {
batch_refs.push(batch);
batch_refs.len() - 1
})
});
indices.push((pos, row as usize));
if let Some(ranks) = &mut ranks {
ranks.push(dense_rank);
}
if indices.len() == batch_size {
let b = interleave_record_batch(&batch_refs, &indices)?;
let ranks = ranks.as_mut().map(|r| r.drain(..));
out.push(Ok(finish_chunk(
b,
ranks,
&output_schema,
&metrics,
)?));
indices.clear();
batch_refs.clear();
batch_id_pos.clear();
array_pos = None;
}
}
}
}
}
if !indices.is_empty() {
let b = interleave_record_batch(&batch_refs, &indices)?;
let ranks = ranks.as_mut().map(|r| r.drain(..));
out.push(Ok(finish_chunk(b, ranks, &output_schema, &metrics)?));
}
Ok(Box::pin(RecordBatchStreamAdapter::new(
output_schema,
futures::stream::iter(out),
)))
}
fn size(&self) -> usize {
let states_contents: usize = self
.states
.iter()
.map(|(pk, state)| pk.capacity() + state.size())
.sum();
let scratch_tables = self.partition_groups.capacity()
* (size_of::<Vec<u8>>() + size_of::<Vec<u32>>())
+ self.ob_runs.capacity() * (size_of::<Vec<u8>>() + size_of::<Vec<u32>>());
size_of::<Self>()
+ self.row_converter.size()
+ self.partition_converter.size()
+ self.scratch_rows.size()
+ self.partition_scratch_rows.size()
+ states_contents
+ self.states.capacity()
* (size_of::<Vec<u8>>() + size_of::<DenseRankPartitionState>())
+ scratch_tables
+ self.store.size()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::metrics::MetricValue;
use crate::spill::get_record_batch_memory_size;
use arrow::array::{
AsArray, BooleanArray, Float64Array, Int32Array, Int64Array, StringArray,
StringDictionaryBuilder,
};
use arrow::datatypes::{DataType, Field, Int32Type, Int64Type, Schema, UInt64Type};
use arrow_schema::SortOptions;
use datafusion_common::utils::memory::RecordBatchMemoryCounter;
use datafusion_common::{assert_batches_eq, exec_datafusion_err};
use datafusion_execution::memory_pool::GreedyMemoryPool;
use datafusion_execution::runtime_env::RuntimeEnvBuilder;
use datafusion_physical_expr::{DynamicFilterTracking, expressions::col};
use futures::TryStreamExt;
#[test]
fn test_record_batch_store_size() {
let schema = Arc::new(Schema::new(vec![
Field::new("ints", DataType::Int32, true),
Field::new("float64", DataType::Float64, false),
]));
let mut record_batch_store = RecordBatchStore::new();
let int_array =
Int32Array::from(vec![Some(1), Some(2), Some(3), Some(4), Some(5)]); let float64_array = Float64Array::from(vec![1.0, 2.0, 3.0, 4.0, 5.0]);
let record_batch_entry = RecordBatchEntry {
id: 0,
batch: RecordBatch::try_new(
schema,
vec![Arc::new(int_array), Arc::new(float64_array)],
)
.unwrap(),
uses: 1,
};
record_batch_store.insert(record_batch_entry);
assert_eq!(record_batch_store.batches_size, 60);
record_batch_store.unuse(0);
assert_eq!(record_batch_store.batches_size, 0);
}
fn make_ab_schema() -> SchemaRef {
make_ab_schema_with_nullable_a(false)
}
fn make_ab_schema_with_nullable_a(a_nullable: bool) -> SchemaRef {
Arc::new(Schema::new(vec![
Field::new("a", DataType::Int32, a_nullable),
Field::new("b", DataType::Float64, false),
]))
}
fn make_topk_filter() -> Arc<RwLock<TopKDynamicFilters>> {
make_shared_topk_filter(1)
}
fn make_shared_topk_filter(
topk_emitter_count: usize,
) -> Arc<RwLock<TopKDynamicFilters>> {
Arc::new(RwLock::new(
TopKDynamicFilters::new_with_topk_emitter_count(
Arc::new(DynamicFilterPhysicalExpr::new(vec![], lit(true))),
topk_emitter_count,
),
))
}
fn make_ab_topk(
schema: SchemaRef,
filter: Arc<RwLock<TopKDynamicFilters>>,
) -> Result<TopK> {
make_ab_topk_with_options(0, schema, filter, SortOptions::default())
}
fn make_ab_topk_with_options(
partition_id: usize,
schema: SchemaRef,
filter: Arc<RwLock<TopKDynamicFilters>>,
a_options: SortOptions,
) -> Result<TopK> {
let sort_expr_a = PhysicalSortExpr {
expr: col("a", schema.as_ref())?,
options: a_options,
};
let sort_expr_b = PhysicalSortExpr {
expr: col("b", schema.as_ref())?,
options: SortOptions::default(),
};
TopK::try_new(
partition_id,
schema,
vec![sort_expr_a.clone()],
LexOrdering::from([sort_expr_a, sort_expr_b]),
3,
2,
Arc::new(RuntimeEnv::default()),
&ExecutionPlanMetricsSet::new(),
filter,
)
}
#[test]
fn test_topk_size_common_sort_prefix_converter() -> Result<()> {
let schema = make_ab_schema();
let sort_expr = PhysicalSortExpr {
expr: col("a", schema.as_ref())?,
options: SortOptions::default(),
};
let make_topk = |common_sort_prefix| {
TopK::try_new(
0,
Arc::clone(&schema),
common_sort_prefix,
LexOrdering::from([sort_expr.clone()]),
3,
2,
Arc::new(RuntimeEnv::default()),
&ExecutionPlanMetricsSet::new(),
make_topk_filter(),
)
};
let without_prefix = make_topk(vec![])?;
let with_prefix = make_topk(vec![sort_expr.clone()])?;
let converter_size = with_prefix
.common_sort_prefix_converter
.as_ref()
.expect("common sort prefix converter")
.size();
assert!(converter_size > 0);
assert!(without_prefix.common_sort_prefix_converter.is_none());
assert_eq!(
without_prefix.size(),
size_of::<TopK>()
+ without_prefix.row_converter.size()
+ without_prefix.scratch_rows.size()
+ without_prefix.heap.size()
);
assert_eq!(with_prefix.size(), without_prefix.size() + converter_size);
Ok(())
}
fn output_batches_and_rows(metrics: &ExecutionPlanMetricsSet) -> (usize, usize) {
let metrics = metrics.clone_inner();
let batches = metrics
.sum(|m| matches!(m.value(), MetricValue::OutputBatches(_)))
.expect("output_batches metric")
.as_usize();
(batches, metrics.output_rows().expect("output_rows metric"))
}
#[tokio::test]
async fn test_topk_output_batches_metric_counts_emitted_batches() -> Result<()> {
let schema = make_ab_schema();
let metrics = ExecutionPlanMetricsSet::new();
let sort_expr = PhysicalSortExpr {
expr: col("a", schema.as_ref())?,
options: SortOptions::default(),
};
let mut topk = TopK::try_new(
0,
Arc::clone(&schema),
vec![],
LexOrdering::from([sort_expr]),
5,
2,
Arc::new(RuntimeEnv::default()),
&metrics,
make_topk_filter(),
)?;
topk.insert_batch(make_ab_batch(
Arc::clone(&schema),
&[Some(5), Some(4), Some(3), Some(2), Some(1), Some(0)],
&[0.0, 1.0, 2.0, 3.0, 4.0, 5.0],
)?)?;
let results: Vec<_> = topk.emit()?.try_collect().await?;
let row_counts: Vec<usize> = results.iter().map(|b| b.num_rows()).collect();
assert_eq!(row_counts, vec![2, 2, 1]);
assert_eq!(output_batches_and_rows(&metrics), (3, 5));
Ok(())
}
fn make_ab_batch(
schema: SchemaRef,
a: &[Option<i32>],
b: &[f64],
) -> Result<RecordBatch> {
Ok(RecordBatch::try_new(
schema,
vec![
Arc::new(Int32Array::from(a.to_vec())) as ArrayRef,
Arc::new(Float64Array::from(b.to_vec())) as ArrayRef,
],
)?)
}
type AbRow = (Option<i32>, f64);
fn make_ab_rows_batch(schema: SchemaRef, rows: &[AbRow]) -> Result<RecordBatch> {
let (a, b): (Vec<_>, Vec<_>) = rows.iter().copied().unzip();
make_ab_batch(schema, &a, &b)
}
#[tokio::test]
async fn test_early_completion_marks_finished_with_prefix() -> Result<()> {
let schema = make_ab_schema();
let mut topk = make_ab_topk(Arc::clone(&schema), make_topk_filter())?;
topk.insert_batch(make_ab_batch(
Arc::clone(&schema),
&[Some(1), Some(1), Some(2)],
&[20.0, 15.0, 30.0],
)?)?;
assert!(!topk.finished);
topk.insert_batch(make_ab_batch(
Arc::clone(&schema),
&[Some(2), Some(3)],
&[10.0, 20.0],
)?)?;
assert!(topk.finished);
let results: Vec<_> = topk.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+---+------+",
"| a | b |",
"+---+------+",
"| 1 | 15.0 |",
"| 1 | 20.0 |",
"| 2 | 10.0 |",
"+---+------+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_early_completion_fires_when_filter_rejects_entire_batch() -> Result<()>
{
let schema = make_ab_schema();
let mut topk = make_ab_topk(Arc::clone(&schema), make_topk_filter())?;
topk.insert_batch(make_ab_batch(
Arc::clone(&schema),
&[Some(1), Some(1), Some(2)],
&[20.0, 15.0, 30.0],
)?)?;
assert!(!topk.finished);
topk.insert_batch(make_ab_batch(
Arc::clone(&schema),
&[Some(3), Some(3)],
&[10.0, 20.0],
)?)?;
assert!(topk.finished);
let results: Vec<_> = topk.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+---+------+",
"| a | b |",
"+---+------+",
"| 1 | 15.0 |",
"| 1 | 20.0 |",
"| 2 | 30.0 |",
"+---+------+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_early_completion_fires_when_batch_makes_no_replacements() -> Result<()>
{
let schema = make_ab_schema();
let filter = make_topk_filter();
let mut topk = make_ab_topk(Arc::clone(&schema), Arc::clone(&filter))?;
topk.insert_batch(make_ab_batch(
Arc::clone(&schema),
&[Some(1), Some(1), Some(2)],
&[20.0, 15.0, 30.0],
)?)?;
assert!(!topk.finished);
let replacements_before = topk.metrics.row_replacements.value();
filter.read().expr().update(lit(true))?;
topk.insert_batch(make_ab_batch(
Arc::clone(&schema),
&[Some(3), Some(3)],
&[10.0, 20.0],
)?)?;
assert_eq!(topk.metrics.row_replacements.value(), replacements_before);
assert!(topk.finished);
let results: Vec<_> = topk.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+---+------+",
"| a | b |",
"+---+------+",
"| 1 | 15.0 |",
"| 1 | 20.0 |",
"| 2 | 30.0 |",
"+---+------+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_empty_batch_with_prefix_does_not_finish() -> Result<()> {
let schema = make_ab_schema();
let mut topk = make_ab_topk(Arc::clone(&schema), make_topk_filter())?;
let empty = RecordBatch::new_empty(Arc::clone(&schema));
topk.insert_batch(empty.clone())?;
assert!(!topk.finished);
assert_eq!(topk.heap.store.len(), 0);
topk.insert_batch(make_ab_batch(
Arc::clone(&schema),
&[Some(1), Some(1), Some(2)],
&[20.0, 15.0, 30.0],
)?)?;
let heap_before = heap_snapshot(&topk);
let store_len_before = topk.heap.store.len();
topk.insert_batch(empty)?;
assert!(!topk.finished);
assert_eq!(heap_snapshot(&topk), heap_before);
assert_eq!(topk.heap.store.len(), store_len_before);
let results: Vec<_> = topk.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+---+------+",
"| a | b |",
"+---+------+",
"| 1 | 15.0 |",
"| 1 | 20.0 |",
"| 2 | 30.0 |",
"+---+------+",
],
&results
);
Ok(())
}
fn make_single_key_topk(
schema: SchemaRef,
expr: Arc<dyn PhysicalExpr>,
metrics: &ExecutionPlanMetricsSet,
) -> Result<TopK> {
TopK::try_new(
0,
schema,
vec![],
LexOrdering::from([PhysicalSortExpr {
expr,
options: SortOptions::default(),
}]),
3,
2,
Arc::new(RuntimeEnv::default()),
metrics,
make_topk_filter(),
)
}
fn heap_snapshot(topk: &TopK) -> Vec<(Vec<u8>, u32, usize)> {
topk.heap
.inner
.iter()
.map(|r| (r.row.clone(), r.batch_id, r.index))
.collect()
}
#[tokio::test]
async fn test_batch_rejected_by_threshold_leaves_heap_untouched() -> Result<()> {
let schema = make_ab_schema();
let metrics = ExecutionPlanMetricsSet::new();
let mut topk =
make_single_key_topk(Arc::clone(&schema), col("a", &schema)?, &metrics)?;
topk.insert_batch(make_ab_batch(
Arc::clone(&schema),
&[Some(3), Some(1), Some(2)],
&[0.0, 1.0, 2.0],
)?)?;
let rejected = make_ab_batch(
Arc::clone(&schema),
&[Some(7), Some(5), Some(9)],
&[3.0, 4.0, 5.0],
)?;
let threshold = topk.filter.read().expr.current()?;
let passing = threshold
.evaluate(&rejected)?
.into_array(rejected.num_rows())?;
assert!(!passing.as_boolean().has_true());
let heap_before = heap_snapshot(&topk);
let store_len_before = topk.heap.store.len();
let replacements_before = topk.metrics.row_replacements.value();
topk.insert_batch(rejected)?;
assert_eq!(heap_snapshot(&topk), heap_before);
assert_eq!(topk.heap.store.len(), store_len_before);
assert_eq!(topk.metrics.row_replacements.value(), replacements_before);
let results: Vec<_> = topk.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+---+-----+",
"| a | b |",
"+---+-----+",
"| 1 | 1.0 |",
"| 2 | 2.0 |",
"| 3 | 0.0 |",
"+---+-----+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_expression_sort_key_matches_column_sort_key() -> Result<()> {
let schema = make_ab_schema();
let column_metrics = ExecutionPlanMetricsSet::new();
let expr_metrics = ExecutionPlanMetricsSet::new();
let mut by_column = make_single_key_topk(
Arc::clone(&schema),
col("a", &schema)?,
&column_metrics,
)?;
let a_plus_one = Arc::new(BinaryExpr::new(
col("a", &schema)?,
Operator::Plus,
lit(1i32),
));
let mut by_expr =
make_single_key_topk(Arc::clone(&schema), a_plus_one, &expr_metrics)?;
let inputs: [&[Option<i32>]; 4] = [
&[Some(8), Some(5), Some(9)],
&[Some(4), Some(10), Some(2)],
&[Some(11), Some(12)],
&[Some(6), Some(1), Some(7)],
];
for a in inputs {
let b: Vec<f64> = a.iter().map(|v| f64::from(v.unwrap()) / 2.0).collect();
let batch = make_ab_batch(Arc::clone(&schema), a, &b)?;
by_column.insert_batch(batch.clone())?;
by_expr.insert_batch(batch)?;
assert_eq!(
by_expr.metrics.row_replacements.value(),
by_column.metrics.row_replacements.value()
);
}
let column_results: Vec<_> = by_column.emit()?.try_collect().await?;
let expr_results: Vec<_> = by_expr.emit()?.try_collect().await?;
let expected = [
"+---+-----+",
"| a | b |",
"+---+-----+",
"| 1 | 0.5 |",
"| 2 | 1.0 |",
"| 4 | 2.0 |",
"+---+-----+",
];
assert_batches_eq!(expected, &column_results);
assert_batches_eq!(expected, &expr_results);
assert_eq!(
output_batches_and_rows(&expr_metrics),
output_batches_and_rows(&column_metrics)
);
Ok(())
}
struct SharedPrefixCase {
name: &'static str,
a_nullable: bool,
a_options: SortOptions,
threshold_source_rows: &'static [AbRow],
lagging_partition_rows: &'static [AbRow],
expected_finished: bool,
}
fn assert_shared_prefix_case(case: SharedPrefixCase) -> Result<()> {
let schema = make_ab_schema_with_nullable_a(case.a_nullable);
let filter = make_shared_topk_filter(2);
let mut threshold_source = make_ab_topk_with_options(
0,
Arc::clone(&schema),
Arc::clone(&filter),
case.a_options,
)?;
threshold_source.insert_batch(make_ab_rows_batch(
Arc::clone(&schema),
case.threshold_source_rows,
)?)?;
assert!(
filter
.read()
.shared_threshold
.as_ref()
.and_then(TopKThreshold::common_prefix_row)
.is_some(),
"{}: threshold-source partition should establish the shared prefix threshold",
case.name
);
let mut lagging_partition = make_ab_topk_with_options(
1,
Arc::clone(&schema),
Arc::clone(&filter),
case.a_options,
)?;
lagging_partition
.insert_batch(make_ab_rows_batch(schema, case.lagging_partition_rows)?)?;
assert!(
lagging_partition.heap.inner.is_empty(),
"{}: lagging partition's local heap should remain empty",
case.name
);
assert_eq!(
lagging_partition.finished, case.expected_finished,
"{}",
case.name
);
Ok(())
}
#[test]
fn test_shared_filter_can_finish_partition_before_local_heap_is_full() -> Result<()> {
assert_shared_prefix_case(SharedPrefixCase {
name: "shared threshold should finish lagging partition",
a_nullable: false,
a_options: SortOptions::default(),
threshold_source_rows: &[(Some(1), 20.0), (Some(1), 15.0), (Some(2), 30.0)],
lagging_partition_rows: &[(Some(3), 10.0), (Some(3), 20.0)],
expected_finished: true,
})
}
#[test]
fn test_shared_prefix_threshold_boundary_cases() -> Result<()> {
for case in [
SharedPrefixCase {
name: "equal prefix cannot prove completion",
a_nullable: false,
a_options: SortOptions::default(),
threshold_source_rows: &[
(Some(1), 20.0),
(Some(1), 15.0),
(Some(2), 30.0),
],
lagging_partition_rows: &[(Some(2), 40.0), (Some(2), 50.0)],
expected_finished: false,
},
SharedPrefixCase {
name: "descending prefix uses sort-order row encoding",
a_nullable: false,
a_options: SortOptions {
descending: true,
nulls_first: true,
},
threshold_source_rows: &[
(Some(10), 1.0),
(Some(10), 2.0),
(Some(9), 3.0),
],
lagging_partition_rows: &[(Some(8), 1.0), (Some(8), 2.0)],
expected_finished: true,
},
SharedPrefixCase {
name: "NULLS LAST prefix uses sort-order row encoding",
a_nullable: true,
a_options: SortOptions {
descending: false,
nulls_first: false,
},
threshold_source_rows: &[
(Some(1), 20.0),
(Some(1), 15.0),
(Some(2), 30.0),
],
lagging_partition_rows: &[(None, 10.0), (None, 20.0)],
expected_finished: true,
},
] {
assert_shared_prefix_case(case)?;
}
Ok(())
}
fn make_single_column_topk(
dynamic_filter: Arc<DynamicFilterPhysicalExpr>,
) -> Result<(SchemaRef, TopK)> {
make_single_column_topk_with_filter(
0,
Arc::new(RwLock::new(TopKDynamicFilters::new(dynamic_filter))),
)
}
fn make_single_column_topk_with_filter(
partition_id: usize,
filter: Arc<RwLock<TopKDynamicFilters>>,
) -> Result<(SchemaRef, TopK)> {
let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)]));
let sort_expr = PhysicalSortExpr {
expr: col("a", schema.as_ref())?,
options: SortOptions::default(),
};
let topk = TopK::try_new(
partition_id,
Arc::clone(&schema),
vec![sort_expr.clone()],
LexOrdering::from([sort_expr]),
2,
10,
Arc::new(RuntimeEnv::default()),
&ExecutionPlanMetricsSet::new(),
filter,
)?;
Ok((schema, topk))
}
#[tokio::test]
async fn test_topk_marks_filter_complete() -> Result<()> {
let dynamic_filter = Arc::new(DynamicFilterPhysicalExpr::new(vec![], lit(true)));
let dynamic_filter_clone = Arc::clone(&dynamic_filter);
let (schema, mut topk) = make_single_column_topk(dynamic_filter)?;
let array: ArrayRef = Arc::new(Int32Array::from(vec![Some(3), Some(1), Some(2)]));
let batch = RecordBatch::try_new(Arc::clone(&schema), vec![array])?;
topk.insert_batch(batch)?;
let _results: Vec<_> = topk.emit()?.try_collect().await?;
tokio::time::timeout(
std::time::Duration::from_secs(1),
dynamic_filter_clone.wait_complete(),
)
.await
.expect("single-emitter TopK should mark the dynamic filter complete");
Ok(())
}
#[tokio::test]
async fn test_shared_topk_filter_completes_after_last_emitter() -> Result<()> {
let dynamic_filter = Arc::new(DynamicFilterPhysicalExpr::new(vec![], lit(true)));
let dynamic_filter_clone = Arc::clone(&dynamic_filter);
let shared_filter = Arc::new(RwLock::new(
TopKDynamicFilters::new_with_topk_emitter_count(dynamic_filter, 2),
));
let (schema, mut topk_0) =
make_single_column_topk_with_filter(0, Arc::clone(&shared_filter))?;
let (_, mut topk_1) =
make_single_column_topk_with_filter(1, Arc::clone(&shared_filter))?;
let array: ArrayRef = Arc::new(Int32Array::from(vec![Some(3), Some(1), Some(2)]));
let batch = RecordBatch::try_new(Arc::clone(&schema), vec![array])?;
topk_0.insert_batch(batch)?;
let _results: Vec<_> = topk_0.emit()?.try_collect().await?;
let dynamic_filter_expr: Arc<dyn PhysicalExpr> =
Arc::<DynamicFilterPhysicalExpr>::clone(&dynamic_filter_clone);
assert!(
matches!(
DynamicFilterTracking::classify(&dynamic_filter_expr),
DynamicFilterTracking::Watching(_)
),
"the shared filter should remain watchable until every TopK emits"
);
let array: ArrayRef = Arc::new(Int32Array::from(vec![Some(6), Some(4), Some(5)]));
let batch = RecordBatch::try_new(schema, vec![array])?;
topk_1.insert_batch(batch)?;
let _results: Vec<_> = topk_1.emit()?.try_collect().await?;
tokio::time::timeout(
std::time::Duration::from_secs(1),
dynamic_filter_clone.wait_complete(),
)
.await
.expect("the final shared TopK emitter should mark the dynamic filter complete");
Ok(())
}
fn make_c0_c1_schema() -> SchemaRef {
Arc::new(Schema::new(vec![
Field::new("c0", DataType::Int64, false),
Field::new("c1", DataType::Int64, false),
]))
}
fn make_c0_c1_batch(schema: SchemaRef, rows: &[(i64, i64)]) -> Result<RecordBatch> {
let c0: ArrayRef =
Arc::new(Int64Array::from_iter_values(rows.iter().map(|row| row.0)));
let c1: ArrayRef =
Arc::new(Int64Array::from_iter_values(rows.iter().map(|row| row.1)));
Ok(RecordBatch::try_new(schema, vec![c0, c1])?)
}
fn c0_c1_sort_exprs(
schema: &SchemaRef,
) -> Result<(PhysicalSortExpr, PhysicalSortExpr)> {
Ok((
PhysicalSortExpr {
expr: col("c0", schema.as_ref())?,
options: SortOptions::default(),
},
PhysicalSortExpr {
expr: col("c1", schema.as_ref())?,
options: SortOptions::default(),
},
))
}
fn make_c0_c1_topk(
partition_id: usize,
schema: SchemaRef,
common_sort_prefix: Vec<PhysicalSortExpr>,
expr: LexOrdering,
filter: Arc<RwLock<TopKDynamicFilters>>,
) -> Result<TopK> {
TopK::try_new(
partition_id,
schema,
common_sort_prefix,
expr,
2,
8192,
Arc::new(RuntimeEnv::default()),
&ExecutionPlanMetricsSet::new(),
filter,
)
}
async fn merged_c0_c1_top2(
schema: &SchemaRef,
topk_ordering: LexOrdering,
common_sort_prefix: Vec<PhysicalSortExpr>,
five_first: bool,
) -> Result<Vec<(i64, i64)>> {
let filter = make_shared_topk_filter(2);
let mut five = make_c0_c1_topk(
0,
Arc::clone(schema),
common_sort_prefix.clone(),
topk_ordering.clone(),
Arc::clone(&filter),
)?;
let mut one = make_c0_c1_topk(
1,
Arc::clone(schema),
common_sort_prefix,
topk_ordering,
filter,
)?;
let five_batch = make_c0_c1_batch(Arc::clone(schema), &[(5, 0), (5, 1)])?;
let one_batch = make_c0_c1_batch(Arc::clone(schema), &[(1, 0), (1, 1)])?;
if five_first {
five.insert_batch(five_batch)?;
one.insert_batch(one_batch)?;
} else {
one.insert_batch(one_batch)?;
five.insert_batch(five_batch)?;
}
collect_c0_c1_top2([five, one]).await
}
async fn collect_c0_c1_top2(topks: [TopK; 2]) -> Result<Vec<(i64, i64)>> {
let mut rows = Vec::new();
for topk in topks {
let batches: Vec<RecordBatch> = topk.emit()?.try_collect().await?;
for batch in batches {
let c0 = batch.column(0).as_primitive::<Int64Type>();
let c1 = batch.column(1).as_primitive::<Int64Type>();
rows.extend((0..batch.num_rows()).map(|i| (c0.value(i), c1.value(i))));
}
}
rows.sort_unstable();
rows.truncate(2);
Ok(rows)
}
#[tokio::test]
async fn test_shared_filter_keeps_heterogeneous_constant_in_key() -> Result<()> {
let schema = make_c0_c1_schema();
let (sort_c0, sort_c1) = c0_c1_sort_exprs(&schema)?;
for five_first in [true, false] {
let rows = merged_c0_c1_top2(
&schema,
LexOrdering::from([sort_c0.clone(), sort_c1.clone()]),
vec![sort_c0.clone()],
five_first,
)
.await?;
assert_eq!(rows, vec![(1, 0), (1, 1)], "five_first={five_first}");
}
Ok(())
}
#[tokio::test]
async fn test_shared_filter_heterogeneous_prefix_across_batches() -> Result<()> {
let schema = make_c0_c1_schema();
let (sort_c0, sort_c1) = c0_c1_sort_exprs(&schema)?;
let ordering = LexOrdering::from([sort_c0.clone(), sort_c1]);
let filter = make_shared_topk_filter(2);
let mut five = make_c0_c1_topk(
0,
Arc::clone(&schema),
vec![sort_c0.clone()],
ordering.clone(),
Arc::clone(&filter),
)?;
let mut one = make_c0_c1_topk(
1,
Arc::clone(&schema),
vec![sort_c0],
ordering,
Arc::clone(&filter),
)?;
five.insert_batch(make_c0_c1_batch(Arc::clone(&schema), &[(5, 0), (5, 1)])?)?;
assert!(filter.read().shared_threshold.is_some());
assert!(!five.finished);
one.insert_batch(make_c0_c1_batch(Arc::clone(&schema), &[(1, 0)])?)?;
assert!(!one.finished);
assert_eq!(one.heap.inner.len(), 1);
one.insert_batch(make_c0_c1_batch(Arc::clone(&schema), &[(1, 1)])?)?;
assert!(!one.finished);
assert_eq!(one.heap.inner.len(), 2);
five.insert_batch(make_c0_c1_batch(schema, &[(5, 2)])?)?;
assert!(five.finished);
assert_eq!(five.metrics.row_replacements.value(), 2);
assert_eq!(collect_c0_c1_top2([five, one]).await?, vec![(1, 0), (1, 1)]);
Ok(())
}
#[tokio::test]
async fn test_topk_memory_compaction() -> Result<()> {
let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)]));
let sort_expr = PhysicalSortExpr {
expr: col("a", schema.as_ref())?,
options: SortOptions::default(),
};
let full_expr = LexOrdering::from([sort_expr.clone()]);
let prefix = vec![sort_expr];
let runtime = Arc::new(RuntimeEnv::default());
let metrics = ExecutionPlanMetricsSet::new();
let k = 5;
let mut topk = TopK::try_new(
0,
Arc::clone(&schema),
prefix,
full_expr,
k,
8192,
runtime,
&metrics,
Arc::new(RwLock::new(TopKDynamicFilters::new(Arc::new(
DynamicFilterPhysicalExpr::new(vec![], lit(true)),
)))),
)?;
let large_values: Vec<i32> = (1..=100_000).collect();
let array1: ArrayRef = Arc::new(Int32Array::from(large_values));
let batch1 = RecordBatch::try_new(Arc::clone(&schema), vec![array1])?;
topk.insert_batch(batch1)?;
assert_eq!(
topk.heap.store.len(),
1,
"should have 1 batch before second insert"
);
let array2: ArrayRef = Arc::new(Int32Array::from(vec![-1, 0]));
let batch2 = RecordBatch::try_new(Arc::clone(&schema), vec![array2])?;
let replacements_before = topk.metrics.row_replacements.value();
topk.insert_batch(batch2)?;
assert!(
topk.metrics.row_replacements.value() > replacements_before,
"batch2 must produce replacements so compaction is exercised"
);
assert_eq!(
topk.heap.store.len(),
1,
"store should be compacted to 1 batch"
);
let results: Vec<_> = topk.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+----+", "| a |", "+----+", "| -1 |", "| 0 |", "| 1 |", "| 2 |",
"| 3 |", "+----+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_topk_memory_compaction_skipped_when_marginal() -> Result<()> {
let schema =
Arc::new(Schema::new(vec![Field::new("a", DataType::Boolean, false)]));
let sort_expr = PhysicalSortExpr {
expr: col("a", schema.as_ref())?,
options: SortOptions::default(),
};
let full_expr = LexOrdering::from([sort_expr.clone()]);
let prefix = vec![sort_expr];
let runtime = Arc::new(RuntimeEnv::default());
let metrics = ExecutionPlanMetricsSet::new();
let k = 10;
let mut topk = TopK::try_new(
0,
Arc::clone(&schema),
prefix,
full_expr,
k,
8192,
runtime,
&metrics,
Arc::new(RwLock::new(TopKDynamicFilters::new(Arc::new(
DynamicFilterPhysicalExpr::new(vec![], lit(true)),
)))),
)?;
let batch1 = RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(BooleanArray::from(vec![false, false, true, true, true]))
as ArrayRef,
],
)?;
topk.insert_batch(batch1)?;
let batch2 = RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(BooleanArray::from(vec![false, false, false, true, true]))
as ArrayRef,
],
)?;
topk.insert_batch(batch2)?;
assert_eq!(
topk.heap.store.len(),
2,
"store must keep 2 batches when savings would be marginal"
);
assert_eq!(topk.heap.inner.len(), 10, "heap should hold all 10 rows");
let results: Vec<_> = topk.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+-------+",
"| a |",
"+-------+",
"| false |",
"| false |",
"| false |",
"| false |",
"| false |",
"| true |",
"| true |",
"| true |",
"| true |",
"| true |",
"+-------+",
],
&results
);
Ok(())
}
fn build_partitioned_topk(k: usize) -> Result<(Arc<Schema>, PartitionedTopK)> {
build_partitioned_topk_with_opts(k, SortOptions::default(), false)
}
fn build_partitioned_topk_with_opts(
k: usize,
val_sort_options: SortOptions,
val_nullable: bool,
) -> Result<(Arc<Schema>, PartitionedTopK)> {
build_pk_val_state(
PartitionedTopK::try_new,
k,
val_sort_options,
val_nullable,
&Arc::new(RuntimeEnv::default()),
None,
)
}
fn build_partitioned_topk_with_runtime(
k: usize,
runtime: &Arc<RuntimeEnv>,
) -> Result<(Arc<Schema>, PartitionedTopK)> {
build_pk_val_state(
PartitionedTopK::try_new,
k,
SortOptions::default(),
false,
runtime,
None,
)
}
type StateCtor<T> = fn(
usize,
&SchemaRef,
Vec<Arc<dyn PhysicalExpr>>,
Vec<SortField>,
LexOrdering,
usize,
usize,
&Arc<RuntimeEnv>,
&ExecutionPlanMetricsSet,
Option<SchemaRef>,
) -> Result<T>;
fn build_pk_val_state<T>(
ctor: StateCtor<T>,
k: usize,
val_sort_options: SortOptions,
val_nullable: bool,
runtime: &Arc<RuntimeEnv>,
ranking_field: Option<FieldRef>,
) -> Result<(Arc<Schema>, T)> {
let schema = pk_val_schema(val_nullable);
let pk_expr: Arc<dyn PhysicalExpr> = col("pk", schema.as_ref())?;
let pk_sort_expr = PhysicalSortExpr {
expr: Arc::clone(&pk_expr),
options: SortOptions::default(),
};
let val_sort_expr = PhysicalSortExpr {
expr: col("val", schema.as_ref())?,
options: val_sort_options,
};
let ranked_schema = ranking_field
.map(|field| partitioned_topk_output_schema(&schema, Some(&field)));
let state = ctor(
0,
&schema,
vec![pk_expr],
build_sort_fields(&[pk_sort_expr], &schema)?,
LexOrdering::from([val_sort_expr]),
k,
8, runtime,
&ExecutionPlanMetricsSet::new(),
ranked_schema,
)?;
Ok((schema, state))
}
fn build_emitting<T>(
ctor: StateCtor<T>,
k: usize,
ranking_field: FieldRef,
) -> Result<(Arc<Schema>, T)> {
build_pk_val_state(
ctor,
k,
SortOptions::default(),
false,
&Arc::new(RuntimeEnv::default()),
Some(ranking_field),
)
}
fn build_partitioned_topk_nullable_pk(
k: usize,
pk_sort_options: SortOptions,
) -> Result<(Arc<Schema>, PartitionedTopK)> {
let schema = Arc::new(Schema::new(vec![
Field::new("pk", DataType::Int32, true),
Field::new("val", DataType::Int32, false),
]));
let pk_expr: Arc<dyn PhysicalExpr> = col("pk", schema.as_ref())?;
let partition_ordering = [PhysicalSortExpr {
expr: Arc::clone(&pk_expr),
options: pk_sort_options,
}];
let order_expr = LexOrdering::from([PhysicalSortExpr {
expr: col("val", schema.as_ref())?,
options: SortOptions::default(),
}]);
let state = PartitionedTopK::try_new(
0,
&schema,
vec![pk_expr],
build_sort_fields(&partition_ordering, &schema)?,
order_expr,
k,
8, &Arc::new(RuntimeEnv::default()),
&ExecutionPlanMetricsSet::new(),
None,
)?;
Ok((schema, state))
}
fn nullable_pk_batch(
schema: &Arc<Schema>,
pks: Vec<Option<i32>>,
vals: Vec<i32>,
) -> Result<RecordBatch> {
Ok(RecordBatch::try_new(
Arc::clone(schema),
vec![
Arc::new(Int32Array::from(pks)),
Arc::new(Int32Array::from(vals)),
],
)?)
}
#[tokio::test]
async fn test_partitioned_topk_null_partition_key_nulls_last() -> Result<()> {
let (schema, mut state) = build_partitioned_topk_nullable_pk(
2,
SortOptions {
descending: false,
nulls_first: false,
},
)?;
let batch = nullable_pk_batch(
&schema,
vec![None, Some(1), None, Some(2), None, Some(1)],
vec![9, 4, 3, 8, 5, 2],
)?;
state.insert_batch(&batch)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+----+-----+",
"| pk | val |",
"+----+-----+",
"| 1 | 2 |",
"| 1 | 4 |",
"| 2 | 8 |",
"| | 3 |",
"| | 5 |",
"+----+-----+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_null_partition_key_nulls_first() -> Result<()> {
let (schema, mut state) = build_partitioned_topk_nullable_pk(
2,
SortOptions {
descending: false,
nulls_first: true,
},
)?;
state.insert_batch(&nullable_pk_batch(
&schema,
vec![Some(1), None, Some(1)],
vec![4, 9, 2],
)?)?;
state.insert_batch(&nullable_pk_batch(
&schema,
vec![None, None, Some(2)],
vec![3, 5, 8],
)?)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+----+-----+",
"| pk | val |",
"+----+-----+",
"| | 3 |",
"| | 5 |",
"| 1 | 2 |",
"| 1 | 4 |",
"| 2 | 8 |",
"+----+-----+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_desc_partition_key_ordering() -> Result<()> {
let (schema, mut state) = build_partitioned_topk_nullable_pk(
1,
SortOptions {
descending: true,
nulls_first: false,
},
)?;
let batch = nullable_pk_batch(
&schema,
vec![Some(1), Some(3), Some(2), Some(3)],
vec![10, 30, 20, 31],
)?;
state.insert_batch(&batch)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+----+-----+",
"| pk | val |",
"+----+-----+",
"| 3 | 30 |",
"| 2 | 20 |",
"| 1 | 10 |",
"+----+-----+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_multi_column_partition_key() -> Result<()> {
let schema = Arc::new(Schema::new(vec![
Field::new("pk_a", DataType::Int32, false),
Field::new("pk_b", DataType::Utf8, false),
Field::new("val", DataType::Int32, false),
]));
let pk_a: Arc<dyn PhysicalExpr> = col("pk_a", schema.as_ref())?;
let pk_b: Arc<dyn PhysicalExpr> = col("pk_b", schema.as_ref())?;
let partition_ordering = [
PhysicalSortExpr {
expr: Arc::clone(&pk_a),
options: SortOptions::default(),
},
PhysicalSortExpr {
expr: Arc::clone(&pk_b),
options: SortOptions::default(),
},
];
let order_expr = LexOrdering::from([PhysicalSortExpr {
expr: col("val", schema.as_ref())?,
options: SortOptions::default(),
}]);
let mut state = PartitionedTopK::try_new(
0,
&schema,
vec![pk_a, pk_b],
build_sort_fields(&partition_ordering, &schema)?,
order_expr,
1,
8,
&Arc::new(RuntimeEnv::default()),
&ExecutionPlanMetricsSet::new(),
None,
)?;
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(Int32Array::from(vec![2, 1, 2, 1, 1])),
Arc::new(StringArray::from(vec!["b", "b", "a", "a", "a"])),
Arc::new(Int32Array::from(vec![20, 15, 25, 11, 10])),
],
)?;
state.insert_batch(&batch)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+------+------+-----+",
"| pk_a | pk_b | val |",
"+------+------+-----+",
"| 1 | a | 10 |",
"| 1 | b | 15 |",
"| 2 | a | 25 |",
"| 2 | b | 20 |",
"+------+------+-----+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_runs_under_bounded_memory_pool() -> Result<()> {
const P: i32 = 256;
const ROWS_PER_PARTITION: i32 = 32;
const ROWS: i32 = P * ROWS_PER_PARTITION;
const BATCHES: i32 = 16;
const K: usize = 2;
let schema = pk_val_schema(false);
let pks: Vec<i32> = (0..ROWS).map(|i| i % P).collect();
let vals = |b: i32| -> Vec<i32> {
(0..ROWS)
.map(|i| (BATCHES - b) * ROWS_PER_PARTITION + i / P)
.collect()
};
let batch_bytes =
get_record_batch_memory_size(&pk_val_batch(&schema, pks.clone(), vals(0))?);
let limit = 5 * batch_bytes;
let runtime = RuntimeEnvBuilder::new()
.with_memory_pool(Arc::new(GreedyMemoryPool::new(limit)))
.build_arc()?;
let (schema, mut state) = build_partitioned_topk_with_runtime(K, &runtime)?;
let mut after_first = 0;
for b in 0..BATCHES {
let batch = pk_val_batch(&schema, pks.clone(), vals(b))?;
state.insert_batch(&batch).map_err(|e| {
exec_datafusion_err!(
"batch {b} of {BATCHES} failed under a {limit}-byte pool: {e}"
)
})?;
if b == 0 {
after_first = state.size();
}
}
assert!(
state.size() <= after_first * 2,
"retention grew from {after_first} to {} bytes across {BATCHES} \
batches; it tracks the input rather than K per partition",
state.size()
);
let expected: Vec<(i32, i32)> = (0..P)
.flat_map(|pk| [(pk, ROWS_PER_PARTITION), (pk, ROWS_PER_PARTITION + 1)])
.collect();
assert_eq!(pk_val_rows(state.emit()?).await?, expected);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_emit_keeps_pinned_bytes_reserved() -> Result<()> {
use datafusion_execution::memory_pool::MemoryPool;
let pool = Arc::new(GreedyMemoryPool::new(16 * 1024 * 1024));
let runtime = RuntimeEnvBuilder::new()
.with_memory_pool(Arc::clone(&pool) as Arc<dyn MemoryPool>)
.build_arc()?;
let (schema, mut state) = build_partitioned_topk_with_runtime(2, &runtime)?;
let pks: Vec<i32> = (0..64).map(|i| i % 8).collect();
let vals: Vec<i32> = (0..64).collect();
state.insert_batch(&pk_val_batch(&schema, pks, vals)?)?;
assert!(pool.reserved() > 0, "insert_batch must reserve");
let stream = state.emit()?;
assert!(
pool.reserved() > 0,
"emit released its reservation while the store's batches are still \
pinned by the stream it returned"
);
let results: Vec<RecordBatch> = stream.try_collect().await?;
assert_eq!(
pool.reserved(),
0,
"the reservation must be released once the stream is dropped"
);
let rows: usize = results.iter().map(|b| b.num_rows()).sum();
assert_eq!(rows, 16, "K = 2 for each of 8 partitions");
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_rank_size_is_not_per_partition_batch() -> Result<()> {
const P: i32 = 500;
const ROWS: i32 = 4000;
let pks: Vec<i32> = (0..ROWS).map(|i| i % P).collect();
let vals: Vec<i32> = (0..ROWS).map(|i| i / P).collect();
let (schema, mut rk) = build_partitioned_topk_rank(2)?;
let batch = pk_val_batch(&schema, pks, vals)?;
let batch_size = get_record_batch_memory_size(&batch);
rk.insert_batch(&batch)?;
let rk_size = rk.size();
assert!(
rk_size <= batch_size * 100,
"RANK reported {rk_size} bytes holding K=2 rows from each of {P} \
partitions of a {batch_size}-byte batch; a per-partition batch \
charge has crept back in"
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_rank_ties_do_not_pin_input_batches() -> Result<()> {
let (schema, mut rk) = build_partitioned_topk_rank(1)?;
let mut vals = vec![100; 1000];
vals[0] = 7;
let batch = pk_val_batch(&schema, vec![1; 1000], vals)?;
rk.insert_batch(&batch)?;
let after_first = rk.size();
for _ in 0..7 {
rk.insert_batch(&batch)?;
}
let after_eight = rk.size();
let growth = after_eight - after_first;
assert!(
growth < 2000,
"tie list grew {growth} bytes over 7 batches that contributed \
1 row each; it is holding the source batches"
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_rank_runs_under_bounded_memory_pool() -> Result<()> {
const P: i32 = 256;
const ROWS_PER_PARTITION: i32 = 32;
const ROWS: i32 = P * ROWS_PER_PARTITION;
const BATCHES: i32 = 16;
const K: usize = 2;
let schema = pk_val_schema(false);
let pks: Vec<i32> = (0..ROWS).map(|i| i % P).collect();
let vals = |b: i32| -> Vec<i32> {
(0..ROWS)
.map(|i| (BATCHES - b) * ROWS_PER_PARTITION + i / P)
.collect()
};
let batch_bytes =
get_record_batch_memory_size(&pk_val_batch(&schema, pks.clone(), vals(0))?);
let limit = 32 * batch_bytes;
let runtime = RuntimeEnvBuilder::new()
.with_memory_pool(Arc::new(GreedyMemoryPool::new(limit)))
.build_arc()?;
let (schema, mut rk) = build_partitioned_topk_rank_with_runtime(K, &runtime)?;
let mut after_first = 0;
for b in 0..BATCHES {
let batch = pk_val_batch(&schema, pks.clone(), vals(b))?;
rk.insert_batch(&batch).map_err(|e| {
exec_datafusion_err!(
"batch {b} of {BATCHES} failed under a {limit}-byte pool: {e}"
)
})?;
if b == 0 {
after_first = rk.size();
}
}
assert!(
rk.size() <= after_first * 2,
"retention grew from {after_first} to {} bytes across {BATCHES} \
batches; it tracks the input rather than a bounded window of it",
rk.size()
);
let expected: Vec<(i32, i32)> = (0..P)
.flat_map(|pk| [(pk, ROWS_PER_PARTITION), (pk, ROWS_PER_PARTITION + 1)])
.collect();
assert_eq!(sorted_pk_val(rk.emit()?).await?, expected);
Ok(())
}
struct DiffShape {
seed: u64,
k: usize,
n_partitions: i32,
n_values: i32,
batches: Vec<(Vec<i32>, Vec<i32>)>,
}
impl std::fmt::Display for DiffShape {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"seed={} k={} partitions={} values={} batches={}",
self.seed,
self.k,
self.n_partitions,
self.n_values,
self.batches.len()
)
}
}
impl DiffShape {
fn new(seed: u64, max_values: i32) -> Self {
use rand::rngs::StdRng;
use rand::{Rng, SeedableRng};
let mut rng = StdRng::seed_from_u64(seed);
let k = rng.random_range(1..5usize);
let n_partitions = rng.random_range(1..4i32);
let n_values = rng.random_range(1..max_values);
let n_batches = rng.random_range(1..5usize);
let batches = (0..n_batches)
.map(|_| {
let rows = rng.random_range(1..12usize);
let pks = (0..rows)
.map(|_| rng.random_range(0..n_partitions))
.collect();
let vals = (0..rows).map(|_| rng.random_range(0..n_values)).collect();
(pks, vals)
})
.collect();
Self {
seed,
k,
n_partitions,
n_values,
batches,
}
}
fn all_rows(&self) -> Vec<(i32, i32)> {
self.batches
.iter()
.flat_map(|(pks, vals)| pks.iter().copied().zip(vals.iter().copied()))
.collect()
}
fn expected_row_number(&self) -> Vec<(i32, i32)> {
let mut by_pk: std::collections::BTreeMap<i32, Vec<i32>> =
std::collections::BTreeMap::new();
for (pk, val) in self.all_rows() {
by_pk.entry(pk).or_default().push(val);
}
let mut kept: Vec<(i32, i32)> = Vec::new();
for (pk, mut vals) in by_pk {
vals.sort_unstable();
kept.extend(vals.into_iter().take(self.k).map(|v| (pk, v)));
}
kept
}
fn expected(
&self,
rank_of: impl Fn(&[(i32, i32)], i32, i32) -> usize,
) -> Vec<(i32, i32)> {
let all = self.all_rows();
let mut kept: Vec<(i32, i32)> = all
.iter()
.copied()
.filter(|&(pk, val)| rank_of(&all, pk, val) <= self.k)
.collect();
kept.sort_unstable();
kept
}
}
async fn pk_val_rows(stream: SendableRecordBatchStream) -> Result<Vec<(i32, i32)>> {
let batches: Vec<RecordBatch> = stream.try_collect().await?;
let mut rows: Vec<(i32, i32)> = Vec::new();
for b in &batches {
let pk = b.column(0).as_primitive::<Int32Type>();
let val = b.column(1).as_primitive::<Int32Type>();
for i in 0..b.num_rows() {
rows.push((pk.value(i), val.value(i)));
}
}
Ok(rows)
}
async fn sorted_pk_val(stream: SendableRecordBatchStream) -> Result<Vec<(i32, i32)>> {
let mut rows = pk_val_rows(stream).await?;
assert!(
rows.windows(2).all(|w| w[0] <= w[1]),
"emitted rows are not in (pk, val) order: {rows:?}"
);
rows.sort_unstable();
Ok(rows)
}
#[tokio::test]
async fn test_partitioned_topk_matches_bruteforce() -> Result<()> {
for seed in 0..64u64 {
let shape = DiffShape::new(seed, 6);
let (schema, mut state) = build_partitioned_topk(shape.k)?;
for (pks, vals) in &shape.batches {
state.insert_batch(&pk_val_batch(&schema, pks.clone(), vals.clone())?)?;
}
assert_eq!(
pk_val_rows(state.emit()?).await?,
shape.expected_row_number(),
"{shape}"
);
}
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_payload_survives_supersession() -> Result<()> {
let (schema, mut state) = build_partitioned_topk(1)?;
state.insert_batch(&pk_val_batch(
&schema,
vec![0, 1, 0, 1, 0],
vec![9, 8, 3, 2, 1],
)?)?;
assert_eq!(pk_val_rows(state.emit()?).await?, vec![(0, 1), (1, 2)]);
let (schema, mut state) = build_partitioned_topk(2)?;
state.insert_batch(&pk_val_batch(&schema, vec![0, 0, 0], vec![4, 7, 5])?)?;
assert_eq!(pk_val_rows(state.emit()?).await?, vec![(0, 4), (0, 5)]);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_store_releases_superseded_batches() -> Result<()> {
const K: usize = 2;
let (schema, mut state) = build_partitioned_topk(K)?;
state.insert_batch(&pk_val_batch(&schema, vec![0, 0], vec![50, 60])?)?;
assert_eq!(state.core.store.len(), 1, "the batch every slot points at");
let first_id = *state.core.store.batches.keys().next().expect("one entry");
state.insert_batch(&pk_val_batch(&schema, vec![0, 0], vec![70, 80])?)?;
assert_eq!(
state.core.store.len(),
1,
"a fully-rejected batch must not be registered"
);
state.insert_batch(&pk_val_batch(&schema, vec![0, 0], vec![10, 20])?)?;
assert_eq!(
state.core.store.len(),
1,
"superseded batch 0 must be released, not accumulated"
);
assert!(
!state.core.store.batches.contains_key(&first_id),
"the released entry must be the superseded one"
);
state.insert_batch(&pk_val_batch(&schema, vec![0], vec![5])?)?;
assert_eq!(
state.core.store.len(),
2,
"a batch still holding one live row must stay pinned"
);
assert_eq!(pk_val_rows(state.emit()?).await?, vec![(0, 5), (0, 10)]);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_store_compacts_when_survivors_spread() -> Result<()> {
const B: i32 = 512;
let (schema, mut state) = build_partitioned_topk(1)?;
for j in 0..B {
let pks: Vec<i32> = (0..B).collect();
let vals: Vec<i32> = (0..B).map(|p| (j - p).abs()).collect();
state.insert_batch(&pk_val_batch(&schema, pks, vals)?)?;
}
assert_eq!(state.core.live_slots, B as usize);
let pinned: usize = state
.core
.store
.batches
.values()
.map(|e| e.batch.num_rows())
.sum();
assert_eq!(
pinned, state.core.store.total_rows,
"store row count is exact"
);
let bound = B as usize * STORE_COMPACTION_RATIO;
assert!(
pinned <= bound,
"{pinned} rows pinned to retain {} — above the {bound}-row bound, so \
retention tracks the input rather than the rows held",
state.core.live_slots
);
let expected: Vec<(i32, i32)> = (0..B).map(|pk| (pk, 0)).collect();
assert_eq!(pk_val_rows(state.emit()?).await?, expected);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_store_compacts_a_single_oversized_entry() -> Result<()>
{
const ROWS: i32 = 200;
let (schema, mut state) = build_partitioned_topk(1)?;
state.insert_batch(&pk_val_batch(
&schema,
vec![0; ROWS as usize],
(0..ROWS).map(|i| ROWS - i).collect(),
)?)?;
assert_eq!(state.core.live_slots, 1, "K = 1 in a single partition");
assert_eq!(
state.core.store.len(),
1,
"one input batch, one gathered entry"
);
assert!(
state.core.store.total_rows <= state.core.live_slots * STORE_COMPACTION_RATIO,
"{} rows pinned to retain {}; a single entry escaped compaction",
state.core.store.total_rows,
state.core.live_slots
);
assert_eq!(pk_val_rows(state.emit()?).await?, vec![(0, 1)]);
Ok(())
}
fn assert_store_invariants(state: &PartitionedTopK, label: &str) {
let slots: Vec<StoreRef> = state
.core
.partitions
.values()
.flat_map(PartitionHeap::store_rows)
.collect();
assert_store_matches_slots(
&state.core.store,
state.core.live_slots,
&slots,
label,
);
assert_eq!(
state.core.reservation.size(),
state.size(),
"{label}: the reservation does not match size()"
);
}
fn assert_store_matches_slots(
store: &RecordBatchStore,
live_slots: usize,
slots: &[StoreRef],
label: &str,
) {
assert_eq!(
slots.len(),
live_slots,
"{label}: live_slots disagrees with the slots held"
);
let mut refs: HashMap<u32, usize> = HashMap::new();
for slot in slots {
let entry = store.get(slot.batch_id).unwrap_or_else(|| {
panic!(
"{label}: slot points at batch {} which the store does not hold",
slot.batch_id
)
});
assert!(
(slot.row as usize) < entry.batch.num_rows(),
"{label}: slot row {} is outside entry {} ({} rows)",
slot.row,
slot.batch_id,
entry.batch.num_rows()
);
*refs.entry(slot.batch_id).or_default() += 1;
}
assert_eq!(
refs.len(),
store.len(),
"{label}: the store holds entries nothing points at"
);
for (id, entry) in &store.batches {
let expected = refs.get(id).copied().unwrap_or(0);
assert_eq!(
entry.uses, expected,
"{label}: entry {id} has uses={} but {expected} slots point at it",
entry.uses
);
}
let rows: usize = store.batches.values().map(|e| e.batch.num_rows()).sum();
assert_eq!(rows, store.total_rows, "{label}: store.total_rows drifted");
let mut counter = RecordBatchMemoryCounter::new();
let bytes: usize = store
.batches
.values()
.map(|e| counter.count_batch(&e.batch))
.sum();
assert_eq!(
bytes, store.batches_size,
"{label}: store.batches_size drifted"
);
assert!(
store.total_rows <= live_slots * STORE_COMPACTION_RATIO,
"{label}: {} rows pinned to retain {live_slots}",
store.total_rows
);
}
#[tokio::test]
async fn test_partitioned_topk_store_bookkeeping_holds_under_stress() -> Result<()> {
use rand::rngs::StdRng;
use rand::{Rng, SeedableRng};
struct Case {
name: &'static str,
k: usize,
partitions: i32,
values: i32,
batches: usize,
rows: usize,
descending: bool,
one_partition_per_batch: bool,
}
let cases = [
Case {
name: "k1_one_partition_per_batch",
k: 1,
partitions: 64,
values: 1_000,
batches: 64,
rows: 16,
descending: false,
one_partition_per_batch: true,
},
Case {
name: "k1_descending_runs",
k: 1,
partitions: 3,
values: 1_000,
batches: 20,
rows: 50,
descending: true,
one_partition_per_batch: false,
},
Case {
name: "all_ties_uses_zero",
k: 2,
partitions: 1,
values: 1,
batches: 20,
rows: 30,
descending: false,
one_partition_per_batch: false,
},
Case {
name: "k_exceeds_partition_size",
k: 40,
partitions: 50,
values: 1_000,
batches: 30,
rows: 10,
descending: false,
one_partition_per_batch: false,
},
Case {
name: "wide_churn",
k: 3,
partitions: 12,
values: 20,
batches: 40,
rows: 64,
descending: false,
one_partition_per_batch: false,
},
];
for case in cases {
for seed in 0..4u64 {
let mut rng = StdRng::seed_from_u64(seed);
let (schema, mut state) = build_partitioned_topk(case.k)?;
let mut all_rows: Vec<(i32, i32)> = Vec::new();
for b in 0..case.batches {
let pks: Vec<i32> = if case.one_partition_per_batch {
vec![(b as i32) % case.partitions; case.rows]
} else {
(0..case.rows)
.map(|_| rng.random_range(0..case.partitions))
.collect()
};
let mut vals: Vec<i32> = (0..case.rows)
.map(|_| rng.random_range(0..case.values))
.collect();
if case.descending {
vals.sort_unstable_by(|a, b| b.cmp(a));
}
all_rows.extend(pks.iter().copied().zip(vals.iter().copied()));
state.insert_batch(&pk_val_batch(&schema, pks, vals)?)?;
assert_store_invariants(
&state,
&format!("{} seed {seed} batch {b}", case.name),
);
}
let mut expected: Vec<(i32, i32)> = Vec::new();
let mut pks: Vec<i32> = all_rows.iter().map(|&(p, _)| p).collect();
pks.sort_unstable();
pks.dedup();
for pk in pks {
let mut vals: Vec<i32> = all_rows
.iter()
.filter(|&&(p, _)| p == pk)
.map(|&(_, v)| v)
.collect();
vals.sort_unstable();
vals.truncate(case.k);
expected.extend(vals.into_iter().map(|v| (pk, v)));
}
assert_eq!(
pk_val_rows(state.emit()?).await?,
expected,
"{} seed {seed}",
case.name
);
}
}
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_unused_gather_id_is_reused() -> Result<()> {
let (schema, mut state) = build_partitioned_topk(1)?;
state.insert_batch(&pk_val_batch(&schema, vec![0], vec![5])?)?;
assert_eq!(
state.core.store.next_batch_id(),
1,
"batch 0 consumed its id"
);
state.insert_batch(&pk_val_batch(&schema, vec![0, 0, 0], vec![7, 8, 9])?)?;
assert_eq!(state.core.store.next_batch_id(), 1, "no admission, no id");
assert_eq!(state.core.store.len(), 1);
assert_store_invariants(&state, "after a batch with no admissions");
state.insert_batch(&pk_val_batch(&schema, vec![0, 0, 0], vec![4, 3, 2])?)?;
assert_store_invariants(&state, "after a self-superseding batch");
assert_eq!(state.core.store.len(), 1, "batch 0's entry was released");
assert_eq!(
state.core.store.total_rows, 1,
"compaction dropped the dead rows"
);
let after_compaction = state.core.store.next_batch_id();
state.insert_batch(&pk_val_batch(&schema, vec![0, 0], vec![3, 6])?)?;
assert_eq!(
state.core.store.next_batch_id(),
after_compaction,
"every admission was superseded, so the id must be reusable"
);
assert_store_invariants(&state, "after a fully superseded batch");
assert_eq!(pk_val_rows(state.emit()?).await?, vec![(0, 2)]);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_size_accounts_for_retained_keys() -> Result<()> {
const PARTITIONS: usize = 200;
const K: usize = 4;
const KEY_WIDTH: usize = 512;
let schema = Arc::new(Schema::new(vec![
Field::new("pk", DataType::Int32, false),
Field::new("val", DataType::Utf8, false),
]));
let pk_expr: Arc<dyn PhysicalExpr> = col("pk", schema.as_ref())?;
let partition_ordering = [PhysicalSortExpr {
expr: Arc::clone(&pk_expr),
options: SortOptions::default(),
}];
let order_expr = LexOrdering::from([PhysicalSortExpr {
expr: col("val", schema.as_ref())?,
options: SortOptions::default(),
}]);
let mut state = PartitionedTopK::try_new(
0,
&schema,
vec![pk_expr],
build_sort_fields(&partition_ordering, &schema)?,
order_expr,
K,
8,
&Arc::new(RuntimeEnv::default()),
&ExecutionPlanMetricsSet::new(),
None,
)?;
let empty = state.size();
let mut pks: Vec<i32> = Vec::new();
let mut vals: Vec<String> = Vec::new();
for p in 0..PARTITIONS {
for i in 0..K {
pks.push(p as i32);
vals.push(format!("{p:0>width$}{i}", width = KEY_WIDTH - 1));
}
}
state.insert_batch(&RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(Int32Array::from(pks)),
Arc::new(StringArray::from(vals)),
],
)?)?;
assert_eq!(
state.core.live_slots,
PARTITIONS * K,
"every row should have been retained"
);
let key_bytes = PARTITIONS * K * KEY_WIDTH;
assert!(
state.core.heaps_bytes >= key_bytes,
"heaps_bytes is {} but the retained keys are at least {key_bytes} bytes",
state.core.heaps_bytes
);
assert!(
state.size() >= empty + key_bytes,
"size() grew by {} for {key_bytes} bytes of retained keys",
state.size() - empty
);
assert!(
state.core.index_bytes >= PARTITIONS,
"index_bytes is {} for {PARTITIONS} interned keys",
state.core.index_bytes
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_dense_rank_matches_bruteforce() -> Result<()> {
for seed in 0..64u64 {
let shape = DiffShape::new(seed, 8);
let (schema, mut state) = build_partitioned_topk_dense_rank(shape.k)?;
for (pks, vals) in &shape.batches {
state.insert_batch(&pk_val_batch(&schema, pks.clone(), vals.clone())?)?;
}
let expected = shape.expected(|rows, pk, val| {
1 + rows
.iter()
.filter(|&&(p, v)| p == pk && v < val)
.map(|&(_, v)| v)
.collect::<std::collections::BTreeSet<_>>()
.len()
});
assert_eq!(sorted_pk_val(state.emit()?).await?, expected, "{shape}");
}
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_dense_rank_contents_bytes_tracks_recompute()
-> Result<()> {
let mut saw_eviction = false;
for seed in 0..64u64 {
let shape = DiffShape::new(seed, 8);
let (schema, mut state) = build_partitioned_topk_dense_rank(shape.k)?;
for (pks, vals) in &shape.batches {
state.insert_batch(&pk_val_batch(&schema, pks.clone(), vals.clone())?)?;
for (pk, partition) in &state.states {
assert_eq!(
partition.contents_bytes,
partition.recompute_contents_bytes(),
"seed {seed}, partition {pk:?}: {shape}"
);
}
}
saw_eviction |= state.metrics.row_replacements.value() > 0;
}
assert!(saw_eviction, "workload never evicted a group");
Ok(())
}
fn pk_val_schema(val_nullable: bool) -> Arc<Schema> {
Arc::new(Schema::new(vec![
Field::new("pk", DataType::Int32, false),
Field::new("val", DataType::Int32, val_nullable),
]))
}
fn pk_val_batch(
schema: &Arc<Schema>,
pks: Vec<i32>,
vals: Vec<i32>,
) -> Result<RecordBatch> {
Ok(RecordBatch::try_new(
Arc::clone(schema),
vec![
Arc::new(Int32Array::from(pks)),
Arc::new(Int32Array::from(vals)),
],
)?)
}
fn nullable_pk_val_batch(
schema: &Arc<Schema>,
pks: Vec<i32>,
vals: Vec<Option<i32>>,
) -> Result<RecordBatch> {
Ok(RecordBatch::try_new(
Arc::clone(schema),
vec![
Arc::new(Int32Array::from(pks)),
Arc::new(Int32Array::from(vals)),
],
)?)
}
#[tokio::test]
async fn test_partitioned_topk_output_batches_metric_counts_emitted_batches()
-> Result<()> {
let schema = Arc::new(Schema::new(vec![
Field::new("pk", DataType::Int32, false),
Field::new("val", DataType::Int32, false),
]));
let pk_expr: Arc<dyn PhysicalExpr> = col("pk", schema.as_ref())?;
let partition_ordering = vec![PhysicalSortExpr {
expr: Arc::clone(&pk_expr),
options: SortOptions::default(),
}];
let metrics = ExecutionPlanMetricsSet::new();
let order_ordering = [PhysicalSortExpr {
expr: col("val", schema.as_ref())?,
options: SortOptions::default(),
}];
let mut state = PartitionedTopK::try_new(
0,
&schema,
vec![pk_expr],
build_sort_fields(&partition_ordering, &schema)?,
LexOrdering::from(order_ordering.clone()),
2,
3, &Arc::new(RuntimeEnv::default()),
&metrics,
None,
)?;
state.insert_batch(&pk_val_batch(
&schema,
vec![1, 1, 2, 2, 3, 3],
vec![10, 5, 20, 15, 30, 25],
)?)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
let row_counts: Vec<usize> = results.iter().map(|b| b.num_rows()).collect();
assert_eq!(row_counts, vec![3, 3]);
assert_eq!(output_batches_and_rows(&metrics), (2, 6));
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_emits_row_number_column() -> Result<()> {
let rn_field = Arc::new(Field::new("rn", DataType::UInt64, false));
let (schema, mut state) =
build_emitting(PartitionedTopK::try_new, 3, Arc::clone(&rn_field))?;
state.insert_batch(&pk_val_batch(
&schema,
vec![1, 2, 1, 1, 1],
vec![30, 5, 10, 20, 40],
)?)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_eq!(
results[0].schema().field(2),
rn_field.as_ref(),
"the appended field is the one the caller asked for"
);
assert_batches_eq!(
&[
"+----+-----+----+",
"| pk | val | rn |",
"+----+-----+----+",
"| 1 | 10 | 1 |",
"| 1 | 20 | 2 |",
"| 1 | 30 | 3 |",
"| 2 | 5 | 1 |",
"+----+-----+----+",
],
&results
);
Ok(())
}
fn ranking_chunk_batches(schema: &SchemaRef) -> Result<[RecordBatch; 2]> {
Ok([
pk_val_batch(schema, vec![1; 7], vec![1, 1, 1, 2, 2, 2, 3])?,
pk_val_batch(schema, vec![1, 1, 1, 1, 1, 2, 2], vec![3, 3, 4, 4, 4, 5, 5])?,
])
}
fn vals_and_ranks(batches: &[RecordBatch]) -> (Vec<(i32, u64)>, usize) {
let mut rows = Vec::new();
for batch in batches {
let vals = batch.column(1).as_primitive::<Int32Type>();
let ranks = batch.column(2).as_primitive::<UInt64Type>();
rows.extend(
vals.values()
.iter()
.copied()
.zip(ranks.values().iter().copied()),
);
}
(rows, batches.len())
}
#[tokio::test]
async fn test_partitioned_topk_row_number_column_spans_output_chunks() -> Result<()> {
let rn = Arc::new(Field::new("rn", DataType::UInt64, false));
let (schema, mut state) = build_emitting(PartitionedTopK::try_new, 10, rn)?;
for batch in ranking_chunk_batches(&schema)? {
state.insert_batch(&batch)?;
}
let results: Vec<_> = state.emit()?.try_collect().await?;
let (rows, chunks) = vals_and_ranks(&results);
assert_eq!(chunks, 2);
assert_eq!(
rows,
vec![
(1, 1),
(1, 2),
(1, 3),
(2, 4),
(2, 5),
(2, 6),
(3, 7),
(3, 8),
(3, 9),
(4, 10),
(5, 1),
(5, 2),
]
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_rank_column_spans_output_chunks() -> Result<()> {
let rk = Arc::new(Field::new("rk", DataType::UInt64, false));
let (schema, mut state) = build_emitting(PartitionedTopKRank::try_new, 10, rk)?;
for batch in ranking_chunk_batches(&schema)? {
state.insert_batch(&batch)?;
}
let results: Vec<_> = state.emit()?.try_collect().await?;
let (rows, chunks) = vals_and_ranks(&results);
assert_eq!(chunks, 2);
assert_eq!(
rows,
vec![
(1, 1),
(1, 1),
(1, 1),
(2, 4),
(2, 4),
(2, 4),
(3, 7),
(3, 7),
(3, 7),
(4, 10),
(4, 10),
(4, 10),
(5, 1),
(5, 1),
]
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_dense_rank_column_spans_output_chunks() -> Result<()> {
let dr = Arc::new(Field::new("dr", DataType::UInt64, false));
let (schema, mut state) =
build_emitting(PartitionedTopKDenseRank::try_new, 3, dr)?;
for batch in ranking_chunk_batches(&schema)? {
state.insert_batch(&batch)?;
}
let results: Vec<_> = state.emit()?.try_collect().await?;
let (rows, chunks) = vals_and_ranks(&results);
assert_eq!(chunks, 2);
assert_eq!(
rows,
vec![
(1, 1),
(1, 1),
(1, 1),
(2, 2),
(2, 2),
(2, 2),
(3, 3),
(3, 3),
(3, 3),
(5, 1),
(5, 1),
]
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_multi_partition_within_batch() -> Result<()> {
let (schema, mut state) = build_partitioned_topk(2)?;
let batch =
pk_val_batch(&schema, vec![1, 2, 1, 2, 1, 3], vec![10, 20, 5, 15, 8, 7])?;
state.insert_batch(&batch)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+----+-----+",
"| pk | val |",
"+----+-----+",
"| 1 | 5 |",
"| 1 | 8 |",
"| 2 | 15 |",
"| 2 | 20 |",
"| 3 | 7 |",
"+----+-----+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_cross_batch_eviction() -> Result<()> {
let (schema, mut state) = build_partitioned_topk(2)?;
state.insert_batch(&pk_val_batch(&schema, vec![1, 1], vec![50, 40])?)?;
state.insert_batch(&pk_val_batch(
&schema,
vec![1, 2, 1],
vec![10, 99, 60], )?)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+----+-----+",
"| pk | val |",
"+----+-----+",
"| 1 | 10 |",
"| 1 | 40 |",
"| 2 | 99 |",
"+----+-----+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_empty_input() -> Result<()> {
let (_schema, state) = build_partitioned_topk(3)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert!(results.is_empty(), "empty input → empty output");
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_fetch_one() -> Result<()> {
let (schema, mut state) = build_partitioned_topk(1)?;
state.insert_batch(&pk_val_batch(
&schema,
vec![1, 1, 2, 2, 3],
vec![3, 1, 9, 4, 7],
)?)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+----+-----+",
"| pk | val |",
"+----+-----+",
"| 1 | 1 |",
"| 2 | 4 |",
"| 3 | 7 |",
"+----+-----+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_desc_ordering() -> Result<()> {
let (schema, mut state) = build_partitioned_topk_with_opts(
2,
SortOptions {
descending: true,
nulls_first: false,
},
false,
)?;
let batch = pk_val_batch(
&schema,
vec![1, 2, 1, 2, 1, 1, 2],
vec![10, 20, 5, 15, 8, 12, 25],
)?;
state.insert_batch(&batch)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+----+-----+",
"| pk | val |",
"+----+-----+",
"| 1 | 12 |",
"| 1 | 10 |",
"| 2 | 25 |",
"| 2 | 20 |",
"+----+-----+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_nulls_last_ordering() -> Result<()> {
let (schema, mut state) = build_partitioned_topk_with_opts(
1,
SortOptions {
descending: false,
nulls_first: false,
},
true,
)?;
let batch = nullable_pk_val_batch(
&schema,
vec![1, 2, 1, 1, 3, 3, 3],
vec![None, None, Some(7), None, None, Some(4), Some(2)],
)?;
state.insert_batch(&batch)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+----+-----+",
"| pk | val |",
"+----+-----+",
"| 1 | 7 |",
"| 2 | |",
"| 3 | 2 |",
"+----+-----+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_nulls_first_ordering() -> Result<()> {
let (schema, mut state) = build_partitioned_topk_with_opts(
2,
SortOptions {
descending: false,
nulls_first: true,
},
true,
)?;
let batch = nullable_pk_val_batch(
&schema,
vec![1, 2, 1, 3, 1, 2, 1, 3],
vec![
None,
Some(7),
Some(5),
Some(3),
None,
None,
Some(8),
Some(1),
],
)?;
state.insert_batch(&batch)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+----+-----+",
"| pk | val |",
"+----+-----+",
"| 1 | |",
"| 1 | |",
"| 2 | |",
"| 2 | 7 |",
"| 3 | 1 |",
"| 3 | 3 |",
"+----+-----+",
],
&results
);
Ok(())
}
fn build_partitioned_topk_rank(
k: usize,
) -> Result<(Arc<Schema>, PartitionedTopKRank)> {
build_partitioned_topk_rank_with_opts(k, SortOptions::default(), false)
}
fn build_partitioned_topk_rank_with_opts(
k: usize,
val_sort_options: SortOptions,
val_nullable: bool,
) -> Result<(Arc<Schema>, PartitionedTopKRank)> {
build_pk_val_state(
PartitionedTopKRank::try_new,
k,
val_sort_options,
val_nullable,
&Arc::new(RuntimeEnv::default()),
None,
)
}
fn build_partitioned_topk_rank_with_runtime(
k: usize,
runtime: &Arc<RuntimeEnv>,
) -> Result<(Arc<Schema>, PartitionedTopKRank)> {
build_pk_val_state(
PartitionedTopKRank::try_new,
k,
SortOptions::default(),
false,
runtime,
None,
)
}
#[tokio::test]
async fn test_partitioned_topk_rank_multi_partition_within_batch() -> Result<()> {
let (schema, mut state) = build_partitioned_topk_rank(2)?;
let batch =
pk_val_batch(&schema, vec![1, 2, 1, 2, 1, 3], vec![10, 20, 5, 15, 8, 7])?;
state.insert_batch(&batch)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+----+-----+",
"| pk | val |",
"+----+-----+",
"| 1 | 5 |",
"| 1 | 8 |",
"| 2 | 15 |",
"| 2 | 20 |",
"| 3 | 7 |",
"+----+-----+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_rank_cross_batch_eviction() -> Result<()> {
let (schema, mut state) = build_partitioned_topk_rank(2)?;
state.insert_batch(&pk_val_batch(&schema, vec![1, 1], vec![50, 40])?)?;
state.insert_batch(&pk_val_batch(&schema, vec![1, 2, 1], vec![10, 99, 60])?)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+----+-----+",
"| pk | val |",
"+----+-----+",
"| 1 | 10 |",
"| 1 | 40 |",
"| 2 | 99 |",
"+----+-----+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_rank_empty_input() -> Result<()> {
let (_schema, state) = build_partitioned_topk_rank(3)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert!(results.is_empty(), "empty input → empty output");
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_rank_fetch_one() -> Result<()> {
let (schema, mut state) = build_partitioned_topk_rank(1)?;
state.insert_batch(&pk_val_batch(
&schema,
vec![1, 1, 2, 2, 3],
vec![3, 1, 9, 4, 7],
)?)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+----+-----+",
"| pk | val |",
"+----+-----+",
"| 1 | 1 |",
"| 2 | 4 |",
"| 3 | 7 |",
"+----+-----+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_rank_desc_ordering() -> Result<()> {
let (schema, mut state) = build_partitioned_topk_rank_with_opts(
2,
SortOptions {
descending: true,
nulls_first: false,
},
false,
)?;
let batch = pk_val_batch(
&schema,
vec![1, 2, 1, 2, 1, 1, 2],
vec![10, 20, 5, 15, 8, 12, 25],
)?;
state.insert_batch(&batch)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+----+-----+",
"| pk | val |",
"+----+-----+",
"| 1 | 12 |",
"| 1 | 10 |",
"| 2 | 25 |",
"| 2 | 20 |",
"+----+-----+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_rank_nulls_last_ordering() -> Result<()> {
let (schema, mut state) = build_partitioned_topk_rank_with_opts(
1,
SortOptions {
descending: false,
nulls_first: false,
},
true,
)?;
let batch = nullable_pk_val_batch(
&schema,
vec![1, 2, 1, 1, 3, 3, 3],
vec![None, None, Some(7), None, None, Some(4), Some(2)],
)?;
state.insert_batch(&batch)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+----+-----+",
"| pk | val |",
"+----+-----+",
"| 1 | 7 |",
"| 2 | |",
"| 3 | 2 |",
"+----+-----+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_rank_nulls_first_ordering() -> Result<()> {
let (schema, mut state) = build_partitioned_topk_rank_with_opts(
2,
SortOptions {
descending: false,
nulls_first: true,
},
true,
)?;
let batch = nullable_pk_val_batch(
&schema,
vec![1, 2, 1, 3, 1, 2, 1, 3],
vec![
None,
Some(7),
Some(5),
Some(3),
None,
None,
Some(8),
Some(1),
],
)?;
state.insert_batch(&batch)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+----+-----+",
"| pk | val |",
"+----+-----+",
"| 1 | |",
"| 1 | |",
"| 2 | |",
"| 2 | 7 |",
"| 3 | 1 |",
"| 3 | 3 |",
"+----+-----+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_rank_boundary_ties_retained() -> Result<()> {
let (schema, mut state) = build_partitioned_topk_rank(2)?;
let batch = pk_val_batch(&schema, vec![1, 1, 1, 1], vec![5, 5, 10, 5])?;
state.insert_batch(&batch)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+----+-----+",
"| pk | val |",
"+----+-----+",
"| 1 | 5 |",
"| 1 | 5 |",
"| 1 | 5 |",
"+----+-----+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_rank_emits_rank_column() -> Result<()> {
let rk_field = Arc::new(Field::new("rk", DataType::UInt64, false));
let (schema, mut state) =
build_emitting(PartitionedTopKRank::try_new, 2, Arc::clone(&rk_field))?;
state.insert_batch(&pk_val_batch(
&schema,
vec![1, 1, 1, 2, 2, 3, 3, 3],
vec![10, 20, 20, 5, 5, 7, 7, 7],
)?)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_eq!(results[0].schema().field(2), rk_field.as_ref());
assert_batches_eq!(
&[
"+----+-----+----+",
"| pk | val | rk |",
"+----+-----+----+",
"| 1 | 10 | 1 |",
"| 1 | 20 | 2 |",
"| 1 | 20 | 2 |",
"| 2 | 5 | 1 |",
"| 2 | 5 | 1 |",
"| 3 | 7 | 1 |",
"| 3 | 7 | 1 |",
"| 3 | 7 | 1 |",
"+----+-----+----+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_rank_emits_rank_after_boundary_moves() -> Result<()> {
let rk_field = Arc::new(Field::new("rk", DataType::UInt64, false));
let (schema, mut state) =
build_emitting(PartitionedTopKRank::try_new, 2, Arc::clone(&rk_field))?;
state.insert_batch(&pk_val_batch(&schema, vec![1, 1], vec![20, 20])?)?;
state.insert_batch(&pk_val_batch(&schema, vec![1], vec![10])?)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+----+-----+----+",
"| pk | val | rk |",
"+----+-----+----+",
"| 1 | 10 | 1 |",
"| 1 | 20 | 2 |",
"| 1 | 20 | 2 |",
"+----+-----+----+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_rank_output_rows_counts_ties_once() -> Result<()> {
let schema = pk_val_schema(false);
let pk_expr: Arc<dyn PhysicalExpr> = col("pk", schema.as_ref())?;
let pk_sort_expr = PhysicalSortExpr {
expr: Arc::clone(&pk_expr),
options: SortOptions::default(),
};
let val_sort_expr = PhysicalSortExpr {
expr: col("val", schema.as_ref())?,
options: SortOptions::default(),
};
let metrics = ExecutionPlanMetricsSet::new();
let mut state = PartitionedTopKRank::try_new(
0,
&schema,
vec![pk_expr],
build_sort_fields(&[pk_sort_expr], &schema)?,
LexOrdering::from([val_sort_expr]),
2,
8, &Arc::new(RuntimeEnv::default()),
&metrics,
None,
)?;
let batch = pk_val_batch(&schema, vec![1, 1, 1, 1], vec![5, 5, 10, 5])?;
state.insert_batch(&batch)?;
let results: Vec<RecordBatch> = state.emit()?.try_collect().await?;
let emitted_rows: usize = results.iter().map(|b| b.num_rows()).sum();
assert_eq!(emitted_rows, 3);
assert_eq!(
output_batches_and_rows(&metrics),
(results.len(), emitted_rows)
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_rank_boundary_shifts_clears_ties() -> Result<()> {
let (schema, mut state) = build_partitioned_topk_rank(2)?;
let batch = pk_val_batch(&schema, vec![1, 1, 1, 1, 1], vec![10, 10, 10, 5, 3])?;
state.insert_batch(&batch)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+----+-----+",
"| pk | val |",
"+----+-----+",
"| 1 | 3 |",
"| 1 | 5 |",
"+----+-----+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_rank_row_replacements_counts_ties() -> Result<()> {
let (schema, mut state) = build_partitioned_topk_rank(2)?;
let batch =
pk_val_batch(&schema, vec![1, 1, 1, 1, 1, 1], vec![10, 10, 10, 20, 10, 5])?;
state.insert_batch(&batch)?;
assert_eq!(state.core.metrics.row_replacements.value(), 5);
let results: Vec<_> = state.emit()?.try_collect().await?;
let emitted: usize = results.iter().map(RecordBatch::num_rows).sum();
assert_eq!(emitted, 5);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_rank_boundary_move_frees_tie_capacity() -> Result<()> {
let (schema, mut state) = build_partitioned_topk_rank(2)?;
let batch = pk_val_batch(&schema, vec![1; 7], vec![10, 10, 10, 10, 10, 5, 3])?;
state.insert_batch(&batch)?;
let partition = state
.core
.partitions
.values()
.next()
.expect("one partition");
assert!(partition.ties.is_empty());
assert_eq!(partition.ties.capacity(), 0, "tie capacity must be freed");
assert_eq!(state.ties_bytes, 0);
assert_eq!(
rank_recompute(&state),
(state.core.heaps_bytes, 0, state.core.index_bytes)
);
Ok(())
}
fn build_partitioned_topk_rank_for(
schema: &Arc<Schema>,
k: usize,
batch_size: usize,
) -> Result<PartitionedTopKRank> {
let pk_expr: Arc<dyn PhysicalExpr> = col("pk", schema.as_ref())?;
let partition_sort_fields = build_sort_fields(
&[PhysicalSortExpr {
expr: Arc::clone(&pk_expr),
options: SortOptions::default(),
}],
schema,
)?;
let order_expr = LexOrdering::from([PhysicalSortExpr {
expr: col("val", schema.as_ref())?,
options: SortOptions::default(),
}]);
PartitionedTopKRank::try_new(
0,
schema,
vec![pk_expr],
partition_sort_fields,
order_expr,
k,
batch_size,
&Arc::new(RuntimeEnv::default()),
&ExecutionPlanMetricsSet::new(),
None,
)
}
#[tokio::test]
async fn test_partitioned_topk_rank_sorted_input_evicts_every_row() -> Result<()> {
let schema = Arc::new(Schema::new(vec![
Field::new("pk", DataType::Int32, false),
Field::new("val", DataType::Utf8, false),
]));
let mut state = build_partitioned_topk_rank_for(&schema, 2, 8)?;
let vals = [
"zzzzzzzzz",
"zzzzzzzzz",
"y",
"xxxxxx",
"w",
"cccccc",
"c",
"bbbbbbbbb",
"a",
];
for (i, chunk) in vals.chunks(3).enumerate() {
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(Int32Array::from(vec![1; chunk.len()])),
Arc::new(StringArray::from(chunk.to_vec())),
],
)?;
state.insert_batch(&batch)?;
if i == 0 {
let partition = state
.core
.partitions
.values()
.next()
.expect("one partition");
assert_eq!(partition.ties.len(), 1, "\"y\" must leave a tie");
}
let (heaps, ties, index) = rank_recompute(&state);
assert_eq!(state.core.heaps_bytes, heaps, "heaps_bytes");
assert_eq!(state.ties_bytes, ties, "ties_bytes");
assert_eq!(state.core.index_bytes, index, "index_bytes");
}
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+----+-----------+",
"| pk | val |",
"+----+-----------+",
"| 1 | a |",
"| 1 | bbbbbbbbb |",
"+----+-----------+",
],
&results
);
Ok(())
}
#[test]
fn test_interleave_referenced_matches_interleave_over_all() -> Result<()> {
let schema = Arc::new(Schema::new(vec![Field::new(
"d",
DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
false,
)]));
let batches: Vec<RecordBatch> = (0..4)
.map(|b| {
let mut builder = StringDictionaryBuilder::<Int32Type>::new();
for row in 0..3 {
builder.append_value(format!("b{b}r{row}"));
}
RecordBatch::try_new(
Arc::clone(&schema),
vec![Arc::new(builder.finish())],
)
})
.collect::<std::result::Result<_, _>>()?;
let all: Vec<&RecordBatch> = batches.iter().collect();
let as_strings = |batch: &RecordBatch| -> Result<Vec<String>> {
let col = arrow::compute::cast(batch.column(0), &DataType::Utf8)?;
Ok(col
.as_string::<i32>()
.iter()
.map(|v| v.unwrap().to_string())
.collect())
};
let mut remap = vec![usize::MAX; batches.len()];
let chunks: [&[(usize, usize)]; 3] = [
&[(2, 0), (2, 2)],
&[(3, 1), (2, 1), (3, 0)],
&[(1, 2), (0, 0), (3, 2), (2, 0), (1, 1)],
];
for chunk in chunks {
let got = interleave_referenced(&batches, chunk, &mut remap)?;
let want = interleave_record_batch(&all, chunk)?;
assert_eq!(as_strings(&got)?, as_strings(&want)?, "chunk {chunk:?}");
assert!(remap.iter().all(|&r| r == usize::MAX), "remap left dirty");
}
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_rank_emit_dictionary_chunks_use_few_batches()
-> Result<()> {
let schema = Arc::new(Schema::new(vec![
Field::new("pk", DataType::Int32, false),
Field::new("val", DataType::Int32, false),
Field::new(
"d",
DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
false,
),
]));
let mut state = build_partitioned_topk_rank_for(&schema, 2, 8)?;
for b in 0..4 {
let mut pks = Vec::new();
let mut builder = StringDictionaryBuilder::<Int32Type>::new();
for pk in [2 * b, 2 * b + 1] {
for row in 0..6 {
pks.push(pk);
builder.append_value(format!("p{pk}r{row}"));
}
}
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(Int32Array::from(pks)),
Arc::new(Int32Array::from(vec![0; 12])),
Arc::new(builder.finish()),
],
)?;
state.insert_batch(&batch)?;
}
assert_eq!(
state.core.store.len(),
4,
"every input batch stays in the store"
);
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_eq!(
results
.iter()
.map(RecordBatch::num_rows)
.collect::<Vec<_>>(),
vec![8; 6]
);
let mut emitted: Vec<(i32, String)> = Vec::new();
for batch in &results {
let pks = batch.column(0).as_primitive::<Int32Type>();
let d = arrow::compute::cast(batch.column(2), &DataType::Utf8)?;
let d = d.as_string::<i32>();
for i in 0..batch.num_rows() {
emitted.push((pks.value(i), d.value(i).to_string()));
}
}
let pks_in_order: Vec<i32> = emitted.iter().map(|(pk, _)| *pk).collect();
assert!(pks_in_order.is_sorted(), "partitions emit in key order");
emitted.sort();
let expected: Vec<(i32, String)> = (0..8)
.flat_map(|pk| (0..6).map(move |row| (pk, format!("p{pk}r{row}"))))
.collect();
assert_eq!(emitted, expected);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_rank_eviction_at_unchanged_boundary() -> Result<()> {
let (schema, mut state) = build_partitioned_topk_rank(2)?;
let batch = pk_val_batch(&schema, vec![1, 1, 1], vec![10, 10, 5])?;
state.insert_batch(&batch)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+----+-----+",
"| pk | val |",
"+----+-----+",
"| 1 | 5 |",
"| 1 | 10 |",
"| 1 | 10 |",
"+----+-----+",
],
&results
);
Ok(())
}
fn rank_recompute(state: &PartitionedTopKRank) -> (usize, usize, usize) {
let (mut heaps, mut ties, mut index) = (state.evicted_key.capacity(), 0, 0);
for (pk, partition) in &state.core.partitions {
index += pk.len();
heaps += partition.heap.inner.capacity() * size_of::<PartitionSlot>()
+ partition
.heap
.slots()
.map(|slot| slot.key.capacity())
.sum::<usize>();
ties += partition.ties.capacity() * size_of::<StoreRef>();
}
(heaps, ties, index)
}
fn rank_slots(state: &PartitionedTopKRank) -> Vec<StoreRef> {
state
.core
.partitions
.values()
.flat_map(RankPartitionState::store_rows)
.collect()
}
#[tokio::test]
async fn test_partitioned_topk_rank_bookkeeping_tracks_recompute() -> Result<()> {
let (mut saw_ties, mut saw_compaction) = (false, false);
for seed in 0..256u64 {
let shape = DiffShape::new(seed, 6);
let (schema, mut state) = build_partitioned_topk_rank(shape.k)?;
for (pks, vals) in &shape.batches {
let next_id = state.core.store.next_batch_id();
state.insert_batch(&pk_val_batch(&schema, pks.clone(), vals.clone())?)?;
saw_compaction |= state.core.store.next_batch_id() > next_id + 1;
saw_ties |= state.core.partitions.values().any(|p| !p.ties.is_empty());
assert_store_matches_slots(
&state.core.store,
state.core.live_slots,
&rank_slots(&state),
&shape.to_string(),
);
let (heaps, ties, index) = rank_recompute(&state);
assert_eq!(state.core.heaps_bytes, heaps, "heaps_bytes: {shape}");
assert_eq!(state.ties_bytes, ties, "ties_bytes: {shape}");
assert_eq!(state.core.index_bytes, index, "index_bytes: {shape}");
assert_eq!(
state.core.reservation.size(),
state.size(),
"reservation vs size(): {shape}"
);
}
let expected = shape.expected(|rows, pk, val| {
1 + rows.iter().filter(|&&(p, v)| p == pk && v < val).count()
});
assert_eq!(sorted_pk_val(state.emit()?).await?, expected, "{shape}");
}
assert!(saw_ties, "no shape retained a tie");
assert!(saw_compaction, "no shape compacted the store");
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_rank_store_bounded_when_ties_spread_thinly()
-> Result<()> {
const B: i32 = 64;
let (schema, mut state) = build_partitioned_topk_rank(1)?;
for j in 0..B {
let pks: Vec<i32> = (0..B).flat_map(|p| [p, p]).collect();
let vals: Vec<i32> = (0..B)
.flat_map(|p| {
let v = (j - p).abs();
[v, v]
})
.collect();
state.insert_batch(&pk_val_batch(&schema, pks, vals)?)?;
assert!(
state.core.store.total_rows
<= STORE_COMPACTION_RATIO * state.core.live_slots,
"batch {j}: store holds {} rows for {} retained",
state.core.store.total_rows,
state.core.live_slots
);
}
let expected: Vec<(i32, i32)> = (0..B).flat_map(|p| [(p, 0), (p, 0)]).collect();
assert_eq!(pk_val_rows(state.emit()?).await?, expected);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_rank_boundary_move_releases_ties_across_batches()
-> Result<()> {
let (schema, mut state) = build_partitioned_topk_rank(2)?;
state.insert_batch(&pk_val_batch(&schema, vec![1; 4], vec![10; 4])?)?;
assert_eq!((state.core.store.len(), state.core.live_slots), (1, 4));
state.insert_batch(&pk_val_batch(&schema, vec![1; 3], vec![10, 3, 1])?)?;
assert_eq!((state.core.store.len(), state.core.live_slots), (1, 2));
let entry = state.core.store.batches.values().next().expect("one entry");
assert_eq!((entry.batch.num_rows(), entry.uses), (3, 2));
assert_eq!(pk_val_rows(state.emit()?).await?, vec![(1, 1), (1, 3)]);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_rank_ties_share_one_store_entry() -> Result<()> {
const P: i32 = 4096;
let (schema, mut state) = build_partitioned_topk_rank(1)?;
let batch =
pk_val_batch(&schema, (0..4 * P).map(|i| i % P).collect(), vec![0; 16384])?;
state.insert_batch(&batch)?;
assert_eq!(state.core.live_slots, 4 * P as usize);
assert_eq!(state.core.store.len(), 1);
assert!(
state.core.store.batches_size <= 2 * get_record_batch_memory_size(&batch),
"store charges {} bytes for one {}-byte batch",
state.core.store.batches_size,
get_record_batch_memory_size(&batch)
);
Ok(())
}
fn build_partitioned_topk_dense_rank(
k: usize,
) -> Result<(Arc<Schema>, PartitionedTopKDenseRank)> {
build_partitioned_topk_dense_rank_with_opts(k, SortOptions::default(), false)
}
fn build_partitioned_topk_dense_rank_with_opts(
k: usize,
val_sort_options: SortOptions,
val_nullable: bool,
) -> Result<(Arc<Schema>, PartitionedTopKDenseRank)> {
build_pk_val_state(
PartitionedTopKDenseRank::try_new,
k,
val_sort_options,
val_nullable,
&Arc::new(RuntimeEnv::default()),
None,
)
}
#[tokio::test]
async fn test_partitioned_topk_dense_rank_multi_partition_within_batch() -> Result<()>
{
let (schema, mut state) = build_partitioned_topk_dense_rank(2)?;
let batch =
pk_val_batch(&schema, vec![1, 2, 1, 2, 1, 3], vec![10, 20, 5, 15, 8, 7])?;
state.insert_batch(&batch)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+----+-----+",
"| pk | val |",
"+----+-----+",
"| 1 | 5 |",
"| 1 | 8 |",
"| 2 | 15 |",
"| 2 | 20 |",
"| 3 | 7 |",
"+----+-----+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_dense_rank_emits_rank_column() -> Result<()> {
let dr_field = Arc::new(Field::new("dr", DataType::UInt64, false));
let (schema, mut state) =
build_emitting(PartitionedTopKDenseRank::try_new, 2, Arc::clone(&dr_field))?;
state.insert_batch(&pk_val_batch(
&schema,
vec![1, 1, 1, 1, 2, 2],
vec![10, 10, 20, 30, 7, 7],
)?)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_eq!(results[0].schema().field(2), dr_field.as_ref());
assert_batches_eq!(
&[
"+----+-----+----+",
"| pk | val | dr |",
"+----+-----+----+",
"| 1 | 10 | 1 |",
"| 1 | 10 | 1 |",
"| 1 | 20 | 2 |",
"| 2 | 7 | 1 |",
"| 2 | 7 | 1 |",
"+----+-----+----+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_dense_rank_emits_rank_across_batches() -> Result<()> {
let dr_field = Arc::new(Field::new("dr", DataType::UInt64, false));
let (schema, mut state) =
build_emitting(PartitionedTopKDenseRank::try_new, 2, Arc::clone(&dr_field))?;
state.insert_batch(&pk_val_batch(&schema, vec![1, 1], vec![20, 10])?)?;
state.insert_batch(&pk_val_batch(&schema, vec![1, 1], vec![10, 20])?)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+----+-----+----+",
"| pk | val | dr |",
"+----+-----+----+",
"| 1 | 10 | 1 |",
"| 1 | 10 | 1 |",
"| 1 | 20 | 2 |",
"| 1 | 20 | 2 |",
"+----+-----+----+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_dense_rank_heavy_ties_coalesced() -> Result<()> {
let (schema, mut state) = build_partitioned_topk_dense_rank(2)?;
let batch = pk_val_batch(
&schema,
vec![1, 1, 1, 1, 1, 1, 1, 1, 1],
vec![1, 3, 1, 2, 3, 1, 2, 3, 4],
)?;
state.insert_batch(&batch)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+----+-----+",
"| pk | val |",
"+----+-----+",
"| 1 | 1 |",
"| 1 | 1 |",
"| 1 | 1 |",
"| 1 | 2 |",
"| 1 | 2 |",
"+----+-----+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_dense_rank_cross_batch_same_key() -> Result<()> {
let (schema, mut state) = build_partitioned_topk_dense_rank(2)?;
state.insert_batch(&pk_val_batch(&schema, vec![1, 1, 1], vec![5, 5, 8])?)?;
state.insert_batch(&pk_val_batch(&schema, vec![1, 1, 1], vec![5, 8, 20])?)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+----+-----+",
"| pk | val |",
"+----+-----+",
"| 1 | 5 |",
"| 1 | 5 |",
"| 1 | 5 |",
"| 1 | 8 |",
"| 1 | 8 |",
"+----+-----+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_dense_rank_multi_batch_multi_partition() -> Result<()>
{
let (schema, mut state) = build_partitioned_topk_dense_rank(2)?;
state.insert_batch(&pk_val_batch(
&schema,
vec![1, 2, 1, 1, 2, 1, 1],
vec![10, 100, 20, 20, 100, 10, 10],
)?)?;
state.insert_batch(&pk_val_batch(
&schema,
vec![1, 2, 1, 1],
vec![20, 50, 5, 10],
)?)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+----+-----+",
"| pk | val |",
"+----+-----+",
"| 1 | 5 |",
"| 1 | 10 |",
"| 1 | 10 |",
"| 1 | 10 |",
"| 1 | 10 |",
"| 2 | 50 |",
"| 2 | 100 |",
"| 2 | 100 |",
"+----+-----+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_dense_rank_emit_dictionary_spans_chunks() -> Result<()>
{
let schema = Arc::new(Schema::new(vec![
Field::new("pk", DataType::Int32, false),
Field::new(
"val",
DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
false,
),
]));
let pk_expr: Arc<dyn PhysicalExpr> = col("pk", schema.as_ref())?;
let partition_sort_fields = build_sort_fields(
&[PhysicalSortExpr {
expr: Arc::clone(&pk_expr),
options: SortOptions::default(),
}],
&schema,
)?;
let order_expr = LexOrdering::from([PhysicalSortExpr {
expr: col("val", schema.as_ref())?,
options: SortOptions::default(),
}]);
let mut state = PartitionedTopKDenseRank::try_new(
0,
&schema,
vec![pk_expr],
partition_sort_fields,
order_expr,
20, 8, &Arc::new(RuntimeEnv::default()),
&ExecutionPlanMetricsSet::new(),
None,
)?;
let dict_batch = |vals: &[&str]| -> Result<RecordBatch> {
let mut builder = StringDictionaryBuilder::<Int32Type>::new();
for v in vals {
builder.append_value(v);
}
Ok(RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(Int32Array::from(vec![1; vals.len()])),
Arc::new(builder.finish()),
],
)?)
};
state.insert_batch(&dict_batch(&[
"v00", "v01", "v02", "v03", "v04", "v05", "v06", "v06", "v06", "v06",
])?)?;
state.insert_batch(&dict_batch(&[
"v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19",
])?)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_eq!(
results.iter().map(|b| b.num_rows()).collect::<Vec<_>>(),
vec![8, 8, 4]
);
let mut emitted = Vec::new();
for b in &results {
let val_col = b.column(1).as_dictionary::<Int32Type>();
let dict_values = val_col.values().as_string::<i32>();
for key in val_col.keys().values() {
emitted.push(dict_values.value(*key as usize).to_string());
}
}
let expected: Vec<String> = [
"v00", "v01", "v02", "v03", "v04", "v05", "v06", "v06", "v06", "v06", "v10",
"v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19",
]
.iter()
.map(|s| s.to_string())
.collect();
assert_eq!(emitted, expected, "rows must emit in ob-sorted order");
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_dense_rank_max_group_eviction() -> Result<()> {
let (schema, mut state) = build_partitioned_topk_dense_rank(2)?;
state.insert_batch(&pk_val_batch(
&schema,
vec![1, 1, 1, 1],
vec![10, 10, 20, 20],
)?)?;
state.insert_batch(&pk_val_batch(&schema, vec![1, 1], vec![5, 30])?)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+----+-----+",
"| pk | val |",
"+----+-----+",
"| 1 | 5 |",
"| 1 | 10 |",
"| 1 | 10 |",
"+----+-----+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_dense_rank_empty_input() -> Result<()> {
let (_schema, state) = build_partitioned_topk_dense_rank(3)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert!(results.is_empty(), "empty input → empty output");
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_dense_rank_fetch_one() -> Result<()> {
let (schema, mut state) = build_partitioned_topk_dense_rank(1)?;
let batch = pk_val_batch(
&schema,
vec![1, 1, 1, 2, 1, 2, 1],
vec![5, 3, 5, 9, 3, 4, 7],
)?;
state.insert_batch(&batch)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+----+-----+",
"| pk | val |",
"+----+-----+",
"| 1 | 3 |",
"| 1 | 3 |",
"| 2 | 4 |",
"+----+-----+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_dense_rank_k_exceeds_distinct() -> Result<()> {
let (schema, mut state) = build_partitioned_topk_dense_rank(10)?;
let batch = pk_val_batch(&schema, vec![1, 1, 1, 1], vec![5, 3, 3, 7])?;
state.insert_batch(&batch)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+----+-----+",
"| pk | val |",
"+----+-----+",
"| 1 | 3 |",
"| 1 | 3 |",
"| 1 | 5 |",
"| 1 | 7 |",
"+----+-----+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_dense_rank_desc_ordering() -> Result<()> {
let (schema, mut state) = build_partitioned_topk_dense_rank_with_opts(
2,
SortOptions {
descending: true,
nulls_first: false,
},
false,
)?;
let batch = pk_val_batch(&schema, vec![1, 1, 1, 1, 1], vec![10, 5, 8, 12, 10])?;
state.insert_batch(&batch)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+----+-----+",
"| pk | val |",
"+----+-----+",
"| 1 | 12 |",
"| 1 | 10 |",
"| 1 | 10 |",
"+----+-----+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_dense_rank_partition_independence() -> Result<()> {
let (schema, mut state) = build_partitioned_topk_dense_rank(2)?;
state.insert_batch(&pk_val_batch(
&schema,
vec![1, 1, 2, 2],
vec![10, 20, 30, 40],
)?)?;
state.insert_batch(&pk_val_batch(&schema, vec![1, 2], vec![5, 25])?)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+----+-----+",
"| pk | val |",
"+----+-----+",
"| 1 | 5 |",
"| 1 | 10 |",
"| 2 | 25 |",
"| 2 | 30 |",
"+----+-----+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_dense_rank_nulls_last_ordering() -> Result<()> {
let (schema, mut state) = build_partitioned_topk_dense_rank_with_opts(
2,
SortOptions {
descending: false,
nulls_first: false,
},
true,
)?;
let batch = nullable_pk_val_batch(
&schema,
vec![1, 1, 1, 1, 2, 3, 3],
vec![None, Some(10), Some(20), None, None, Some(3), Some(3)],
)?;
state.insert_batch(&batch)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+----+-----+",
"| pk | val |",
"+----+-----+",
"| 1 | 10 |",
"| 1 | 20 |",
"| 2 | |",
"| 3 | 3 |",
"| 3 | 3 |",
"+----+-----+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_dense_rank_nulls_first_ordering() -> Result<()> {
let (schema, mut state) = build_partitioned_topk_dense_rank_with_opts(
2,
SortOptions {
descending: false,
nulls_first: true,
},
true,
)?;
let batch = nullable_pk_val_batch(
&schema,
vec![1, 2, 1, 3, 1, 2, 1, 3],
vec![
None,
Some(7),
Some(5),
Some(3),
None,
None,
Some(8),
Some(1),
],
)?;
state.insert_batch(&batch)?;
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+----+-----+",
"| pk | val |",
"+----+-----+",
"| 1 | |",
"| 1 | |",
"| 1 | 5 |",
"| 2 | |",
"| 2 | 7 |",
"| 3 | 1 |",
"| 3 | 3 |",
"+----+-----+",
],
&results
);
Ok(())
}
fn dense_rank_entry_count(state: &PartitionedTopKDenseRank) -> usize {
state
.states
.values()
.flat_map(|s| s.groups.values())
.map(|entries| entries.len())
.sum()
}
#[tokio::test]
async fn test_partitioned_topk_dense_rank_charges_batch_once() -> Result<()> {
let (schema, mut state) = build_partitioned_topk_dense_rank(3)?;
let batch = pk_val_batch(
&schema,
vec![1, 1, 1, 1, 2, 2, 2, 2],
vec![1, 2, 3, 4, 10, 20, 30, 40],
)?;
let batch_bytes = get_record_batch_memory_size(&batch);
state.insert_batch(&batch)?;
assert_eq!(dense_rank_entry_count(&state), 6);
assert_eq!(state.store.len(), 1);
assert_eq!(state.store.batches_size, batch_bytes);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_dense_rank_releases_evicted_batch() -> Result<()> {
let (schema, mut state) = build_partitioned_topk_dense_rank(2)?;
let first = pk_val_batch(&schema, vec![1, 1], vec![50, 60])?;
state.insert_batch(&first)?;
assert_eq!(state.store.len(), 1);
let second = pk_val_batch(&schema, vec![1, 1], vec![5, 6])?;
let second_bytes = get_record_batch_memory_size(&second);
state.insert_batch(&second)?;
assert_eq!(state.store.len(), 1);
assert_eq!(state.store.batches_size, second_bytes);
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+----+-----+",
"| pk | val |",
"+----+-----+",
"| 1 | 5 |",
"| 1 | 6 |",
"+----+-----+",
],
&results
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_dense_rank_ignores_fully_rejected_batch() -> Result<()>
{
let (schema, mut state) = build_partitioned_topk_dense_rank(2)?;
let first = pk_val_batch(&schema, vec![1, 1], vec![5, 6])?;
let first_bytes = get_record_batch_memory_size(&first);
state.insert_batch(&first)?;
assert_eq!(state.store.len(), 1);
state.insert_batch(&pk_val_batch(&schema, vec![1, 1], vec![50, 60])?)?;
assert_eq!(dense_rank_entry_count(&state), 2);
assert_eq!(state.store.len(), 1);
assert_eq!(state.store.batches_size, first_bytes);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_dense_rank_heap_grows_on_demand() -> Result<()> {
const K: usize = 512;
const PARTITIONS: usize = 64;
let (schema, mut state) = build_partitioned_topk_dense_rank(K)?;
let pks: Vec<i32> = (0..PARTITIONS as i32).collect();
let vals = pks.clone();
state.insert_batch(&pk_val_batch(&schema, pks, vals)?)?;
assert_eq!(state.states.len(), PARTITIONS);
let heap_slots: usize = state.states.values().map(|s| s.keys.capacity()).sum();
assert!(
heap_slots <= PARTITIONS * 8,
"reserved {heap_slots} heap slots to hold {PARTITIONS} keys"
);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_dense_rank_size_covers_keys_and_scratch() -> Result<()>
{
const PARTITIONS: usize = 64;
const KEY_WIDTH: usize = 1024;
let schema = Arc::new(Schema::new(vec![
Field::new("pk", DataType::Utf8, false),
Field::new("val", DataType::Int32, false),
]));
let pk_expr: Arc<dyn PhysicalExpr> = col("pk", schema.as_ref())?;
let partition_sort_fields = build_sort_fields(
&[PhysicalSortExpr {
expr: Arc::clone(&pk_expr),
options: SortOptions::default(),
}],
&schema,
)?;
let order_expr = LexOrdering::from([PhysicalSortExpr {
expr: col("val", schema.as_ref())?,
options: SortOptions::default(),
}]);
let mut state = PartitionedTopKDenseRank::try_new(
0,
&schema,
vec![pk_expr],
partition_sort_fields,
order_expr,
4,
8, &Arc::new(RuntimeEnv::default()),
&ExecutionPlanMetricsSet::new(),
None,
)?;
let pks: Vec<String> = (0..PARTITIONS)
.map(|i| format!("{}{i:04}", "p".repeat(KEY_WIDTH - 4)))
.collect();
let vals: Vec<i32> = (0..PARTITIONS as i32).collect();
state.insert_batch(&RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(StringArray::from(pks)),
Arc::new(Int32Array::from(vals)),
],
)?)?;
assert_eq!(state.states.len(), PARTITIONS);
let key_bytes: usize = state.states.keys().map(|pk| pk.capacity()).sum();
let scratch_bytes = state.partition_groups.capacity()
* (size_of::<Vec<u8>>() + size_of::<Vec<u32>>())
+ state.ob_runs.capacity() * (size_of::<Vec<u8>>() + size_of::<Vec<u32>>());
assert!(key_bytes >= PARTITIONS * KEY_WIDTH, "key bytes {key_bytes}");
assert!(scratch_bytes > 0, "scratch tables never allocated");
let expected = size_of::<PartitionedTopKDenseRank>()
+ state.row_converter.size()
+ state.partition_converter.size()
+ state.scratch_rows.size()
+ state.partition_scratch_rows.size()
+ key_bytes
+ state.states.values().map(|s| s.size()).sum::<usize>()
+ state.states.capacity()
* (size_of::<Vec<u8>>() + size_of::<DenseRankPartitionState>())
+ scratch_bytes
+ state.store.size();
assert_eq!(state.size(), expected);
Ok(())
}
#[tokio::test]
async fn test_partitioned_topk_dense_rank_evicts_same_call_group() -> Result<()> {
let (schema, mut state) = build_partitioned_topk_dense_rank(1)?;
let pks = vec![1; 32];
let vals: Vec<i32> = (0..32).rev().collect();
let batch = pk_val_batch(&schema, pks, vals)?;
let batch_bytes = get_record_batch_memory_size(&batch);
state.insert_batch(&batch)?;
assert_eq!(dense_rank_entry_count(&state), 1);
assert_eq!(state.store.len(), 1);
assert_eq!(state.store.batches_size, batch_bytes);
let results: Vec<_> = state.emit()?.try_collect().await?;
assert_batches_eq!(
&[
"+----+-----+",
"| pk | val |",
"+----+-----+",
"| 1 | 0 |",
"+----+-----+",
],
&results
);
Ok(())
}
}