use std::future::poll_fn;
use std::sync::Arc;
use super::utils::{
BuildProbeJoinMetrics, OnceAsync, OnceFut, adjust_right_output_partitioning,
reorder_output_after_swap,
};
use crate::execution_plan::{EmissionType, boundedness_from_children};
use crate::metrics::{ExecutionPlanMetricsSet, MetricsSet};
use crate::projection::{
ProjectionExec, join_allows_pushdown, join_table_borders, new_join_children,
physical_to_column_exprs,
};
use crate::statistics::{ChildStats, StatisticsArgs};
use crate::stream::{EmptyRecordBatchStream, ObservedStream, RecordBatchStreamAdapter};
use crate::{
ChildrenPropertiesMode, ColumnStatistics, DisplayAs, DisplayFormatType, Distribution,
ExecutionPlan, ExecutionPlanProperties, PlanProperties, ReplaceChildrenOptions,
SendableRecordBatchStream, Statistics, validate_child_count,
};
use arrow::array::{RecordBatch, RecordBatchOptions};
use arrow::compute::concat_batches;
use arrow::datatypes::{Fields, Schema, SchemaRef};
use datafusion_common::stats::Precision;
use datafusion_common::tree_node::TreeNodeRecursion;
use datafusion_common::{
DataFusionError, JoinType, Result, ScalarValue, assert_eq_or_internal_err,
};
use datafusion_execution::memory_pool::{MemoryConsumer, MemoryReservation};
use datafusion_execution::{TaskContext, TryEmitter, async_try_stream};
use datafusion_physical_expr::PhysicalExpr;
use datafusion_physical_expr::equivalence::join_equivalence_properties;
use futures::{StreamExt, TryStreamExt};
use num_traits::Zero;
#[derive(Debug)]
struct JoinLeftData {
merged_batch: RecordBatch,
_reservation: MemoryReservation,
}
#[expect(rustdoc::private_intra_doc_links)]
#[derive(Debug)]
pub struct CrossJoinExec {
pub left: Arc<dyn ExecutionPlan>,
pub right: Arc<dyn ExecutionPlan>,
schema: SchemaRef,
left_fut: OnceAsync<JoinLeftData>,
metrics: ExecutionPlanMetricsSet,
cache: Arc<PlanProperties>,
}
impl CrossJoinExec {
pub fn new(left: Arc<dyn ExecutionPlan>, right: Arc<dyn ExecutionPlan>) -> Self {
let (all_columns, metadata) = {
let left_schema = left.schema();
let right_schema = right.schema();
let left_fields = left_schema.fields().iter();
let right_fields = right_schema.fields().iter();
let mut metadata = left_schema.metadata().clone();
metadata.extend(right_schema.metadata().clone());
(
left_fields.chain(right_fields).cloned().collect::<Fields>(),
metadata,
)
};
let schema = Arc::new(Schema::new(all_columns).with_metadata(metadata));
let cache = Self::compute_properties(&left, &right, Arc::clone(&schema)).unwrap();
CrossJoinExec {
left,
right,
schema,
left_fut: Default::default(),
metrics: ExecutionPlanMetricsSet::default(),
cache: Arc::new(cache),
}
}
pub fn left(&self) -> &Arc<dyn ExecutionPlan> {
&self.left
}
pub fn right(&self) -> &Arc<dyn ExecutionPlan> {
&self.right
}
fn compute_properties(
left: &Arc<dyn ExecutionPlan>,
right: &Arc<dyn ExecutionPlan>,
schema: SchemaRef,
) -> Result<PlanProperties> {
let eq_properties = join_equivalence_properties(
left.equivalence_properties().clone(),
right.equivalence_properties().clone(),
&JoinType::Inner,
schema,
&[false, false],
None,
&[],
)?;
let output_partitioning = adjust_right_output_partitioning(
right.output_partitioning(),
left.schema().fields.len(),
)?;
Ok(PlanProperties::new(
eq_properties,
output_partitioning,
EmissionType::Final,
boundedness_from_children([left, right]),
))
}
#[doc(hidden)]
pub fn swap_inputs(&self) -> Result<Arc<dyn ExecutionPlan>> {
let new_join =
CrossJoinExec::new(Arc::clone(&self.right), Arc::clone(&self.left));
reorder_output_after_swap(
Arc::new(new_join),
&self.left.schema(),
&self.right.schema(),
)
}
}
async fn load_left_input(
stream: SendableRecordBatchStream,
metrics: BuildProbeJoinMetrics,
reservation: MemoryReservation,
) -> Result<JoinLeftData> {
let left_schema = stream.schema();
let (batches, metrics, reservation) = stream
.try_fold(
(Vec::new(), metrics, reservation),
|(mut batches, metrics, reservation), batch| async {
let batch_size = batch.get_array_memory_size();
reservation.try_grow(batch_size)?;
metrics.build_mem_used.add(batch_size);
metrics.build_input_batches.add(1);
metrics.build_input_rows.add(batch.num_rows());
batches.push(batch);
Ok((batches, metrics, reservation))
},
)
.await?;
let build_timer = metrics.build_time.timer();
let merged_batch = concat_batches(&left_schema, &batches)?;
build_timer.done();
Ok(JoinLeftData {
merged_batch,
_reservation: reservation,
})
}
impl DisplayAs for CrossJoinExec {
fn fmt_as(
&self,
t: DisplayFormatType,
f: &mut std::fmt::Formatter,
) -> std::fmt::Result {
match t {
DisplayFormatType::Default | DisplayFormatType::Verbose => {
write!(f, "CrossJoinExec")
}
DisplayFormatType::TreeRender => {
Ok(())
}
}
}
}
impl ExecutionPlan for CrossJoinExec {
fn name(&self) -> &'static str {
"CrossJoinExec"
}
fn properties(&self) -> &Arc<PlanProperties> {
&self.cache
}
fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
vec![&self.left, &self.right]
}
fn metrics(&self) -> Option<MetricsSet> {
Some(self.metrics.clone_inner())
}
fn apply_expressions(
&self,
_f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
) -> Result<TreeNodeRecursion> {
Ok(TreeNodeRecursion::Continue)
}
fn replace_children(
self: Arc<Self>,
mut children: Vec<Arc<dyn ExecutionPlan>>,
options: ReplaceChildrenOptions,
) -> Result<Arc<dyn ExecutionPlan>> {
validate_child_count!(self, children);
match options.children_properties {
ChildrenPropertiesMode::Keep => {
let left = children.swap_remove(0);
let right = children.swap_remove(0);
Ok(Arc::new(Self {
left,
right,
metrics: ExecutionPlanMetricsSet::new(),
left_fut: Default::default(),
cache: Arc::clone(&self.cache),
schema: Arc::clone(&self.schema),
}))
}
ChildrenPropertiesMode::Recompute => Ok(Arc::new(CrossJoinExec::new(
Arc::clone(&children[0]),
Arc::clone(&children[1]),
))),
}
}
fn with_new_children(
self: Arc<Self>,
children: Vec<Arc<dyn ExecutionPlan>>,
) -> Result<Arc<dyn ExecutionPlan>> {
self.replace_children(
children,
ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
)
}
fn with_new_children_and_same_properties(
self: Arc<Self>,
children: Vec<Arc<dyn ExecutionPlan>>,
) -> Result<Arc<dyn ExecutionPlan>> {
self.replace_children(
children,
ReplaceChildrenOptions::new(ChildrenPropertiesMode::Keep),
)
}
fn reset_state(self: Arc<Self>) -> Result<Arc<dyn ExecutionPlan>> {
let new_exec = CrossJoinExec {
left: Arc::clone(&self.left),
right: Arc::clone(&self.right),
schema: Arc::clone(&self.schema),
left_fut: Default::default(), metrics: ExecutionPlanMetricsSet::default(),
cache: Arc::clone(&self.cache),
};
Ok(Arc::new(new_exec))
}
fn required_input_distribution(&self) -> Vec<Distribution> {
self.input_distribution_requirements().into_per_child()
}
fn input_distribution_requirements(&self) -> crate::InputDistributionRequirements {
crate::InputDistributionRequirements::new(vec![
Distribution::SinglePartition,
Distribution::UnspecifiedDistribution,
])
}
fn execute(
&self,
partition: usize,
context: Arc<TaskContext>,
) -> Result<SendableRecordBatchStream> {
assert_eq_or_internal_err!(
self.left.output_partitioning().partition_count(),
1,
"Invalid CrossJoinExec, the output partition count of the left child must be 1,\
consider using CoalescePartitionsExec or the EnforceDistribution rule"
);
let stream = self.right.execute(partition, Arc::clone(&context))?;
let join_metrics = BuildProbeJoinMetrics::new(partition, &self.metrics);
let reservation =
MemoryConsumer::new("CrossJoinExec").register(context.memory_pool());
let left_fut = self.left_fut.try_once(|| {
let left_stream = self.left.execute(0, context)?;
Ok(load_left_input(
left_stream,
join_metrics.clone(),
reservation,
))
})?;
let mut state = CrossJoinStream {
schema: Arc::clone(&self.schema),
left_fut,
right: stream,
join_metrics,
left_data: RecordBatch::new_empty(self.left().schema()),
};
let schema = Arc::clone(&self.schema);
let baseline_metrics = state.join_metrics.baseline.clone();
let stream =
async_try_stream(|mut emitter| async move { state.join(&mut emitter).await });
Ok(Box::pin(ObservedStream::new(
Box::pin(RecordBatchStreamAdapter::new(schema, stream)),
baseline_metrics,
None,
)))
}
fn child_stats_requests(&self, partition: Option<usize>) -> Vec<ChildStats> {
vec![ChildStats::At(None), ChildStats::At(partition)]
}
fn statistics_from_inputs(
&self,
input_stats: &[Arc<Statistics>],
_args: &StatisticsArgs,
) -> Result<Arc<Statistics>> {
let left_stats = input_stats[0].as_ref().clone();
let right_stats = input_stats[1].as_ref().clone();
Ok(Arc::new(stats_cartesian_product(left_stats, right_stats)))
}
fn try_swapping_with_projection(
&self,
projection: &ProjectionExec,
) -> Result<Option<Arc<dyn ExecutionPlan>>> {
let Some(projection_as_columns) = physical_to_column_exprs(projection.expr())
else {
return Ok(None);
};
let (far_right_left_col_ind, far_left_right_col_ind) = join_table_borders(
self.left().schema().fields().len(),
&projection_as_columns,
);
if !join_allows_pushdown(
&projection_as_columns,
&self.schema(),
far_right_left_col_ind,
far_left_right_col_ind,
) {
return Ok(None);
}
let (new_left, new_right) = new_join_children(
&projection_as_columns,
far_right_left_col_ind,
far_left_right_col_ind,
self.left(),
self.right(),
)?;
Ok(Some(Arc::new(CrossJoinExec::new(
Arc::new(new_left),
Arc::new(new_right),
))))
}
#[cfg(feature = "proto")]
fn try_to_proto(
&self,
ctx: &crate::proto::ExecutionPlanEncodeCtx<'_>,
) -> Result<Option<datafusion_proto_models::protobuf::PhysicalPlanNode>> {
use datafusion_proto_models::protobuf;
let Self {
left,
right,
schema: _,
left_fut: _,
metrics: _,
cache: _,
} = self;
let left = ctx.encode_child(left)?;
let right = ctx.encode_child(right)?;
Ok(Some(protobuf::PhysicalPlanNode {
physical_plan_type: Some(
protobuf::physical_plan_node::PhysicalPlanType::CrossJoin(Box::new(
protobuf::CrossJoinExecNode {
left: Some(Box::new(left)),
right: Some(Box::new(right)),
},
)),
),
}))
}
}
#[cfg(feature = "proto")]
impl CrossJoinExec {
pub fn try_from_proto(
node: &datafusion_proto_models::protobuf::PhysicalPlanNode,
ctx: &crate::proto::ExecutionPlanDecodeCtx<'_>,
) -> Result<Arc<dyn ExecutionPlan>> {
use datafusion_proto_models::protobuf;
let crossjoin = crate::expect_plan_variant!(
node,
protobuf::physical_plan_node::PhysicalPlanType::CrossJoin,
"CrossJoinExec",
);
let protobuf::CrossJoinExecNode { left, right } = &**crossjoin;
let left = ctx.decode_required_child(left.as_deref(), "CrossJoinExec", "left")?;
let right =
ctx.decode_required_child(right.as_deref(), "CrossJoinExec", "right")?;
Ok(Arc::new(CrossJoinExec::new(left, right)))
}
}
fn stats_cartesian_product(
left_stats: Statistics,
right_stats: Statistics,
) -> Statistics {
let left_row_count = left_stats.num_rows;
let right_row_count = right_stats.num_rows;
let num_rows = left_row_count.multiply(&right_row_count);
let left_byte_size = left_stats.total_byte_size.multiply(&right_row_count);
let right_byte_size = right_stats.total_byte_size.multiply(&left_row_count);
let total_byte_size = left_byte_size.add(&right_byte_size);
let left_col_stats = left_stats.column_statistics;
let right_col_stats = right_stats.column_statistics;
let cross_join_stats = left_col_stats
.into_iter()
.map(|s| {
let widened_sum = s.sum_value.cast_to_sum_type();
ColumnStatistics {
null_count: s.null_count.multiply(&right_row_count),
distinct_count: s.distinct_count,
min_value: s.min_value,
max_value: s.max_value,
sum_value: widened_sum
.get_value()
.and_then(|v| {
Precision::<ScalarValue>::from(right_row_count)
.cast_to(&v.data_type())
.ok()
})
.map(|row_count| widened_sum.multiply(&row_count))
.unwrap_or(Precision::Absent),
byte_size: Precision::Absent,
}
})
.chain(right_col_stats.into_iter().map(|s| {
let widened_sum = s.sum_value.cast_to_sum_type();
ColumnStatistics {
null_count: s.null_count.multiply(&left_row_count),
distinct_count: s.distinct_count,
min_value: s.min_value,
max_value: s.max_value,
sum_value: widened_sum
.get_value()
.and_then(|v| {
Precision::<ScalarValue>::from(left_row_count)
.cast_to(&v.data_type())
.ok()
})
.map(|row_count| widened_sum.multiply(&row_count))
.unwrap_or(Precision::Absent),
byte_size: Precision::Absent,
}
}))
.collect();
Statistics {
num_rows,
total_byte_size,
column_statistics: cross_join_stats,
}
}
struct CrossJoinStream {
schema: Arc<Schema>,
left_fut: OnceFut<JoinLeftData>,
right: SendableRecordBatchStream,
join_metrics: BuildProbeJoinMetrics,
left_data: RecordBatch,
}
fn build_batch(
left_index: usize,
batch: &RecordBatch,
left_data: &RecordBatch,
schema: &Schema,
) -> Result<RecordBatch> {
let mut arrays = Vec::with_capacity(left_data.num_columns() + batch.num_columns());
for arr in left_data.columns() {
let scalar = ScalarValue::try_from_array(arr, left_index)?;
arrays.push(scalar.to_array_of_size(batch.num_rows())?);
}
arrays.extend_from_slice(batch.columns());
RecordBatch::try_new_with_options(
Arc::new(schema.clone()),
arrays,
&RecordBatchOptions::new().with_row_count(Some(batch.num_rows())),
)
.map_err(Into::into)
}
impl CrossJoinStream {
async fn join(
&mut self,
emitter: &mut TryEmitter<RecordBatch, DataFusionError>,
) -> Result<()> {
if !self.collect_build_side().await? {
return Ok(());
}
self.process_right_batch(emitter).await?;
Ok(())
}
async fn collect_build_side(&mut self) -> Result<bool> {
let left_data = poll_fn(|cx| {
self.left_fut
.get(cx)
.map(|res| res.map(|data| data.merged_batch.clone()))
})
.await?;
let is_empty = left_data.num_rows().is_zero();
self.left_data = left_data;
Ok(!is_empty)
}
async fn fetch_probe_batch(&mut self) -> Result<Option<RecordBatch>> {
let right_data = match self.right.next().await {
Some(Ok(right_data)) => right_data,
Some(Err(e)) => return Err(e),
None => {
let right_schema = self.right.schema();
self.right = Box::pin(EmptyRecordBatchStream::new(right_schema));
return Ok(None);
}
};
self.join_metrics.input_batches.add(1);
self.join_metrics.input_rows.add(right_data.num_rows());
Ok(Some(right_data))
}
async fn process_right_batch(
&mut self,
emitter: &mut TryEmitter<RecordBatch, DataFusionError>,
) -> Result<()> {
while let Some(right_batch) = self.fetch_probe_batch().await? {
for left_index in 0..self.left_data.num_rows() {
let join_timer = self.join_metrics.join_time.timer();
let result =
build_batch(left_index, &right_batch, &self.left_data, &self.schema)?;
join_timer.done();
emitter.emit(result).await;
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::common;
use crate::test::{
TestMemoryExec, assert_join_metrics, build_table_i32, build_table_scan_i32,
};
use datafusion_common::{assert_contains, test_util::batches_to_sort_string};
use datafusion_execution::runtime_env::RuntimeEnvBuilder;
use insta::assert_snapshot;
async fn join_collect(
left: Arc<dyn ExecutionPlan>,
right: Arc<dyn ExecutionPlan>,
context: Arc<TaskContext>,
) -> Result<(Vec<String>, Vec<RecordBatch>, MetricsSet)> {
let join = CrossJoinExec::new(left, right);
let columns_header = columns(&join.schema());
let stream = join.execute(0, context)?;
let batches = common::collect(stream).await?;
let metrics = join.metrics().unwrap();
Ok((columns_header, batches, metrics))
}
fn build_table_scan_i32_chunked(
a: (&str, &Vec<i32>),
b: (&str, &Vec<i32>),
c: (&str, &Vec<i32>),
input_batch_size: usize,
) -> Arc<dyn ExecutionPlan> {
let full = build_table_i32(a, b, c);
let n = full.num_rows();
let batches = (0..n)
.step_by(input_batch_size)
.map(|i| full.slice(i, input_batch_size.min(n - i)))
.collect();
TestMemoryExec::try_new_exec(&[batches], full.schema(), None).unwrap()
}
fn metric_count(metrics: &MetricsSet, name: &str) -> usize {
metrics
.sum_by_name(name)
.expect("missing metric")
.as_usize()
}
#[tokio::test]
async fn test_stats_cartesian_product() {
let left_row_count = 11;
let left_bytes = 23;
let right_row_count = 7;
let right_bytes = 27;
let left = Statistics {
num_rows: Precision::Exact(left_row_count),
total_byte_size: Precision::Exact(left_bytes),
column_statistics: vec![
ColumnStatistics {
distinct_count: Precision::Exact(5),
max_value: Precision::Exact(ScalarValue::Int64(Some(21))),
min_value: Precision::Exact(ScalarValue::Int64(Some(-4))),
sum_value: Precision::Exact(ScalarValue::Int64(Some(42))),
null_count: Precision::Exact(0),
byte_size: Precision::Absent,
},
ColumnStatistics {
distinct_count: Precision::Exact(1),
max_value: Precision::Exact(ScalarValue::from("x")),
min_value: Precision::Exact(ScalarValue::from("a")),
sum_value: Precision::Absent,
null_count: Precision::Exact(3),
byte_size: Precision::Absent,
},
],
};
let right = Statistics {
num_rows: Precision::Exact(right_row_count),
total_byte_size: Precision::Exact(right_bytes),
column_statistics: vec![ColumnStatistics {
distinct_count: Precision::Exact(3),
max_value: Precision::Exact(ScalarValue::Int64(Some(12))),
min_value: Precision::Exact(ScalarValue::Int64(Some(0))),
sum_value: Precision::Exact(ScalarValue::Int64(Some(20))),
null_count: Precision::Exact(2),
byte_size: Precision::Absent,
}],
};
let result = stats_cartesian_product(left, right);
let expected = Statistics {
num_rows: Precision::Exact(left_row_count * right_row_count),
total_byte_size: Precision::Exact(
left_bytes * right_row_count + right_bytes * left_row_count,
),
column_statistics: vec![
ColumnStatistics {
distinct_count: Precision::Exact(5),
max_value: Precision::Exact(ScalarValue::Int64(Some(21))),
min_value: Precision::Exact(ScalarValue::Int64(Some(-4))),
sum_value: Precision::Exact(ScalarValue::Int64(Some(
42 * right_row_count as i64,
))),
null_count: Precision::Exact(0),
byte_size: Precision::Absent,
},
ColumnStatistics {
distinct_count: Precision::Exact(1),
max_value: Precision::Exact(ScalarValue::from("x")),
min_value: Precision::Exact(ScalarValue::from("a")),
sum_value: Precision::Absent,
null_count: Precision::Exact(3 * right_row_count),
byte_size: Precision::Absent,
},
ColumnStatistics {
distinct_count: Precision::Exact(3),
max_value: Precision::Exact(ScalarValue::Int64(Some(12))),
min_value: Precision::Exact(ScalarValue::Int64(Some(0))),
sum_value: Precision::Exact(ScalarValue::Int64(Some(
20 * left_row_count as i64,
))),
null_count: Precision::Exact(2 * left_row_count),
byte_size: Precision::Absent,
},
],
};
assert_eq!(result, expected);
}
#[tokio::test]
async fn test_stats_cartesian_product_with_unknown_size() {
let left_row_count = 11;
let left = Statistics {
num_rows: Precision::Exact(left_row_count),
total_byte_size: Precision::Exact(23),
column_statistics: vec![
ColumnStatistics {
distinct_count: Precision::Exact(5),
max_value: Precision::Exact(ScalarValue::Int64(Some(21))),
min_value: Precision::Exact(ScalarValue::Int64(Some(-4))),
sum_value: Precision::Exact(ScalarValue::Int64(Some(42))),
null_count: Precision::Exact(0),
byte_size: Precision::Absent,
},
ColumnStatistics {
distinct_count: Precision::Exact(1),
max_value: Precision::Exact(ScalarValue::from("x")),
min_value: Precision::Exact(ScalarValue::from("a")),
sum_value: Precision::Absent,
null_count: Precision::Exact(3),
byte_size: Precision::Absent,
},
],
};
let right = Statistics {
num_rows: Precision::Absent,
total_byte_size: Precision::Absent,
column_statistics: vec![ColumnStatistics {
distinct_count: Precision::Exact(3),
max_value: Precision::Exact(ScalarValue::Int64(Some(12))),
min_value: Precision::Exact(ScalarValue::Int64(Some(0))),
sum_value: Precision::Exact(ScalarValue::Int64(Some(20))),
null_count: Precision::Exact(2),
byte_size: Precision::Absent,
}],
};
let result = stats_cartesian_product(left, right);
let expected = Statistics {
num_rows: Precision::Absent,
total_byte_size: Precision::Absent,
column_statistics: vec![
ColumnStatistics {
distinct_count: Precision::Exact(5),
max_value: Precision::Exact(ScalarValue::Int64(Some(21))),
min_value: Precision::Exact(ScalarValue::Int64(Some(-4))),
sum_value: Precision::Absent, null_count: Precision::Absent, byte_size: Precision::Absent,
},
ColumnStatistics {
distinct_count: Precision::Exact(1),
max_value: Precision::Exact(ScalarValue::from("x")),
min_value: Precision::Exact(ScalarValue::from("a")),
sum_value: Precision::Absent,
null_count: Precision::Absent, byte_size: Precision::Absent,
},
ColumnStatistics {
distinct_count: Precision::Exact(3),
max_value: Precision::Exact(ScalarValue::Int64(Some(12))),
min_value: Precision::Exact(ScalarValue::Int64(Some(0))),
sum_value: Precision::Exact(ScalarValue::Int64(Some(
20 * left_row_count as i64,
))),
null_count: Precision::Exact(2 * left_row_count),
byte_size: Precision::Absent,
},
],
};
assert_eq!(result, expected);
}
#[tokio::test]
async fn test_stats_cartesian_product_unsigned_sum_widens_to_u64() {
let left_row_count = 2;
let right_row_count = 3;
let left = Statistics {
num_rows: Precision::Exact(left_row_count),
total_byte_size: Precision::Exact(10),
column_statistics: vec![ColumnStatistics {
distinct_count: Precision::Exact(2),
max_value: Precision::Exact(ScalarValue::UInt32(Some(10))),
min_value: Precision::Exact(ScalarValue::UInt32(Some(1))),
sum_value: Precision::Exact(ScalarValue::UInt32(Some(7))),
null_count: Precision::Exact(0),
byte_size: Precision::Absent,
}],
};
let right = Statistics {
num_rows: Precision::Exact(right_row_count),
total_byte_size: Precision::Exact(10),
column_statistics: vec![ColumnStatistics {
distinct_count: Precision::Exact(3),
max_value: Precision::Exact(ScalarValue::UInt32(Some(12))),
min_value: Precision::Exact(ScalarValue::UInt32(Some(0))),
sum_value: Precision::Exact(ScalarValue::UInt32(Some(11))),
null_count: Precision::Exact(0),
byte_size: Precision::Absent,
}],
};
let result = stats_cartesian_product(left, right);
assert_eq!(
result.column_statistics[0].sum_value,
Precision::Exact(ScalarValue::UInt64(Some(21)))
);
assert_eq!(
result.column_statistics[1].sum_value,
Precision::Exact(ScalarValue::UInt64(Some(22)))
);
}
#[tokio::test]
async fn test_join() -> Result<()> {
let task_ctx = Arc::new(TaskContext::default());
let left = build_table_scan_i32(
("a1", &vec![1, 2, 3]),
("b1", &vec![4, 5, 6]),
("c1", &vec![7, 8, 9]),
);
let right = build_table_scan_i32(
("a2", &vec![10, 11]),
("b2", &vec![12, 13]),
("c2", &vec![14, 15]),
);
let (columns, batches, metrics) = join_collect(left, right, task_ctx).await?;
assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b2", "c2"]);
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+----+----+----+----+
| a1 | b1 | c1 | a2 | b2 | c2 |
+----+----+----+----+----+----+
| 1 | 4 | 7 | 10 | 12 | 14 |
| 1 | 4 | 7 | 11 | 13 | 15 |
| 2 | 5 | 8 | 10 | 12 | 14 |
| 2 | 5 | 8 | 11 | 13 | 15 |
| 3 | 6 | 9 | 10 | 12 | 14 |
| 3 | 6 | 9 | 11 | 13 | 15 |
+----+----+----+----+----+----+
");
assert_join_metrics!(metrics, 6);
assert_eq!(metric_count(&metrics, "build_input_rows"), 3);
assert_eq!(metric_count(&metrics, "input_rows"), 2);
Ok(())
}
#[tokio::test]
async fn join_metrics_count_rows_once_across_batches() -> Result<()> {
let task_ctx = Arc::new(TaskContext::default());
for (input_batch_size, expected_build_batches, expected_probe_batches) in
[(2, 2, 1), (1, 3, 2)]
{
let left = build_table_scan_i32_chunked(
("a1", &vec![1, 2, 3]),
("b1", &vec![4, 5, 6]),
("c1", &vec![7, 8, 9]),
input_batch_size,
);
let right = build_table_scan_i32_chunked(
("a2", &vec![10, 11]),
("b2", &vec![12, 13]),
("c2", &vec![14, 15]),
input_batch_size,
);
let (_, batches, metrics) =
join_collect(left, right, Arc::clone(&task_ctx)).await?;
let num_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
assert_eq!(num_rows, 6);
assert_join_metrics!(metrics, 6);
assert_eq!(metric_count(&metrics, "build_input_rows"), 3);
assert_eq!(metric_count(&metrics, "input_rows"), 2);
assert_eq!(
metric_count(&metrics, "build_input_batches"),
expected_build_batches
);
assert_eq!(
metric_count(&metrics, "input_batches"),
expected_probe_batches
);
}
Ok(())
}
#[tokio::test]
async fn test_overallocation() -> Result<()> {
let runtime = RuntimeEnvBuilder::new()
.with_memory_limit(100, 1.0)
.build_arc()?;
let task_ctx = TaskContext::default().with_runtime(runtime);
let task_ctx = Arc::new(task_ctx);
let left = build_table_scan_i32(
("a1", &vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 0]),
("b1", &vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 0]),
("c1", &vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 0]),
);
let right = build_table_scan_i32(
("a2", &vec![10, 11]),
("b2", &vec![12, 13]),
("c2", &vec![14, 15]),
);
let err = join_collect(left, right, task_ctx).await.unwrap_err();
assert_contains!(
err.to_string(),
"Resources exhausted: Additional allocation failed for CrossJoinExec with top memory consumers (across reservations) as:\n CrossJoinExec"
);
Ok(())
}
fn columns(schema: &Schema) -> Vec<String> {
schema.fields().iter().map(|f| f.name().clone()).collect()
}
}