use std::fmt::{self, Debug};
use std::mem::{size_of, size_of_val};
use std::sync::Arc;
use std::task::{Context, Poll};
use std::vec;
use crate::common::SharedMemoryReservation;
use crate::execution_plan::{boundedness_from_children, emission_type_from_children};
use crate::joins::stream_join_utils::{
PruningJoinHashMap, SortedFilterExpr, StreamJoinMetrics,
calculate_filter_expr_intervals, combine_two_batches,
convert_sort_expr_with_filter_schema, get_pruning_anti_indices,
get_pruning_semi_indices, prepare_sorted_exprs, record_visited_indices,
};
use crate::joins::utils::{
BatchSplitter, BatchTransformer, ColumnIndex, JoinFilter, JoinHashMapType, JoinOn,
JoinOnRef, NoopBatchTransformer, StatefulStreamResult, apply_join_filter_to_indices,
build_batch_from_indices, build_join_schema, check_join_is_valid, equal_rows_arr,
matchable_join_keys, symmetric_join_output_partitioning, update_hash,
};
use crate::projection::{
JoinData, ProjectionExec, try_pushdown_through_join_with_column_indices,
};
use crate::stream::EmptyRecordBatchStream;
use crate::{ChildrenPropertiesMode, ReplaceChildrenOptions, validate_child_count};
use crate::{
DisplayAs, DisplayFormatType, Distribution, ExecutionPlan, ExecutionPlanProperties,
InputDistributionRequirements, PlanProperties, RecordBatchStream,
SendableRecordBatchStream,
joins::StreamJoinPartitionMode,
metrics::{ExecutionPlanMetricsSet, MetricsSet},
};
use arrow::array::{
ArrowPrimitiveType, NativeAdapter, PrimitiveArray, PrimitiveBuilder, UInt32Array,
UInt64Array,
};
use arrow::compute::concat_batches;
use arrow::datatypes::{ArrowNativeType, Schema, SchemaRef};
use arrow::record_batch::RecordBatch;
use datafusion_common::hash_utils::create_hashes;
use datafusion_common::tree_node::TreeNodeRecursion;
use datafusion_common::utils::bisect;
use datafusion_common::utils::memory::RecordBatchMemoryCounter;
use datafusion_common::{
HashSet, JoinSide, JoinType, NullEquality, Result, assert_eq_or_internal_err,
plan_err,
};
use datafusion_execution::TaskContext;
use datafusion_execution::memory_pool::MemoryConsumer;
use datafusion_expr::interval_arithmetic::Interval;
use datafusion_physical_expr::equivalence::join_equivalence_properties;
use datafusion_physical_expr::intervals::cp_solver::ExprIntervalGraph;
use datafusion_physical_expr_common::physical_expr::{PhysicalExprRef, fmt_sql};
use datafusion_physical_expr_common::sort_expr::{LexOrdering, OrderingRequirements};
use datafusion_common::hash_utils::RandomState;
use datafusion_physical_expr_common::utils::evaluate_expressions_to_arrays;
use futures::{Stream, StreamExt, ready};
const HASHMAP_SHRINK_SCALE_FACTOR: usize = 4;
#[derive(Debug, Clone)]
pub struct SymmetricHashJoinExec {
pub(crate) left: Arc<dyn ExecutionPlan>,
pub(crate) right: Arc<dyn ExecutionPlan>,
pub(crate) on: Vec<(PhysicalExprRef, PhysicalExprRef)>,
pub(crate) filter: Option<JoinFilter>,
pub(crate) join_type: JoinType,
random_state: RandomState,
metrics: ExecutionPlanMetricsSet,
column_indices: Vec<ColumnIndex>,
pub(crate) null_equality: NullEquality,
pub(crate) left_sort_exprs: Option<LexOrdering>,
pub(crate) right_sort_exprs: Option<LexOrdering>,
mode: StreamJoinPartitionMode,
cache: Arc<PlanProperties>,
}
impl SymmetricHashJoinExec {
#[expect(clippy::too_many_arguments)]
pub fn try_new(
left: Arc<dyn ExecutionPlan>,
right: Arc<dyn ExecutionPlan>,
on: JoinOn,
filter: Option<JoinFilter>,
join_type: &JoinType,
null_equality: NullEquality,
left_sort_exprs: Option<LexOrdering>,
right_sort_exprs: Option<LexOrdering>,
mode: StreamJoinPartitionMode,
) -> Result<Self> {
let left_schema = left.schema();
let right_schema = right.schema();
if on.is_empty() {
return plan_err!(
"On constraints in SymmetricHashJoinExec should be non-empty"
);
}
check_join_is_valid(&left_schema, &right_schema, &on)?;
let (schema, column_indices) =
build_join_schema(&left_schema, &right_schema, join_type);
let random_state = RandomState::with_seed(0);
let schema = Arc::new(schema);
let cache = Self::compute_properties(&left, &right, schema, *join_type, &on)?;
Ok(SymmetricHashJoinExec {
left,
right,
on,
filter,
join_type: *join_type,
random_state,
metrics: ExecutionPlanMetricsSet::new(),
column_indices,
null_equality,
left_sort_exprs,
right_sort_exprs,
mode,
cache: Arc::new(cache),
})
}
fn compute_properties(
left: &Arc<dyn ExecutionPlan>,
right: &Arc<dyn ExecutionPlan>,
schema: SchemaRef,
join_type: JoinType,
join_on: JoinOnRef,
) -> Result<PlanProperties> {
let eq_properties = join_equivalence_properties(
left.equivalence_properties().clone(),
right.equivalence_properties().clone(),
&join_type,
schema,
&[false, false],
None,
join_on,
)?;
let output_partitioning =
symmetric_join_output_partitioning(left, right, &join_type)?;
Ok(PlanProperties::new(
eq_properties,
output_partitioning,
emission_type_from_children([left, right]),
boundedness_from_children([left, right]),
))
}
pub fn left(&self) -> &Arc<dyn ExecutionPlan> {
&self.left
}
pub fn right(&self) -> &Arc<dyn ExecutionPlan> {
&self.right
}
pub fn on(&self) -> &[(PhysicalExprRef, PhysicalExprRef)] {
&self.on
}
pub fn filter(&self) -> Option<&JoinFilter> {
self.filter.as_ref()
}
pub fn join_type(&self) -> &JoinType {
&self.join_type
}
pub fn null_equality(&self) -> NullEquality {
self.null_equality
}
pub fn partition_mode(&self) -> StreamJoinPartitionMode {
self.mode
}
pub fn left_sort_exprs(&self) -> Option<&LexOrdering> {
self.left_sort_exprs.as_ref()
}
pub fn right_sort_exprs(&self) -> Option<&LexOrdering> {
self.right_sort_exprs.as_ref()
}
#[doc(hidden)]
pub fn check_if_order_information_available(&self) -> Result<bool> {
if let Some(filter) = self.filter() {
let left = self.left();
if let Some(left_ordering) = left.output_ordering() {
let right = self.right();
if let Some(right_ordering) = right.output_ordering() {
let left_convertible = convert_sort_expr_with_filter_schema(
&JoinSide::Left,
filter,
&left.schema(),
&left_ordering[0],
)?
.is_some();
let right_convertible = convert_sort_expr_with_filter_schema(
&JoinSide::Right,
filter,
&right.schema(),
&right_ordering[0],
)?
.is_some();
return Ok(left_convertible && right_convertible);
}
}
}
Ok(false)
}
}
impl DisplayAs for SymmetricHashJoinExec {
fn fmt_as(&self, t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
match t {
DisplayFormatType::Default | DisplayFormatType::Verbose => {
let display_filter = self.filter.as_ref().map_or_else(
|| "".to_string(),
|f| format!(", filter={}", f.expression()),
);
let on = self
.on
.iter()
.map(|(c1, c2)| format!("({c1}, {c2})"))
.collect::<Vec<String>>()
.join(", ");
write!(
f,
"SymmetricHashJoinExec: mode={:?}, join_type={:?}, on=[{}]{}",
self.mode, self.join_type, on, display_filter
)
}
DisplayFormatType::TreeRender => {
let on = self
.on
.iter()
.map(|(c1, c2)| {
format!("({} = {})", fmt_sql(c1.as_ref()), fmt_sql(c2.as_ref()))
})
.collect::<Vec<String>>()
.join(", ");
writeln!(f, "mode={:?}", self.mode)?;
if *self.join_type() != JoinType::Inner {
writeln!(f, "join_type={:?}", self.join_type)?;
}
writeln!(f, "on={on}")
}
}
}
}
impl ExecutionPlan for SymmetricHashJoinExec {
fn name(&self) -> &'static str {
"SymmetricHashJoinExec"
}
fn properties(&self) -> &Arc<PlanProperties> {
&self.cache
}
fn required_input_distribution(&self) -> Vec<Distribution> {
self.input_distribution_requirements().into_per_child()
}
fn input_distribution_requirements(&self) -> InputDistributionRequirements {
match self.mode {
StreamJoinPartitionMode::Partitioned => {
let (left_expr, right_expr) = self
.on
.iter()
.map(|(l, r)| (Arc::clone(l) as _, Arc::clone(r) as _))
.unzip();
InputDistributionRequirements::co_partitioned(vec![
Distribution::KeyPartitioned(left_expr),
Distribution::KeyPartitioned(right_expr),
])
}
StreamJoinPartitionMode::SinglePartition => {
InputDistributionRequirements::new(vec![
Distribution::SinglePartition,
Distribution::SinglePartition,
])
}
}
}
fn required_input_ordering(&self) -> Vec<Option<OrderingRequirements>> {
vec![
self.left_sort_exprs
.as_ref()
.map(|e| OrderingRequirements::from(e.clone())),
self.right_sort_exprs
.as_ref()
.map(|e| OrderingRequirements::from(e.clone())),
]
}
fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
vec![&self.left, &self.right]
}
fn apply_expressions(
&self,
f: &mut dyn FnMut(&Arc<dyn crate::PhysicalExpr>) -> Result<TreeNodeRecursion>,
) -> Result<TreeNodeRecursion> {
let join_keys = self.on.iter().flat_map(|(left, right)| [left, right]);
let filter = self.filter.iter().map(|filter| filter.expression());
crate::apply_expression_roots(join_keys.chain(filter), f)
}
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(),
..Self::clone(&*self)
}))
}
ChildrenPropertiesMode::Recompute => {
Ok(Arc::new(SymmetricHashJoinExec::try_new(
Arc::clone(&children[0]),
Arc::clone(&children[1]),
self.on.clone(),
self.filter.clone(),
&self.join_type,
self.null_equality,
self.left_sort_exprs.clone(),
self.right_sort_exprs.clone(),
self.mode,
)?))
}
}
}
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 metrics(&self) -> Option<MetricsSet> {
Some(self.metrics.clone_inner())
}
fn execute(
&self,
partition: usize,
context: Arc<TaskContext>,
) -> Result<SendableRecordBatchStream> {
let left_partitions = self.left.output_partitioning().partition_count();
let right_partitions = self.right.output_partitioning().partition_count();
assert_eq_or_internal_err!(
left_partitions,
right_partitions,
"Invalid SymmetricHashJoinExec, partition count mismatch {left_partitions}!={right_partitions},\
consider using RepartitionExec"
);
let (left_sorted_filter_expr, right_sorted_filter_expr, graph) = match (
self.left_sort_exprs(),
self.right_sort_exprs(),
&self.filter,
) {
(Some(left_sort_exprs), Some(right_sort_exprs), Some(filter)) => {
let (left, right, graph) = prepare_sorted_exprs(
filter,
&self.left,
&self.right,
left_sort_exprs,
right_sort_exprs,
)?;
(Some(left), Some(right), Some(graph))
}
_ => (None, None, None),
};
let (on_left, on_right) = self.on.iter().cloned().unzip();
let left_side_joiner =
OneSideHashJoiner::new(JoinSide::Left, on_left, self.left.schema());
let right_side_joiner =
OneSideHashJoiner::new(JoinSide::Right, on_right, self.right.schema());
let left_stream = self.left.execute(partition, Arc::clone(&context))?;
let right_stream = self.right.execute(partition, Arc::clone(&context))?;
let batch_size = context.session_config().batch_size();
let enforce_batch_size_in_joins =
context.session_config().enforce_batch_size_in_joins();
let reservation = Arc::new(
MemoryConsumer::new(format!("SymmetricHashJoinStream[{partition}]"))
.register(context.memory_pool()),
);
if let Some(g) = graph.as_ref() {
reservation.try_grow(g.size())?;
}
if enforce_batch_size_in_joins {
Ok(Box::pin(SymmetricHashJoinStream {
left_stream,
right_stream,
schema: self.schema(),
filter: self.filter.clone(),
join_type: self.join_type,
random_state: self.random_state.clone(),
left: left_side_joiner,
right: right_side_joiner,
column_indices: self.column_indices.clone(),
metrics: StreamJoinMetrics::new(partition, &self.metrics),
graph,
left_sorted_filter_expr,
right_sorted_filter_expr,
null_equality: self.null_equality,
state: SHJStreamState::PullRight,
reservation,
batch_transformer: BatchSplitter::new(batch_size),
}))
} else {
Ok(Box::pin(SymmetricHashJoinStream {
left_stream,
right_stream,
schema: self.schema(),
filter: self.filter.clone(),
join_type: self.join_type,
random_state: self.random_state.clone(),
left: left_side_joiner,
right: right_side_joiner,
column_indices: self.column_indices.clone(),
metrics: StreamJoinMetrics::new(partition, &self.metrics),
graph,
left_sorted_filter_expr,
right_sorted_filter_expr,
null_equality: self.null_equality,
state: SHJStreamState::PullRight,
reservation,
batch_transformer: NoopBatchTransformer::new(),
}))
}
}
fn try_swapping_with_projection(
&self,
projection: &ProjectionExec,
) -> Result<Option<Arc<dyn ExecutionPlan>>> {
let schema = self.schema();
if let Some(JoinData {
projected_left_child,
projected_right_child,
join_filter,
join_on,
}) = try_pushdown_through_join_with_column_indices(
projection,
self.left(),
self.right(),
self.on(),
&schema,
self.filter(),
self.column_indices.as_slice(),
)? {
SymmetricHashJoinExec::try_new(
Arc::new(projected_left_child),
Arc::new(projected_right_child),
join_on,
join_filter,
self.join_type(),
self.null_equality(),
self.right().output_ordering().cloned(),
self.left().output_ordering().cloned(),
self.partition_mode(),
)
.map(|e| Some(Arc::new(e) as _))
} else {
Ok(None)
}
}
#[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,
on,
filter,
join_type,
null_equality,
left_sort_exprs,
right_sort_exprs,
mode,
random_state: _,
metrics: _,
column_indices: _,
cache: _,
} = self;
let left = ctx.encode_child(left)?;
let right = ctx.encode_child(right)?;
let on = on
.iter()
.map(|(left, right)| {
Ok(protobuf::JoinOn {
left: Some(ctx.encode_expr(left)?),
right: Some(ctx.encode_expr(right)?),
})
})
.collect::<Result<Vec<_>>>()?;
let join_type = match join_type {
JoinType::Inner => protobuf::JoinType::Inner,
JoinType::Left => protobuf::JoinType::Left,
JoinType::Right => protobuf::JoinType::Right,
JoinType::Full => protobuf::JoinType::Full,
JoinType::LeftSemi => protobuf::JoinType::Leftsemi,
JoinType::RightSemi => protobuf::JoinType::Rightsemi,
JoinType::LeftAnti => protobuf::JoinType::Leftanti,
JoinType::RightAnti => protobuf::JoinType::Rightanti,
JoinType::LeftMark => protobuf::JoinType::Leftmark,
JoinType::RightMark => protobuf::JoinType::Rightmark,
};
let null_equality = match null_equality {
NullEquality::NullEqualsNothing => protobuf::NullEquality::NullEqualsNothing,
NullEquality::NullEqualsNull => protobuf::NullEquality::NullEqualsNull,
};
let partition_mode = match mode {
StreamJoinPartitionMode::SinglePartition => {
protobuf::StreamPartitionMode::SinglePartition
}
StreamJoinPartitionMode::Partitioned => {
protobuf::StreamPartitionMode::PartitionedExec
}
};
let filter = filter
.as_ref()
.map(|filter| -> Result<protobuf::JoinFilter> {
let expression = ctx.encode_expr(filter.expression())?;
let column_indices = filter
.column_indices()
.iter()
.map(|column_index| {
let side = match column_index.side {
JoinSide::Left => protobuf::JoinSide::LeftSide,
JoinSide::Right => protobuf::JoinSide::RightSide,
JoinSide::None => protobuf::JoinSide::None,
};
protobuf::ColumnIndex {
index: column_index.index as u32,
side: side.into(),
}
})
.collect();
Ok(protobuf::JoinFilter {
expression: Some(expression),
column_indices,
schema: Some(filter.schema().as_ref().try_into()?),
})
})
.transpose()?;
let expr_ctx = ctx.expr_ctx();
let left_sort_exprs =
datafusion_physical_expr_common::sort_expr::optional_ordering_try_to_proto(
left_sort_exprs.as_ref(),
&expr_ctx,
)?;
let right_sort_exprs =
datafusion_physical_expr_common::sort_expr::optional_ordering_try_to_proto(
right_sort_exprs.as_ref(),
&expr_ctx,
)?;
Ok(Some(protobuf::PhysicalPlanNode {
physical_plan_type: Some(
protobuf::physical_plan_node::PhysicalPlanType::SymmetricHashJoin(
Box::new(protobuf::SymmetricHashJoinExecNode {
left: Some(Box::new(left)),
right: Some(Box::new(right)),
on,
join_type: join_type.into(),
partition_mode: partition_mode.into(),
null_equality: null_equality.into(),
filter,
left_sort_exprs,
right_sort_exprs,
}),
),
),
}))
}
}
#[cfg(feature = "proto")]
impl SymmetricHashJoinExec {
pub fn try_from_proto(
node: &datafusion_proto_models::protobuf::PhysicalPlanNode,
ctx: &crate::proto::ExecutionPlanDecodeCtx<'_>,
) -> Result<Arc<dyn ExecutionPlan>> {
use datafusion_common::internal_datafusion_err;
use datafusion_proto_models::protobuf;
let sym_join = crate::expect_plan_variant!(
node,
protobuf::physical_plan_node::PhysicalPlanType::SymmetricHashJoin,
"SymmetricHashJoinExec",
);
let protobuf::SymmetricHashJoinExecNode {
left,
right,
on,
join_type,
partition_mode,
null_equality,
filter,
left_sort_exprs,
right_sort_exprs,
} = &**sym_join;
let left =
ctx.decode_required_child(left.as_deref(), "SymmetricHashJoinExec", "left")?;
let right = ctx.decode_required_child(
right.as_deref(),
"SymmetricHashJoinExec",
"right",
)?;
let left_schema = left.schema();
let right_schema = right.schema();
let on = on
.iter()
.map(|columns| {
let left = ctx.decode_required_expr(
columns.left.as_ref(),
left_schema.as_ref(),
"SymmetricHashJoinExec",
"on.left",
)?;
let right = ctx.decode_required_expr(
columns.right.as_ref(),
right_schema.as_ref(),
"SymmetricHashJoinExec",
"on.right",
)?;
Ok((left, right))
})
.collect::<Result<JoinOn>>()?;
let join_type = match protobuf::JoinType::try_from(*join_type).map_err(|_| {
internal_datafusion_err!(
"SymmetricHashJoinExec: unknown JoinType {join_type}"
)
})? {
protobuf::JoinType::Inner => JoinType::Inner,
protobuf::JoinType::Left => JoinType::Left,
protobuf::JoinType::Right => JoinType::Right,
protobuf::JoinType::Full => JoinType::Full,
protobuf::JoinType::Leftsemi => JoinType::LeftSemi,
protobuf::JoinType::Rightsemi => JoinType::RightSemi,
protobuf::JoinType::Leftanti => JoinType::LeftAnti,
protobuf::JoinType::Rightanti => JoinType::RightAnti,
protobuf::JoinType::Leftmark => JoinType::LeftMark,
protobuf::JoinType::Rightmark => JoinType::RightMark,
};
let null_equality = match protobuf::NullEquality::try_from(*null_equality)
.map_err(|_| {
internal_datafusion_err!(
"SymmetricHashJoinExec: unknown NullEquality {null_equality}"
)
})? {
protobuf::NullEquality::NullEqualsNothing => NullEquality::NullEqualsNothing,
protobuf::NullEquality::NullEqualsNull => NullEquality::NullEqualsNull,
};
let partition_mode = match protobuf::StreamPartitionMode::try_from(
*partition_mode,
)
.map_err(|_| {
internal_datafusion_err!(
"SymmetricHashJoinExec: unknown StreamPartitionMode {partition_mode}"
)
})? {
protobuf::StreamPartitionMode::SinglePartition => {
StreamJoinPartitionMode::SinglePartition
}
protobuf::StreamPartitionMode::PartitionedExec => {
StreamJoinPartitionMode::Partitioned
}
};
let filter = filter
.as_ref()
.map(|filter| -> Result<JoinFilter> {
let schema: Schema = filter
.schema
.as_ref()
.ok_or_else(|| {
internal_datafusion_err!(
"SymmetricHashJoinExec: JoinFilter missing schema"
)
})?
.try_into()?;
let expression = ctx.decode_required_expr(
filter.expression.as_ref(),
&schema,
"SymmetricHashJoinExec",
"filter.expression",
)?;
let column_indices = filter
.column_indices
.iter()
.map(|column_index| {
let side = protobuf::JoinSide::try_from(column_index.side)
.map_err(|_| {
internal_datafusion_err!(
"SymmetricHashJoinExec: unknown JoinSide {}",
column_index.side
)
})?;
let side = match side {
protobuf::JoinSide::LeftSide => JoinSide::Left,
protobuf::JoinSide::RightSide => JoinSide::Right,
protobuf::JoinSide::None => JoinSide::None,
};
Ok(ColumnIndex {
index: column_index.index as usize,
side,
})
})
.collect::<Result<Vec<_>>>()?;
Ok(JoinFilter::new(
expression,
column_indices,
Arc::new(schema),
))
})
.transpose()?;
let left_sort_exprs =
datafusion_physical_expr_common::sort_expr::optional_ordering_try_from_proto(
left_sort_exprs,
&ctx.expr_ctx(left_schema.as_ref()),
)?;
let right_sort_exprs =
datafusion_physical_expr_common::sort_expr::optional_ordering_try_from_proto(
right_sort_exprs,
&ctx.expr_ctx(right_schema.as_ref()),
)?;
Self::try_new(
left,
right,
on,
filter,
&join_type,
null_equality,
left_sort_exprs,
right_sort_exprs,
partition_mode,
)
.map(|exec| Arc::new(exec) as _)
}
}
struct SymmetricHashJoinStream<T> {
left_stream: SendableRecordBatchStream,
right_stream: SendableRecordBatchStream,
schema: Arc<Schema>,
filter: Option<JoinFilter>,
join_type: JoinType,
left: OneSideHashJoiner,
right: OneSideHashJoiner,
column_indices: Vec<ColumnIndex>,
graph: Option<ExprIntervalGraph>,
left_sorted_filter_expr: Option<SortedFilterExpr>,
right_sorted_filter_expr: Option<SortedFilterExpr>,
random_state: RandomState,
null_equality: NullEquality,
metrics: StreamJoinMetrics,
reservation: SharedMemoryReservation,
state: SHJStreamState,
batch_transformer: T,
}
impl<T: BatchTransformer + Unpin + Send> RecordBatchStream
for SymmetricHashJoinStream<T>
{
fn schema(&self) -> SchemaRef {
Arc::clone(&self.schema)
}
}
impl<T: BatchTransformer + Unpin + Send> Stream for SymmetricHashJoinStream<T> {
type Item = Result<RecordBatch>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
self.poll_next_impl(cx)
}
}
fn determine_prune_length(
buffer: &RecordBatch,
build_side_filter_expr: &SortedFilterExpr,
) -> Result<usize> {
let origin_sorted_expr = build_side_filter_expr.origin_sorted_expr();
let interval = build_side_filter_expr.interval();
let batch_arr = origin_sorted_expr
.expr
.evaluate(buffer)?
.into_array(buffer.num_rows())?;
let target = if origin_sorted_expr.options.descending {
interval.upper().clone()
} else {
interval.lower().clone()
};
bisect::<true>(&[batch_arr], &[target], &[origin_sorted_expr.options])
}
fn need_to_produce_result_in_final(build_side: JoinSide, join_type: JoinType) -> bool {
if build_side == JoinSide::Left {
matches!(
join_type,
JoinType::Left
| JoinType::LeftAnti
| JoinType::Full
| JoinType::LeftSemi
| JoinType::LeftMark
)
} else {
matches!(
join_type,
JoinType::Right
| JoinType::RightAnti
| JoinType::Full
| JoinType::RightSemi
| JoinType::RightMark
)
}
}
fn calculate_indices_by_join_type<L: ArrowPrimitiveType, R: ArrowPrimitiveType>(
build_side: JoinSide,
prune_length: usize,
visited_rows: &HashSet<usize>,
deleted_offset: usize,
join_type: JoinType,
) -> Result<(PrimitiveArray<L>, PrimitiveArray<R>)>
where
NativeAdapter<L>: From<<L as ArrowPrimitiveType>::Native>,
{
let result = match (build_side, join_type) {
(JoinSide::Left, JoinType::LeftMark) => {
let build_indices = (0..prune_length)
.map(L::Native::from_usize)
.collect::<PrimitiveArray<L>>();
let probe_indices = (0..prune_length)
.map(|idx| {
visited_rows
.contains(&(idx + deleted_offset))
.then_some(R::Native::from_usize(0).unwrap())
})
.collect();
(build_indices, probe_indices)
}
(JoinSide::Right, JoinType::RightMark) => {
let build_indices = (0..prune_length)
.map(L::Native::from_usize)
.collect::<PrimitiveArray<L>>();
let probe_indices = (0..prune_length)
.map(|idx| {
visited_rows
.contains(&(idx + deleted_offset))
.then_some(R::Native::from_usize(0).unwrap())
})
.collect();
(build_indices, probe_indices)
}
(JoinSide::Left, JoinType::Left | JoinType::LeftAnti)
| (JoinSide::Right, JoinType::Right | JoinType::RightAnti)
| (_, JoinType::Full) => {
let build_unmatched_indices =
get_pruning_anti_indices(prune_length, deleted_offset, visited_rows);
let mut builder =
PrimitiveBuilder::<R>::with_capacity(build_unmatched_indices.len());
builder.append_nulls(build_unmatched_indices.len());
let probe_indices = builder.finish();
(build_unmatched_indices, probe_indices)
}
(JoinSide::Left, JoinType::LeftSemi) | (JoinSide::Right, JoinType::RightSemi) => {
let build_unmatched_indices =
get_pruning_semi_indices(prune_length, deleted_offset, visited_rows);
let mut builder =
PrimitiveBuilder::<R>::with_capacity(build_unmatched_indices.len());
builder.append_nulls(build_unmatched_indices.len());
let probe_indices = builder.finish();
(build_unmatched_indices, probe_indices)
}
_ => unreachable!(),
};
Ok(result)
}
pub(crate) fn build_side_determined_results(
build_hash_joiner: &OneSideHashJoiner,
output_schema: &SchemaRef,
prune_length: usize,
probe_schema: SchemaRef,
join_type: JoinType,
column_indices: &[ColumnIndex],
) -> Result<Option<RecordBatch>> {
if prune_length > 0
&& need_to_produce_result_in_final(build_hash_joiner.build_side, join_type)
{
let (build_indices, probe_indices) = calculate_indices_by_join_type(
build_hash_joiner.build_side,
prune_length,
&build_hash_joiner.visited_rows,
build_hash_joiner.deleted_offset,
join_type,
)?;
let empty_probe_batch = RecordBatch::new_empty(probe_schema);
build_batch_from_indices(
output_schema,
&build_hash_joiner.input_buffer,
&empty_probe_batch,
&build_indices,
&probe_indices,
column_indices,
build_hash_joiner.build_side,
join_type,
None,
)
.map(|batch| (batch.num_rows() > 0).then_some(batch))
} else {
Ok(None)
}
}
#[expect(clippy::too_many_arguments)]
pub(crate) fn join_with_probe_batch(
build_hash_joiner: &mut OneSideHashJoiner,
probe_hash_joiner: &mut OneSideHashJoiner,
schema: &SchemaRef,
join_type: JoinType,
filter: Option<&JoinFilter>,
probe_batch: &RecordBatch,
column_indices: &[ColumnIndex],
random_state: &RandomState,
null_equality: NullEquality,
) -> Result<Option<RecordBatch>> {
if build_hash_joiner.input_buffer.num_rows() == 0 || probe_batch.num_rows() == 0 {
return Ok(None);
}
let (build_indices, probe_indices) = lookup_join_hashmap(
&build_hash_joiner.hashmap,
&build_hash_joiner.input_buffer,
probe_batch,
&build_hash_joiner.on,
&probe_hash_joiner.on,
random_state,
null_equality,
&mut build_hash_joiner.hashes_buffer,
Some(build_hash_joiner.deleted_offset),
)?;
let (build_indices, probe_indices) = if let Some(filter) = filter {
apply_join_filter_to_indices(
&build_hash_joiner.input_buffer,
probe_batch,
build_indices,
probe_indices,
filter,
build_hash_joiner.build_side,
None,
join_type,
)?
} else {
(build_indices, probe_indices)
};
if need_to_produce_result_in_final(build_hash_joiner.build_side, join_type) {
record_visited_indices(
&mut build_hash_joiner.visited_rows,
build_hash_joiner.deleted_offset,
&build_indices,
);
}
if need_to_produce_result_in_final(build_hash_joiner.build_side.negate(), join_type) {
record_visited_indices(
&mut probe_hash_joiner.visited_rows,
probe_hash_joiner.offset,
&probe_indices,
);
}
if matches!(
join_type,
JoinType::LeftAnti
| JoinType::RightAnti
| JoinType::LeftSemi
| JoinType::LeftMark
| JoinType::RightSemi
| JoinType::RightMark
) {
Ok(None)
} else {
build_batch_from_indices(
schema,
&build_hash_joiner.input_buffer,
probe_batch,
&build_indices,
&probe_indices,
column_indices,
build_hash_joiner.build_side,
join_type,
None,
)
.map(|batch| (batch.num_rows() > 0).then_some(batch))
}
}
#[expect(clippy::too_many_arguments)]
fn lookup_join_hashmap(
build_hashmap: &PruningJoinHashMap,
build_batch: &RecordBatch,
probe_batch: &RecordBatch,
build_on: &[PhysicalExprRef],
probe_on: &[PhysicalExprRef],
random_state: &RandomState,
null_equality: NullEquality,
hashes_buffer: &mut Vec<u64>,
deleted_offset: Option<usize>,
) -> Result<(UInt64Array, UInt32Array)> {
let keys_values = evaluate_expressions_to_arrays(probe_on, probe_batch)?;
let build_join_values = evaluate_expressions_to_arrays(build_on, build_batch)?;
hashes_buffer.clear();
hashes_buffer.resize(probe_batch.num_rows(), 0);
let hash_values = create_hashes(&keys_values, random_state, hashes_buffer)?;
let valid_keys = matchable_join_keys(&keys_values, null_equality);
let (mut matched_probe, mut matched_build) = build_hashmap.get_matched_indices(
Box::new(
hash_values
.iter()
.enumerate()
.filter(|(i, _)| {
valid_keys.as_ref().is_none_or(|valid| valid.is_valid(*i))
})
.rev(),
),
deleted_offset,
);
matched_probe.reverse();
matched_build.reverse();
let build_indices: UInt64Array = matched_build.into();
let probe_indices: UInt32Array = matched_probe.into();
let (build_indices, probe_indices) = equal_rows_arr(
&build_indices,
&probe_indices,
&build_join_values,
&keys_values,
null_equality,
&mut None,
)?;
Ok((build_indices, probe_indices))
}
pub struct OneSideHashJoiner {
build_side: JoinSide,
pub input_buffer: RecordBatch,
pub(crate) on: Vec<PhysicalExprRef>,
pub(crate) hashmap: PruningJoinHashMap,
pub(crate) hashes_buffer: Vec<u64>,
pub(crate) visited_rows: HashSet<usize>,
pub(crate) offset: usize,
pub(crate) deleted_offset: usize,
}
impl OneSideHashJoiner {
pub fn size(&self) -> usize {
size_of_val(self)
+ self.input_buffer.get_array_memory_size()
+ self.on.capacity() * size_of::<PhysicalExprRef>()
+ self.hashmap.size()
- size_of_val(&self.hashmap)
+ self.hashes_buffer.capacity() * size_of::<u64>()
+ self.visited_rows.allocation_size()
}
fn size_without_input_buffer(&self) -> usize {
self.size() - self.input_buffer.get_array_memory_size()
}
pub fn new(
build_side: JoinSide,
on: Vec<PhysicalExprRef>,
schema: SchemaRef,
) -> Self {
Self {
build_side,
input_buffer: RecordBatch::new_empty(schema),
on,
hashmap: PruningJoinHashMap::with_capacity(0),
hashes_buffer: vec![],
visited_rows: HashSet::new(),
offset: 0,
deleted_offset: 0,
}
}
pub(crate) fn update_internal_state(
&mut self,
batch: &RecordBatch,
random_state: &RandomState,
null_equality: NullEquality,
) -> Result<()> {
self.input_buffer = concat_batches(&batch.schema(), [&self.input_buffer, batch])?;
self.hashes_buffer.resize(batch.num_rows(), 0);
update_hash(
&self.on,
batch,
&mut self.hashmap,
self.offset,
random_state,
&mut self.hashes_buffer,
self.deleted_offset,
false,
null_equality,
)?;
Ok(())
}
pub(crate) fn calculate_prune_length_with_probe_batch(
&mut self,
build_side_sorted_filter_expr: &mut SortedFilterExpr,
probe_side_sorted_filter_expr: &mut SortedFilterExpr,
graph: &mut ExprIntervalGraph,
) -> Result<usize> {
if self.input_buffer.num_rows() == 0 {
return Ok(0);
}
let mut filter_intervals = vec![];
for expr in [
&build_side_sorted_filter_expr,
&probe_side_sorted_filter_expr,
] {
filter_intervals.push((expr.node_index(), expr.interval().clone()))
}
graph.update_ranges(&mut filter_intervals, Interval::TRUE)?;
let calculated_build_side_interval = filter_intervals.remove(0).1;
if calculated_build_side_interval.eq(build_side_sorted_filter_expr.interval()) {
return Ok(0);
}
build_side_sorted_filter_expr.set_interval(calculated_build_side_interval);
determine_prune_length(&self.input_buffer, build_side_sorted_filter_expr)
}
pub(crate) fn prune_internal_state(&mut self, prune_length: usize) -> Result<()> {
self.hashmap.prune_hash_values(
prune_length,
self.deleted_offset as u64,
HASHMAP_SHRINK_SCALE_FACTOR,
);
for row in self.deleted_offset..(self.deleted_offset + prune_length) {
self.visited_rows.remove(&row);
}
self.input_buffer = self
.input_buffer
.slice(prune_length, self.input_buffer.num_rows() - prune_length);
self.deleted_offset += prune_length;
Ok(())
}
}
impl<T: BatchTransformer> SymmetricHashJoinStream<T> {
fn poll_next_impl(
&mut self,
cx: &mut Context<'_>,
) -> Poll<Option<Result<RecordBatch>>> {
loop {
match self.batch_transformer.next() {
None => {
let result = match self.state() {
SHJStreamState::PullRight => {
ready!(self.fetch_next_from_right_stream(cx))
}
SHJStreamState::PullLeft => {
ready!(self.fetch_next_from_left_stream(cx))
}
SHJStreamState::RightExhausted => {
ready!(self.handle_right_stream_end(cx))
}
SHJStreamState::LeftExhausted => {
ready!(self.handle_left_stream_end(cx))
}
SHJStreamState::BothExhausted {
final_result: false,
} => self.prepare_for_final_results_after_exhaustion(),
SHJStreamState::BothExhausted { final_result: true } => {
return Poll::Ready(None);
}
};
match result? {
StatefulStreamResult::Ready(None) => {
return Poll::Ready(None);
}
StatefulStreamResult::Ready(Some(batch)) => {
self.batch_transformer.set_batch(batch);
self.update_reservation()?;
}
_ => {}
}
}
Some((batch, _)) => {
self.update_reservation()?;
return self
.metrics
.baseline_metrics
.record_poll(Poll::Ready(Some(Ok(batch))));
}
}
}
}
fn cleanup_depleted_right_stream(&mut self) {
let right_schema = self.right_stream.schema();
self.right_stream = Box::pin(EmptyRecordBatchStream::new(right_schema));
}
fn cleanup_depleted_left_stream(&mut self) {
let left_schema = self.left_stream.schema();
self.left_stream = Box::pin(EmptyRecordBatchStream::new(left_schema));
}
fn fetch_next_from_right_stream(
&mut self,
cx: &mut Context<'_>,
) -> Poll<Result<StatefulStreamResult<Option<RecordBatch>>>> {
match ready!(self.right_stream().poll_next_unpin(cx)) {
Some(Ok(batch)) => {
if batch.num_rows() == 0 {
return Poll::Ready(Ok(StatefulStreamResult::Continue));
}
self.set_state(SHJStreamState::PullLeft);
Poll::Ready(self.process_batch_from_right(&batch))
}
Some(Err(e)) => Poll::Ready(Err(e)),
None => {
self.cleanup_depleted_right_stream();
self.set_state(SHJStreamState::RightExhausted);
Poll::Ready(Ok(StatefulStreamResult::Continue))
}
}
}
fn fetch_next_from_left_stream(
&mut self,
cx: &mut Context<'_>,
) -> Poll<Result<StatefulStreamResult<Option<RecordBatch>>>> {
match ready!(self.left_stream().poll_next_unpin(cx)) {
Some(Ok(batch)) => {
if batch.num_rows() == 0 {
return Poll::Ready(Ok(StatefulStreamResult::Continue));
}
self.set_state(SHJStreamState::PullRight);
Poll::Ready(self.process_batch_from_left(&batch))
}
Some(Err(e)) => Poll::Ready(Err(e)),
None => {
self.cleanup_depleted_left_stream();
self.set_state(SHJStreamState::LeftExhausted);
Poll::Ready(Ok(StatefulStreamResult::Continue))
}
}
}
fn handle_right_stream_end(
&mut self,
cx: &mut Context<'_>,
) -> Poll<Result<StatefulStreamResult<Option<RecordBatch>>>> {
match ready!(self.left_stream().poll_next_unpin(cx)) {
Some(Ok(batch)) => {
if batch.num_rows() == 0 {
return Poll::Ready(Ok(StatefulStreamResult::Continue));
}
Poll::Ready(self.process_batch_after_right_end(&batch))
}
Some(Err(e)) => Poll::Ready(Err(e)),
None => {
self.cleanup_depleted_left_stream();
self.set_state(SHJStreamState::BothExhausted {
final_result: false,
});
Poll::Ready(Ok(StatefulStreamResult::Continue))
}
}
}
fn handle_left_stream_end(
&mut self,
cx: &mut Context<'_>,
) -> Poll<Result<StatefulStreamResult<Option<RecordBatch>>>> {
match ready!(self.right_stream().poll_next_unpin(cx)) {
Some(Ok(batch)) => {
if batch.num_rows() == 0 {
return Poll::Ready(Ok(StatefulStreamResult::Continue));
}
Poll::Ready(self.process_batch_after_left_end(&batch))
}
Some(Err(e)) => Poll::Ready(Err(e)),
None => {
self.cleanup_depleted_right_stream();
self.set_state(SHJStreamState::BothExhausted {
final_result: false,
});
Poll::Ready(Ok(StatefulStreamResult::Continue))
}
}
}
fn prepare_for_final_results_after_exhaustion(
&mut self,
) -> Result<StatefulStreamResult<Option<RecordBatch>>> {
self.set_state(SHJStreamState::BothExhausted { final_result: true });
self.process_batches_before_finalization()
}
fn process_batch_from_right(
&mut self,
batch: &RecordBatch,
) -> Result<StatefulStreamResult<Option<RecordBatch>>> {
self.perform_join_for_given_side(batch, JoinSide::Right)
.map(|maybe_batch| {
if maybe_batch.is_some() {
StatefulStreamResult::Ready(maybe_batch)
} else {
StatefulStreamResult::Continue
}
})
}
fn process_batch_from_left(
&mut self,
batch: &RecordBatch,
) -> Result<StatefulStreamResult<Option<RecordBatch>>> {
self.perform_join_for_given_side(batch, JoinSide::Left)
.map(|maybe_batch| {
if maybe_batch.is_some() {
StatefulStreamResult::Ready(maybe_batch)
} else {
StatefulStreamResult::Continue
}
})
}
fn process_batch_after_left_end(
&mut self,
right_batch: &RecordBatch,
) -> Result<StatefulStreamResult<Option<RecordBatch>>> {
self.process_batch_from_right(right_batch)
}
fn process_batch_after_right_end(
&mut self,
left_batch: &RecordBatch,
) -> Result<StatefulStreamResult<Option<RecordBatch>>> {
self.process_batch_from_left(left_batch)
}
fn process_batches_before_finalization(
&mut self,
) -> Result<StatefulStreamResult<Option<RecordBatch>>> {
let left_result = build_side_determined_results(
&self.left,
&self.schema,
self.left.input_buffer.num_rows(),
self.right.input_buffer.schema(),
self.join_type,
&self.column_indices,
)?;
let right_result = build_side_determined_results(
&self.right,
&self.schema,
self.right.input_buffer.num_rows(),
self.left.input_buffer.schema(),
self.join_type,
&self.column_indices,
)?;
let result = combine_two_batches(&self.schema, left_result, right_result)?;
if result.is_some() {
return Ok(StatefulStreamResult::Ready(result));
}
Ok(StatefulStreamResult::Continue)
}
fn right_stream(&mut self) -> &mut SendableRecordBatchStream {
&mut self.right_stream
}
fn left_stream(&mut self) -> &mut SendableRecordBatchStream {
&mut self.left_stream
}
fn set_state(&mut self, state: SHJStreamState) {
self.state = state;
}
fn state(&mut self) -> SHJStreamState {
self.state.clone()
}
fn size(&self) -> usize {
let mut batch_memory_counter = RecordBatchMemoryCounter::new();
batch_memory_counter.count_batch_with_array_overhead(&self.left.input_buffer);
batch_memory_counter.count_batch_with_array_overhead(&self.right.input_buffer);
self.batch_transformer
.count_memory(&mut batch_memory_counter);
let mut size = batch_memory_counter.memory_usage();
size += size_of_val(&self.schema);
size += size_of_val(&self.filter);
size += size_of_val(&self.join_type);
size += self.left.size_without_input_buffer();
size += self.right.size_without_input_buffer();
size += size_of_val(&self.column_indices);
size += self.graph.as_ref().map(|g| g.size()).unwrap_or(0);
size += size_of_val(&self.left_sorted_filter_expr);
size += size_of_val(&self.right_sorted_filter_expr);
size += size_of_val(&self.random_state);
size += size_of_val(&self.null_equality);
size += size_of_val(&self.metrics);
size
}
fn update_reservation(&mut self) -> Result<()> {
let capacity = self.size();
self.reservation.try_resize(capacity)?;
self.metrics.stream_memory_usage.set(capacity);
Ok(())
}
fn perform_join_for_given_side(
&mut self,
probe_batch: &RecordBatch,
probe_side: JoinSide,
) -> Result<Option<RecordBatch>> {
let (
probe_hash_joiner,
build_hash_joiner,
probe_side_sorted_filter_expr,
build_side_sorted_filter_expr,
probe_side_metrics,
) = if probe_side.eq(&JoinSide::Left) {
(
&mut self.left,
&mut self.right,
&mut self.left_sorted_filter_expr,
&mut self.right_sorted_filter_expr,
&mut self.metrics.left,
)
} else {
(
&mut self.right,
&mut self.left,
&mut self.right_sorted_filter_expr,
&mut self.left_sorted_filter_expr,
&mut self.metrics.right,
)
};
probe_side_metrics.input_batches.add(1);
probe_side_metrics.input_rows.add(probe_batch.num_rows());
probe_hash_joiner.update_internal_state(
probe_batch,
&self.random_state,
self.null_equality,
)?;
let equal_result = join_with_probe_batch(
build_hash_joiner,
probe_hash_joiner,
&self.schema,
self.join_type,
self.filter.as_ref(),
probe_batch,
&self.column_indices,
&self.random_state,
self.null_equality,
)?;
probe_hash_joiner.offset += probe_batch.num_rows();
let anti_result = if let (
Some(build_side_sorted_filter_expr),
Some(probe_side_sorted_filter_expr),
Some(graph),
) = (
build_side_sorted_filter_expr.as_mut(),
probe_side_sorted_filter_expr.as_mut(),
self.graph.as_mut(),
) {
calculate_filter_expr_intervals(
&build_hash_joiner.input_buffer,
build_side_sorted_filter_expr,
probe_batch,
probe_side_sorted_filter_expr,
)?;
let prune_length = build_hash_joiner
.calculate_prune_length_with_probe_batch(
build_side_sorted_filter_expr,
probe_side_sorted_filter_expr,
graph,
)?;
let result = build_side_determined_results(
build_hash_joiner,
&self.schema,
prune_length,
probe_batch.schema(),
self.join_type,
&self.column_indices,
)?;
build_hash_joiner.prune_internal_state(prune_length)?;
result
} else {
None
};
let result = combine_two_batches(&self.schema, equal_result, anti_result)?;
self.update_reservation()?;
Ok(result)
}
}
#[derive(Clone, Debug)]
pub enum SHJStreamState {
PullRight,
PullLeft,
RightExhausted,
LeftExhausted,
BothExhausted { final_result: bool },
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use std::sync::{LazyLock, Mutex};
use super::*;
use crate::joins::test_utils::{
build_sides_record_batches, compare_batches, complicated_filter,
create_memory_table, join_expr_tests_fixture_f64, join_expr_tests_fixture_i32,
join_expr_tests_fixture_temporal, partitioned_hash_join_with_filter,
partitioned_sym_join_with_filter, split_record_batches,
};
use crate::test::TestMemoryExec;
use arrow::array::{ArrayRef, Int32Array, StructArray};
use arrow::compute::SortOptions;
use arrow::datatypes::{DataType, Field, Fields, IntervalUnit, TimeUnit};
use datafusion_common::{DataFusionError, ScalarValue};
use datafusion_execution::config::SessionConfig;
use datafusion_execution::memory_pool::{
MemoryLimit, MemoryPool, MemoryReservation, UnboundedMemoryPool,
};
use datafusion_execution::runtime_env::{RuntimeEnv, RuntimeEnvBuilder};
use datafusion_expr::Operator;
use datafusion_physical_expr::expressions::{Column, binary, col, lit};
use datafusion_physical_expr_common::sort_expr::PhysicalSortExpr;
use rstest::*;
const TABLE_SIZE: i32 = 30;
type TableKey = (i32, i32, usize); type TableValue = (Vec<RecordBatch>, Vec<RecordBatch>);
static TABLE_CACHE: LazyLock<Mutex<HashMap<TableKey, TableValue>>> =
LazyLock::new(|| Mutex::new(HashMap::new()));
fn create_stream<T: BatchTransformer>(
batch_transformer: T,
input_schema: SchemaRef,
) -> SymmetricHashJoinStream<T> {
let context = TaskContext::default();
create_stream_with_context(batch_transformer, input_schema, &context)
}
fn create_stream_with_context<T: BatchTransformer>(
batch_transformer: T,
input_schema: SchemaRef,
context: &TaskContext,
) -> SymmetricHashJoinStream<T> {
let metrics = ExecutionPlanMetricsSet::new();
SymmetricHashJoinStream {
left_stream: Box::pin(EmptyRecordBatchStream::new(Arc::clone(&input_schema))),
right_stream: Box::pin(EmptyRecordBatchStream::new(Arc::clone(
&input_schema,
))),
schema: Arc::clone(&input_schema),
filter: None,
join_type: JoinType::Inner,
left: OneSideHashJoiner::new(
JoinSide::Left,
vec![],
Arc::clone(&input_schema),
),
right: OneSideHashJoiner::new(JoinSide::Right, vec![], input_schema),
column_indices: vec![],
graph: None,
left_sorted_filter_expr: None,
right_sorted_filter_expr: None,
random_state: RandomState::default(),
null_equality: NullEquality::NullEqualsNothing,
metrics: StreamJoinMetrics::new(0, &metrics),
reservation: Arc::new(
MemoryConsumer::new("SymmetricHashJoinStream[test]")
.register(context.memory_pool()),
),
state: SHJStreamState::PullRight,
batch_transformer,
}
}
fn expected_one_side_hash_joiner_size(joiner: &OneSideHashJoiner) -> usize {
size_of_val(joiner)
+ joiner.input_buffer.get_array_memory_size()
+ joiner.on.capacity() * size_of::<PhysicalExprRef>()
+ joiner.hashmap.size()
- size_of_val(&joiner.hashmap)
+ joiner.hashes_buffer.capacity() * size_of::<u64>()
+ joiner.visited_rows.allocation_size()
}
#[test]
fn one_side_hash_joiner_size_counts_descriptor_and_hash_set_allocation_once() {
let schema = Arc::new(Schema::empty());
let mut joiner = OneSideHashJoiner::new(JoinSide::Left, vec![], schema);
let empty_size = joiner.size();
assert_eq!(empty_size, expected_one_side_hash_joiner_size(&joiner));
assert_eq!(joiner.visited_rows.allocation_size(), 0);
joiner.visited_rows.extend(0..3);
let initial_capacity = joiner.visited_rows.capacity();
let initial_allocation = joiner.visited_rows.allocation_size();
assert!(initial_capacity > 0);
assert_eq!(joiner.size(), expected_one_side_hash_joiner_size(&joiner));
assert_eq!(joiner.size() - empty_size, initial_allocation);
joiner.visited_rows.extend(3..initial_capacity * 2);
let grown_allocation = joiner.visited_rows.allocation_size();
assert!(joiner.visited_rows.capacity() > initial_capacity);
assert_eq!(joiner.size(), expected_one_side_hash_joiner_size(&joiner));
assert_eq!(joiner.size() - empty_size, grown_allocation);
assert!(grown_allocation > initial_allocation);
let size_with_visited_rows = joiner.size();
let initial_hashmap_allocation =
joiner.hashmap.size() - size_of_val(&joiner.hashmap);
joiner.on = vec![Arc::new(Column::new("a", 0))];
joiner.hashmap = PruningJoinHashMap::with_capacity(3);
joiner.hashes_buffer.try_reserve(3).unwrap();
assert!(joiner.on.capacity() > 0);
assert!(joiner.hashmap.map.capacity() > 0);
assert!(joiner.hashes_buffer.capacity() > 0);
let owned_container_allocation_delta = joiner.on.capacity()
* size_of::<PhysicalExprRef>()
+ (joiner.hashmap.size()
- size_of_val(&joiner.hashmap)
- initial_hashmap_allocation)
+ joiner.hashes_buffer.capacity() * size_of::<u64>();
assert!(owned_container_allocation_delta > 0);
assert_eq!(joiner.size(), expected_one_side_hash_joiner_size(&joiner));
assert_eq!(
joiner.size() - size_with_visited_rows,
owned_container_allocation_delta
);
}
#[test]
fn stream_reserves_retained_interval_graph() -> Result<()> {
let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)]));
let mut stream = create_stream(NoopBatchTransformer::new(), Arc::clone(&schema));
stream.update_reservation()?;
let size_without_graph = stream.reservation.size();
let expr: PhysicalExprRef = Arc::new(Column::new("a", 0));
let predicate = binary(Arc::clone(&expr), Operator::Gt, lit(0_i32), &schema)?;
let graph = ExprIntervalGraph::try_new(predicate, &schema)?;
let graph_size = graph.size();
stream.graph = Some(graph);
stream.update_reservation()?;
assert_eq!(stream.reservation.size(), size_without_graph + graph_size);
assert_eq!(stream.reservation.size(), stream.size());
let graph = stream.graph.as_mut().unwrap();
let indices = graph.gather_node_indices(&[expr]);
let mut ranges = vec![(indices[0].1, Interval::make(Some(1_i32), Some(10_i32))?)];
graph.update_ranges(&mut ranges, Interval::TRUE)?;
let updated_graph_size = graph.size();
stream.update_reservation()?;
assert_eq!(
stream.reservation.size(),
size_without_graph + updated_graph_size
);
assert_eq!(stream.metrics.stream_memory_usage.value(), stream.size());
stream.graph = None;
stream.update_reservation()?;
assert_eq!(stream.reservation.size(), size_without_graph);
assert_eq!(
stream.metrics.stream_memory_usage.value(),
size_without_graph
);
Ok(())
}
fn assert_stream_accounts_for_transformer<T: BatchTransformer>(batch_transformer: T) {
let batch = RecordBatch::try_from_iter(vec![(
"a",
Arc::new(Int32Array::from_iter_values(0..10)) as _,
)])
.unwrap();
let expected_size = batch.get_array_memory_size();
let mut stream = create_stream(batch_transformer, batch.schema());
let empty_size = stream.size();
stream.batch_transformer.set_batch(batch.clone());
stream.update_reservation().unwrap();
assert_eq!(stream.size() - empty_size, expected_size);
assert_eq!(stream.reservation.size(), stream.size());
while stream.batch_transformer.next().is_some() {}
stream.update_reservation().unwrap();
assert_eq!(stream.reservation.size(), empty_size);
stream.left.input_buffer = batch;
let size_with_shared_batch = stream.size();
stream
.batch_transformer
.set_batch(stream.left.input_buffer.clone());
assert_eq!(stream.size(), size_with_shared_batch);
}
#[test]
fn stream_accounts_for_transformer_batches_once() {
assert_stream_accounts_for_transformer(NoopBatchTransformer::new());
assert_stream_accounts_for_transformer(BatchSplitter::new(3));
}
#[tokio::test]
async fn symmetric_hash_join_retains_reservation_until_dropped() -> Result<()> {
let pool = Arc::new(RecordingMemoryPool::default());
let runtime = RuntimeEnvBuilder::new()
.with_memory_pool(Arc::clone(&pool) as Arc<dyn MemoryPool>)
.build_arc()?;
let context = TaskContext::default().with_runtime(runtime);
let schema = Arc::new(Schema::empty());
let mut stream =
create_stream_with_context(NoopBatchTransformer::new(), schema, &context);
stream.update_reservation()?;
let reserved_size = stream.reservation.size();
assert_ne!(reserved_size, 0);
assert!(stream.next().await.is_none());
assert!(matches!(
stream.state(),
SHJStreamState::BothExhausted { final_result: true }
));
assert_eq!(stream.reservation.size(), reserved_size);
assert_eq!(stream.metrics.stream_memory_usage.value(), reserved_size);
drop(stream);
assert_eq!(pool.reserved(), 0);
Ok(())
}
fn assert_stream_deduplicates_nested_transformer_batch<T: BatchTransformer>(
batch_transformer: T,
) {
let shared_child: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3]));
let fields =
Fields::from(vec![Arc::new(Field::new("value", DataType::Int32, false))]);
let left_batch = RecordBatch::try_from_iter(vec![(
"nested",
Arc::new(StructArray::new(
fields.clone(),
vec![Arc::clone(&shared_child)],
None,
)) as ArrayRef,
)])
.unwrap();
let transformer_batch = RecordBatch::try_from_iter(vec![(
"nested",
Arc::new(StructArray::new(
fields,
vec![Arc::clone(&shared_child)],
None,
)) as ArrayRef,
)])
.unwrap();
let mut stream = create_stream(batch_transformer, left_batch.schema());
stream.left.input_buffer = left_batch;
let size_without_transformer = stream.size();
stream
.batch_transformer
.set_batch(transformer_batch.clone());
assert_eq!(
stream.size() - size_without_transformer,
transformer_batch.get_array_memory_size()
- shared_child.get_array_memory_size()
);
}
#[test]
fn stream_deduplicates_nested_transformer_batches() {
assert_stream_deduplicates_nested_transformer_batch(NoopBatchTransformer::new());
assert_stream_deduplicates_nested_transformer_batch(BatchSplitter::new(3));
}
fn assert_transformer_reservation_exhausts_pool<T: BatchTransformer>(
batch_transformer: T,
) -> Result<()> {
let batch = RecordBatch::try_from_iter(vec![(
"a",
Arc::new(Int32Array::from_iter_values(0..10)) as _,
)])?;
let empty_size =
create_stream(NoopBatchTransformer::new(), batch.schema()).size();
let runtime = RuntimeEnvBuilder::new()
.with_memory_limit(empty_size + batch.get_array_memory_size() - 1, 1.0)
.build_arc()?;
let context = TaskContext::default().with_runtime(runtime);
let mut stream =
create_stream_with_context(batch_transformer, batch.schema(), &context);
stream.update_reservation()?;
let reserved_size = stream.reservation.size();
stream.batch_transformer.set_batch(batch);
let error = stream.update_reservation().unwrap_err();
assert!(
matches!(error.find_root(), DataFusionError::ResourcesExhausted(_)),
"expected a memory-pool error, got: {error}"
);
assert_eq!(stream.metrics.stream_memory_usage.value(), reserved_size);
Ok(())
}
#[test]
fn transformer_reservation_exhausts_pool() -> Result<()> {
assert_transformer_reservation_exhausts_pool(NoopBatchTransformer::new())?;
assert_transformer_reservation_exhausts_pool(BatchSplitter::new(3))?;
Ok(())
}
#[derive(Debug, Default)]
struct RecordingMemoryPool {
inner: UnboundedMemoryPool,
symmetric_join_changes: Mutex<Vec<isize>>,
}
impl fmt::Display for RecordingMemoryPool {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.inner, f)
}
}
impl RecordingMemoryPool {
fn record(&self, reservation: &MemoryReservation, change: isize) {
if reservation
.consumer()
.name()
.starts_with("SymmetricHashJoinStream")
{
self.symmetric_join_changes
.lock()
.expect("recording pool mutex is not poisoned")
.push(change);
}
}
fn change_deltas(&self) -> Vec<isize> {
self.symmetric_join_changes
.lock()
.expect("recording pool mutex is not poisoned")
.clone()
}
}
impl MemoryPool for RecordingMemoryPool {
fn name(&self) -> &str {
self.inner.name()
}
fn grow(&self, reservation: &MemoryReservation, additional: usize) {
self.inner.grow(reservation, additional);
self.record(reservation, additional as isize);
}
fn shrink(&self, reservation: &MemoryReservation, shrink: usize) {
self.inner.shrink(reservation, shrink);
self.record(reservation, -(shrink as isize));
}
fn try_grow(
&self,
reservation: &MemoryReservation,
additional: usize,
) -> Result<()> {
self.inner.try_grow(reservation, additional)?;
self.record(reservation, additional as isize);
Ok(())
}
fn reserved(&self) -> usize {
self.inner.reserved()
}
fn memory_limit(&self) -> MemoryLimit {
self.inner.memory_limit()
}
}
fn transformer_lifecycle_test_join() -> Result<SymmetricHashJoinExec> {
let schema =
Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)]));
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![Arc::new(Int32Array::from_iter_values(0..10))],
)?;
let left = TestMemoryExec::try_new_exec(
&[vec![batch.clone()]],
Arc::clone(&schema),
None,
)?;
let right =
TestMemoryExec::try_new_exec(&[vec![batch]], Arc::clone(&schema), None)?;
let on = vec![(col("id", &schema)?, col("id", &schema)?)];
SymmetricHashJoinExec::try_new(
left,
right,
on,
None,
&JoinType::Inner,
NullEquality::NullEqualsNothing,
None,
None,
StreamJoinPartitionMode::Partitioned,
)
}
fn transformer_lifecycle_test_context(
runtime: Arc<RuntimeEnv>,
enforce_batch_size_in_joins: bool,
) -> Arc<TaskContext> {
Arc::new(
TaskContext::default()
.with_session_config(
SessionConfig::new()
.with_batch_size(3)
.with_enforce_batch_size_in_joins(enforce_batch_size_in_joins),
)
.with_runtime(runtime),
)
}
#[rstest]
#[tokio::test]
async fn symmetric_hash_join_updates_reservation_while_transforming_output(
#[values(false, true)] enforce_batch_size_in_joins: bool,
) -> Result<()> {
let pool = Arc::new(RecordingMemoryPool::default());
let runtime = RuntimeEnvBuilder::new()
.with_memory_pool(Arc::clone(&pool) as Arc<dyn MemoryPool>)
.build_arc()?;
let mut stream = transformer_lifecycle_test_join()?.execute(
0,
transformer_lifecycle_test_context(runtime, enforce_batch_size_in_joins),
)?;
let first_batch = stream.next().await.transpose()?.unwrap();
let retained_batch_size = first_batch.get_array_memory_size() as isize;
let changes_after_first_batch = pool.change_deltas();
assert!(
changes_after_first_batch.contains(&retained_batch_size),
"expected transformer retain reservation update: {changes_after_first_batch:?}"
);
if enforce_batch_size_in_joins {
assert!(
!changes_after_first_batch.contains(&-retained_batch_size),
"splitter must retain the output batch after a non-final slice: {changes_after_first_batch:?}"
);
} else {
assert!(
changes_after_first_batch
.windows(2)
.any(|changes| changes == [retained_batch_size, -retained_batch_size]),
"expected Noop transformer release after emission: {changes_after_first_batch:?}"
);
}
let remaining_batches = crate::common::collect(stream).await?;
let changes_after_completion = pool.change_deltas();
if enforce_batch_size_in_joins {
assert!(
changes_after_completion.contains(&-retained_batch_size),
"expected splitter release after final slice: {changes_after_completion:?}"
);
}
let output_rows = first_batch.num_rows()
+ remaining_batches
.iter()
.map(RecordBatch::num_rows)
.sum::<usize>();
assert_eq!(output_rows, 10);
Ok(())
}
#[rstest]
#[tokio::test]
async fn symmetric_hash_join_transformer_retention_exhausts_bounded_pool(
#[values(false, true)] enforce_batch_size_in_joins: bool,
) -> Result<()> {
let calibration_pool = Arc::new(RecordingMemoryPool::default());
let calibration_runtime = RuntimeEnvBuilder::new()
.with_memory_pool(Arc::clone(&calibration_pool) as Arc<dyn MemoryPool>)
.build_arc()?;
let mut calibration_stream = transformer_lifecycle_test_join()?.execute(
0,
transformer_lifecycle_test_context(
calibration_runtime,
enforce_batch_size_in_joins,
),
)?;
let first_batch = calibration_stream.next().await.transpose()?.unwrap();
let retained_size = first_batch.get_array_memory_size() as isize;
let changes = calibration_pool.change_deltas();
let retain_index = changes
.len()
.checked_sub(if enforce_batch_size_in_joins { 1 } else { 2 })
.expect("transformer retain must update the stream reservation");
assert_eq!(
changes[retain_index], retained_size,
"expected transformer retain reservation update: {changes:?}"
);
if !enforce_batch_size_in_joins {
assert_eq!(
changes.last(),
Some(&-retained_size),
"Noop must release the retained batch before emitting it: {changes:?}"
);
}
let pre_retain_size: isize = changes[..retain_index].iter().sum();
assert!(
pre_retain_size > 0,
"expected a positive reservation before retention: {changes:?}"
);
let runtime = RuntimeEnvBuilder::new()
.with_memory_limit((pre_retain_size + retained_size) as usize - 1, 1.0)
.build_arc()?;
let mut stream = transformer_lifecycle_test_join()?.execute(
0,
transformer_lifecycle_test_context(runtime, enforce_batch_size_in_joins),
)?;
let error = stream.next().await.transpose().unwrap_err();
assert!(
matches!(error.find_root(), DataFusionError::ResourcesExhausted(_)),
"expected transformer retention to exhaust the pool, got: {error}"
);
Ok(())
}
fn get_or_create_table(
cardinality: (i32, i32),
batch_size: usize,
) -> Result<TableValue> {
{
let cache = TABLE_CACHE.lock().unwrap();
if let Some(table) = cache.get(&(cardinality.0, cardinality.1, batch_size)) {
return Ok(table.clone());
}
}
let (left_batch, right_batch) =
build_sides_record_batches(TABLE_SIZE, cardinality)?;
let (left_partition, right_partition) = (
split_record_batches(&left_batch, batch_size)?,
split_record_batches(&right_batch, batch_size)?,
);
let mut cache = TABLE_CACHE.lock().unwrap();
cache.insert(
(cardinality.0, cardinality.1, batch_size),
(left_partition.clone(), right_partition.clone()),
);
Ok((left_partition, right_partition))
}
pub async fn experiment(
left: Arc<dyn ExecutionPlan>,
right: Arc<dyn ExecutionPlan>,
filter: Option<JoinFilter>,
join_type: JoinType,
on: JoinOn,
task_ctx: Arc<TaskContext>,
) -> Result<()> {
let first_batches = partitioned_sym_join_with_filter(
Arc::clone(&left),
Arc::clone(&right),
on.clone(),
filter.clone(),
&join_type,
NullEquality::NullEqualsNothing,
Arc::clone(&task_ctx),
)
.await?;
let second_batches = partitioned_hash_join_with_filter(
left,
right,
on,
filter,
&join_type,
NullEquality::NullEqualsNothing,
task_ctx,
)
.await?;
compare_batches(&first_batches, &second_batches);
Ok(())
}
#[rstest]
#[tokio::test(flavor = "multi_thread")]
async fn complex_join_all_one_ascending_numeric(
#[values(
JoinType::Inner,
JoinType::Left,
JoinType::Right,
JoinType::RightSemi,
JoinType::LeftSemi,
JoinType::LeftAnti,
JoinType::LeftMark,
JoinType::RightAnti,
JoinType::RightMark,
JoinType::Full
)]
join_type: JoinType,
#[values(
(4, 5),
(12, 17),
)]
cardinality: (i32, i32),
) -> Result<()> {
let task_ctx = Arc::new(TaskContext::default());
let (left_partition, right_partition) = get_or_create_table(cardinality, 8)?;
let left_schema = &left_partition[0].schema();
let right_schema = &right_partition[0].schema();
let left_sorted = [PhysicalSortExpr {
expr: binary(
col("la1", left_schema)?,
Operator::Plus,
col("la2", left_schema)?,
left_schema,
)?,
options: SortOptions::default(),
}]
.into();
let right_sorted = [PhysicalSortExpr {
expr: col("ra1", right_schema)?,
options: SortOptions::default(),
}]
.into();
let (left, right) = create_memory_table(
left_partition,
right_partition,
vec![left_sorted],
vec![right_sorted],
)?;
let on = vec![(
binary(
col("lc1", left_schema)?,
Operator::Plus,
lit(ScalarValue::Int32(Some(1))),
left_schema,
)?,
Arc::new(Column::new_with_schema("rc1", right_schema)?) as _,
)];
let intermediate_schema = Schema::new(vec![
Field::new("0", DataType::Int32, true),
Field::new("1", DataType::Int32, true),
Field::new("2", DataType::Int32, true),
]);
let filter_expr = complicated_filter(&intermediate_schema)?;
let column_indices = vec![
ColumnIndex {
index: left_schema.index_of("la1")?,
side: JoinSide::Left,
},
ColumnIndex {
index: left_schema.index_of("la2")?,
side: JoinSide::Left,
},
ColumnIndex {
index: right_schema.index_of("ra1")?,
side: JoinSide::Right,
},
];
let filter =
JoinFilter::new(filter_expr, column_indices, Arc::new(intermediate_schema));
experiment(left, right, Some(filter), join_type, on, task_ctx).await?;
Ok(())
}
#[rstest]
#[tokio::test(flavor = "multi_thread")]
async fn join_all_one_ascending_numeric(
#[values(
JoinType::Inner,
JoinType::Left,
JoinType::Right,
JoinType::RightSemi,
JoinType::LeftSemi,
JoinType::LeftAnti,
JoinType::LeftMark,
JoinType::RightAnti,
JoinType::RightMark,
JoinType::Full
)]
join_type: JoinType,
#[values(0, 1, 2, 3, 4, 5)] case_expr: usize,
) -> Result<()> {
let task_ctx = Arc::new(TaskContext::default());
let (left_partition, right_partition) = get_or_create_table((4, 5), 8)?;
let left_schema = &left_partition[0].schema();
let right_schema = &right_partition[0].schema();
let left_sorted = [PhysicalSortExpr {
expr: col("la1", left_schema)?,
options: SortOptions::default(),
}]
.into();
let right_sorted = [PhysicalSortExpr {
expr: col("ra1", right_schema)?,
options: SortOptions::default(),
}]
.into();
let (left, right) = create_memory_table(
left_partition,
right_partition,
vec![left_sorted],
vec![right_sorted],
)?;
let on = vec![(col("lc1", left_schema)?, col("rc1", right_schema)?)];
let intermediate_schema = Schema::new(vec![
Field::new("left", DataType::Int32, true),
Field::new("right", DataType::Int32, true),
]);
let filter_expr = join_expr_tests_fixture_i32(
case_expr,
col("left", &intermediate_schema)?,
col("right", &intermediate_schema)?,
);
let column_indices = vec![
ColumnIndex {
index: 0,
side: JoinSide::Left,
},
ColumnIndex {
index: 0,
side: JoinSide::Right,
},
];
let filter =
JoinFilter::new(filter_expr, column_indices, Arc::new(intermediate_schema));
experiment(left, right, Some(filter), join_type, on, task_ctx).await?;
Ok(())
}
#[rstest]
#[tokio::test(flavor = "multi_thread")]
async fn join_without_sort_information(
#[values(
JoinType::Inner,
JoinType::Left,
JoinType::Right,
JoinType::RightSemi,
JoinType::LeftSemi,
JoinType::LeftAnti,
JoinType::LeftMark,
JoinType::RightAnti,
JoinType::RightMark,
JoinType::Full
)]
join_type: JoinType,
#[values(0, 1, 2, 3, 4, 5)] case_expr: usize,
) -> Result<()> {
let task_ctx = Arc::new(TaskContext::default());
let (left_partition, right_partition) = get_or_create_table((4, 5), 8)?;
let left_schema = &left_partition[0].schema();
let right_schema = &right_partition[0].schema();
let (left, right) =
create_memory_table(left_partition, right_partition, vec![], vec![])?;
let on = vec![(col("lc1", left_schema)?, col("rc1", right_schema)?)];
let intermediate_schema = Schema::new(vec![
Field::new("left", DataType::Int32, true),
Field::new("right", DataType::Int32, true),
]);
let filter_expr = join_expr_tests_fixture_i32(
case_expr,
col("left", &intermediate_schema)?,
col("right", &intermediate_schema)?,
);
let column_indices = vec![
ColumnIndex {
index: 5,
side: JoinSide::Left,
},
ColumnIndex {
index: 5,
side: JoinSide::Right,
},
];
let filter =
JoinFilter::new(filter_expr, column_indices, Arc::new(intermediate_schema));
experiment(left, right, Some(filter), join_type, on, task_ctx).await?;
Ok(())
}
#[rstest]
#[tokio::test(flavor = "multi_thread")]
async fn join_without_filter(
#[values(
JoinType::Inner,
JoinType::Left,
JoinType::Right,
JoinType::RightSemi,
JoinType::LeftSemi,
JoinType::LeftAnti,
JoinType::LeftMark,
JoinType::RightAnti,
JoinType::RightMark,
JoinType::Full
)]
join_type: JoinType,
) -> Result<()> {
let task_ctx = Arc::new(TaskContext::default());
let (left_partition, right_partition) = get_or_create_table((11, 21), 8)?;
let left_schema = &left_partition[0].schema();
let right_schema = &right_partition[0].schema();
let (left, right) =
create_memory_table(left_partition, right_partition, vec![], vec![])?;
let on = vec![(col("lc1", left_schema)?, col("rc1", right_schema)?)];
experiment(left, right, None, join_type, on, task_ctx).await?;
Ok(())
}
#[rstest]
#[tokio::test(flavor = "multi_thread")]
async fn join_all_one_descending_numeric_particular(
#[values(
JoinType::Inner,
JoinType::Left,
JoinType::Right,
JoinType::RightSemi,
JoinType::LeftSemi,
JoinType::LeftAnti,
JoinType::LeftMark,
JoinType::RightAnti,
JoinType::RightMark,
JoinType::Full
)]
join_type: JoinType,
#[values(0, 1, 2, 3, 4, 5)] case_expr: usize,
) -> Result<()> {
let task_ctx = Arc::new(TaskContext::default());
let (left_partition, right_partition) = get_or_create_table((11, 21), 8)?;
let left_schema = &left_partition[0].schema();
let right_schema = &right_partition[0].schema();
let left_sorted = [PhysicalSortExpr {
expr: col("la1_des", left_schema)?,
options: SortOptions {
descending: true,
nulls_first: true,
},
}]
.into();
let right_sorted = [PhysicalSortExpr {
expr: col("ra1_des", right_schema)?,
options: SortOptions {
descending: true,
nulls_first: true,
},
}]
.into();
let (left, right) = create_memory_table(
left_partition,
right_partition,
vec![left_sorted],
vec![right_sorted],
)?;
let on = vec![(col("lc1", left_schema)?, col("rc1", right_schema)?)];
let intermediate_schema = Schema::new(vec![
Field::new("left", DataType::Int32, true),
Field::new("right", DataType::Int32, true),
]);
let filter_expr = join_expr_tests_fixture_i32(
case_expr,
col("left", &intermediate_schema)?,
col("right", &intermediate_schema)?,
);
let column_indices = vec![
ColumnIndex {
index: 5,
side: JoinSide::Left,
},
ColumnIndex {
index: 5,
side: JoinSide::Right,
},
];
let filter =
JoinFilter::new(filter_expr, column_indices, Arc::new(intermediate_schema));
experiment(left, right, Some(filter), join_type, on, task_ctx).await?;
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
async fn build_null_columns_first() -> Result<()> {
let join_type = JoinType::Full;
let case_expr = 1;
let session_config = SessionConfig::new().with_repartition_joins(false);
let task_ctx = TaskContext::default().with_session_config(session_config);
let task_ctx = Arc::new(task_ctx);
let (left_partition, right_partition) = get_or_create_table((10, 11), 8)?;
let left_schema = &left_partition[0].schema();
let right_schema = &right_partition[0].schema();
let left_sorted = [PhysicalSortExpr {
expr: col("l_asc_null_first", left_schema)?,
options: SortOptions {
descending: false,
nulls_first: true,
},
}]
.into();
let right_sorted = [PhysicalSortExpr {
expr: col("r_asc_null_first", right_schema)?,
options: SortOptions {
descending: false,
nulls_first: true,
},
}]
.into();
let (left, right) = create_memory_table(
left_partition,
right_partition,
vec![left_sorted],
vec![right_sorted],
)?;
let on = vec![(col("lc1", left_schema)?, col("rc1", right_schema)?)];
let intermediate_schema = Schema::new(vec![
Field::new("left", DataType::Int32, true),
Field::new("right", DataType::Int32, true),
]);
let filter_expr = join_expr_tests_fixture_i32(
case_expr,
col("left", &intermediate_schema)?,
col("right", &intermediate_schema)?,
);
let column_indices = vec![
ColumnIndex {
index: 6,
side: JoinSide::Left,
},
ColumnIndex {
index: 6,
side: JoinSide::Right,
},
];
let filter =
JoinFilter::new(filter_expr, column_indices, Arc::new(intermediate_schema));
experiment(left, right, Some(filter), join_type, on, task_ctx).await?;
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
async fn build_null_columns_last() -> Result<()> {
let join_type = JoinType::Full;
let case_expr = 1;
let session_config = SessionConfig::new().with_repartition_joins(false);
let task_ctx = TaskContext::default().with_session_config(session_config);
let task_ctx = Arc::new(task_ctx);
let (left_partition, right_partition) = get_or_create_table((10, 11), 8)?;
let left_schema = &left_partition[0].schema();
let right_schema = &right_partition[0].schema();
let left_sorted = [PhysicalSortExpr {
expr: col("l_asc_null_last", left_schema)?,
options: SortOptions {
descending: false,
nulls_first: false,
},
}]
.into();
let right_sorted = [PhysicalSortExpr {
expr: col("r_asc_null_last", right_schema)?,
options: SortOptions {
descending: false,
nulls_first: false,
},
}]
.into();
let (left, right) = create_memory_table(
left_partition,
right_partition,
vec![left_sorted],
vec![right_sorted],
)?;
let on = vec![(col("lc1", left_schema)?, col("rc1", right_schema)?)];
let intermediate_schema = Schema::new(vec![
Field::new("left", DataType::Int32, true),
Field::new("right", DataType::Int32, true),
]);
let filter_expr = join_expr_tests_fixture_i32(
case_expr,
col("left", &intermediate_schema)?,
col("right", &intermediate_schema)?,
);
let column_indices = vec![
ColumnIndex {
index: 7,
side: JoinSide::Left,
},
ColumnIndex {
index: 7,
side: JoinSide::Right,
},
];
let filter =
JoinFilter::new(filter_expr, column_indices, Arc::new(intermediate_schema));
experiment(left, right, Some(filter), join_type, on, task_ctx).await?;
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
async fn build_null_columns_first_descending() -> Result<()> {
let join_type = JoinType::Full;
let cardinality = (10, 11);
let case_expr = 1;
let session_config = SessionConfig::new().with_repartition_joins(false);
let task_ctx = TaskContext::default().with_session_config(session_config);
let task_ctx = Arc::new(task_ctx);
let (left_partition, right_partition) = get_or_create_table(cardinality, 8)?;
let left_schema = &left_partition[0].schema();
let right_schema = &right_partition[0].schema();
let left_sorted = [PhysicalSortExpr {
expr: col("l_desc_null_first", left_schema)?,
options: SortOptions {
descending: true,
nulls_first: true,
},
}]
.into();
let right_sorted = [PhysicalSortExpr {
expr: col("r_desc_null_first", right_schema)?,
options: SortOptions {
descending: true,
nulls_first: true,
},
}]
.into();
let (left, right) = create_memory_table(
left_partition,
right_partition,
vec![left_sorted],
vec![right_sorted],
)?;
let on = vec![(col("lc1", left_schema)?, col("rc1", right_schema)?)];
let intermediate_schema = Schema::new(vec![
Field::new("left", DataType::Int32, true),
Field::new("right", DataType::Int32, true),
]);
let filter_expr = join_expr_tests_fixture_i32(
case_expr,
col("left", &intermediate_schema)?,
col("right", &intermediate_schema)?,
);
let column_indices = vec![
ColumnIndex {
index: 8,
side: JoinSide::Left,
},
ColumnIndex {
index: 8,
side: JoinSide::Right,
},
];
let filter =
JoinFilter::new(filter_expr, column_indices, Arc::new(intermediate_schema));
experiment(left, right, Some(filter), join_type, on, task_ctx).await?;
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
async fn complex_join_all_one_ascending_numeric_missing_stat() -> Result<()> {
let cardinality = (3, 4);
let join_type = JoinType::Full;
let session_config = SessionConfig::new().with_repartition_joins(false);
let task_ctx = TaskContext::default().with_session_config(session_config);
let task_ctx = Arc::new(task_ctx);
let (left_partition, right_partition) = get_or_create_table(cardinality, 8)?;
let left_schema = &left_partition[0].schema();
let right_schema = &right_partition[0].schema();
let left_sorted = [PhysicalSortExpr {
expr: col("la1", left_schema)?,
options: SortOptions::default(),
}]
.into();
let right_sorted = [PhysicalSortExpr {
expr: col("ra1", right_schema)?,
options: SortOptions::default(),
}]
.into();
let (left, right) = create_memory_table(
left_partition,
right_partition,
vec![left_sorted],
vec![right_sorted],
)?;
let on = vec![(col("lc1", left_schema)?, col("rc1", right_schema)?)];
let intermediate_schema = Schema::new(vec![
Field::new("0", DataType::Int32, true),
Field::new("1", DataType::Int32, true),
Field::new("2", DataType::Int32, true),
]);
let filter_expr = complicated_filter(&intermediate_schema)?;
let column_indices = vec![
ColumnIndex {
index: 0,
side: JoinSide::Left,
},
ColumnIndex {
index: 4,
side: JoinSide::Left,
},
ColumnIndex {
index: 0,
side: JoinSide::Right,
},
];
let filter =
JoinFilter::new(filter_expr, column_indices, Arc::new(intermediate_schema));
experiment(left, right, Some(filter), join_type, on, task_ctx).await?;
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
async fn complex_join_all_one_ascending_equivalence() -> Result<()> {
let cardinality = (3, 4);
let join_type = JoinType::Full;
let config = SessionConfig::new().with_repartition_joins(false);
let task_ctx = Arc::new(TaskContext::default().with_session_config(config));
let (left_partition, right_partition) = get_or_create_table(cardinality, 8)?;
let left_schema = &left_partition[0].schema();
let right_schema = &right_partition[0].schema();
let left_sorted = vec![
[PhysicalSortExpr {
expr: col("la1", left_schema)?,
options: SortOptions::default(),
}]
.into(),
[PhysicalSortExpr {
expr: col("la2", left_schema)?,
options: SortOptions::default(),
}]
.into(),
];
let right_sorted = [PhysicalSortExpr {
expr: col("ra1", right_schema)?,
options: SortOptions::default(),
}]
.into();
let (left, right) = create_memory_table(
left_partition,
right_partition,
left_sorted,
vec![right_sorted],
)?;
let on = vec![(col("lc1", left_schema)?, col("rc1", right_schema)?)];
let intermediate_schema = Schema::new(vec![
Field::new("0", DataType::Int32, true),
Field::new("1", DataType::Int32, true),
Field::new("2", DataType::Int32, true),
]);
let filter_expr = complicated_filter(&intermediate_schema)?;
let column_indices = vec![
ColumnIndex {
index: 0,
side: JoinSide::Left,
},
ColumnIndex {
index: 4,
side: JoinSide::Left,
},
ColumnIndex {
index: 0,
side: JoinSide::Right,
},
];
let filter =
JoinFilter::new(filter_expr, column_indices, Arc::new(intermediate_schema));
experiment(left, right, Some(filter), join_type, on, task_ctx).await?;
Ok(())
}
#[rstest]
#[tokio::test(flavor = "multi_thread")]
async fn testing_with_temporal_columns(
#[values(
JoinType::Inner,
JoinType::Left,
JoinType::Right,
JoinType::RightSemi,
JoinType::LeftSemi,
JoinType::LeftAnti,
JoinType::LeftMark,
JoinType::RightAnti,
JoinType::RightMark,
JoinType::Full
)]
join_type: JoinType,
#[values(
(4, 5),
(12, 17),
)]
cardinality: (i32, i32),
#[values(0, 1, 2)] case_expr: usize,
) -> Result<()> {
let session_config = SessionConfig::new().with_repartition_joins(false);
let task_ctx = TaskContext::default().with_session_config(session_config);
let task_ctx = Arc::new(task_ctx);
let (left_partition, right_partition) = get_or_create_table(cardinality, 8)?;
let left_schema = &left_partition[0].schema();
let right_schema = &right_partition[0].schema();
let on = vec![(col("lc1", left_schema)?, col("rc1", right_schema)?)];
let left_sorted = [PhysicalSortExpr {
expr: col("lt1", left_schema)?,
options: SortOptions {
descending: false,
nulls_first: true,
},
}]
.into();
let right_sorted = [PhysicalSortExpr {
expr: col("rt1", right_schema)?,
options: SortOptions {
descending: false,
nulls_first: true,
},
}]
.into();
let (left, right) = create_memory_table(
left_partition,
right_partition,
vec![left_sorted],
vec![right_sorted],
)?;
let intermediate_schema = Schema::new(vec![
Field::new(
"left",
DataType::Timestamp(TimeUnit::Millisecond, None),
false,
),
Field::new(
"right",
DataType::Timestamp(TimeUnit::Millisecond, None),
false,
),
]);
let filter_expr = join_expr_tests_fixture_temporal(
case_expr,
col("left", &intermediate_schema)?,
col("right", &intermediate_schema)?,
&intermediate_schema,
)?;
let column_indices = vec![
ColumnIndex {
index: 3,
side: JoinSide::Left,
},
ColumnIndex {
index: 3,
side: JoinSide::Right,
},
];
let filter =
JoinFilter::new(filter_expr, column_indices, Arc::new(intermediate_schema));
experiment(left, right, Some(filter), join_type, on, task_ctx).await?;
Ok(())
}
#[rstest]
#[tokio::test(flavor = "multi_thread")]
async fn test_with_interval_columns(
#[values(
JoinType::Inner,
JoinType::Left,
JoinType::Right,
JoinType::RightSemi,
JoinType::LeftSemi,
JoinType::LeftAnti,
JoinType::LeftMark,
JoinType::RightAnti,
JoinType::RightMark,
JoinType::Full
)]
join_type: JoinType,
#[values(
(4, 5),
(12, 17),
)]
cardinality: (i32, i32),
) -> Result<()> {
let session_config = SessionConfig::new().with_repartition_joins(false);
let task_ctx = TaskContext::default().with_session_config(session_config);
let task_ctx = Arc::new(task_ctx);
let (left_partition, right_partition) = get_or_create_table(cardinality, 8)?;
let left_schema = &left_partition[0].schema();
let right_schema = &right_partition[0].schema();
let on = vec![(col("lc1", left_schema)?, col("rc1", right_schema)?)];
let left_sorted = [PhysicalSortExpr {
expr: col("li1", left_schema)?,
options: SortOptions {
descending: false,
nulls_first: true,
},
}]
.into();
let right_sorted = [PhysicalSortExpr {
expr: col("ri1", right_schema)?,
options: SortOptions {
descending: false,
nulls_first: true,
},
}]
.into();
let (left, right) = create_memory_table(
left_partition,
right_partition,
vec![left_sorted],
vec![right_sorted],
)?;
let intermediate_schema = Schema::new(vec![
Field::new("left", DataType::Interval(IntervalUnit::DayTime), false),
Field::new("right", DataType::Interval(IntervalUnit::DayTime), false),
]);
let filter_expr = join_expr_tests_fixture_temporal(
0,
col("left", &intermediate_schema)?,
col("right", &intermediate_schema)?,
&intermediate_schema,
)?;
let column_indices = vec![
ColumnIndex {
index: 9,
side: JoinSide::Left,
},
ColumnIndex {
index: 9,
side: JoinSide::Right,
},
];
let filter =
JoinFilter::new(filter_expr, column_indices, Arc::new(intermediate_schema));
experiment(left, right, Some(filter), join_type, on, task_ctx).await?;
Ok(())
}
#[rstest]
#[tokio::test(flavor = "multi_thread")]
async fn testing_ascending_float_pruning(
#[values(
JoinType::Inner,
JoinType::Left,
JoinType::Right,
JoinType::RightSemi,
JoinType::LeftSemi,
JoinType::LeftAnti,
JoinType::LeftMark,
JoinType::RightAnti,
JoinType::RightMark,
JoinType::Full
)]
join_type: JoinType,
#[values(
(4, 5),
(12, 17),
)]
cardinality: (i32, i32),
#[values(0, 1, 2, 3, 4, 5)] case_expr: usize,
) -> Result<()> {
let session_config = SessionConfig::new().with_repartition_joins(false);
let task_ctx = TaskContext::default().with_session_config(session_config);
let task_ctx = Arc::new(task_ctx);
let (left_partition, right_partition) = get_or_create_table(cardinality, 8)?;
let left_schema = &left_partition[0].schema();
let right_schema = &right_partition[0].schema();
let left_sorted = [PhysicalSortExpr {
expr: col("l_float", left_schema)?,
options: SortOptions::default(),
}]
.into();
let right_sorted = [PhysicalSortExpr {
expr: col("r_float", right_schema)?,
options: SortOptions::default(),
}]
.into();
let (left, right) = create_memory_table(
left_partition,
right_partition,
vec![left_sorted],
vec![right_sorted],
)?;
let on = vec![(col("lc1", left_schema)?, col("rc1", right_schema)?)];
let intermediate_schema = Schema::new(vec![
Field::new("left", DataType::Float64, true),
Field::new("right", DataType::Float64, true),
]);
let filter_expr = join_expr_tests_fixture_f64(
case_expr,
col("left", &intermediate_schema)?,
col("right", &intermediate_schema)?,
);
let column_indices = vec![
ColumnIndex {
index: 10, side: JoinSide::Left,
},
ColumnIndex {
index: 10, side: JoinSide::Right,
},
];
let filter =
JoinFilter::new(filter_expr, column_indices, Arc::new(intermediate_schema));
experiment(left, right, Some(filter), join_type, on, task_ctx).await?;
Ok(())
}
}