use std::collections::HashMap;
use std::fmt;
use std::mem::size_of;
use std::sync::{Arc, OnceLock};
use std::vec;
use crate::execution_plan::{
EmissionType, boundedness_from_children, has_same_children_properties,
plan_contains_expression_id, stub_properties,
};
use crate::filter_pushdown::{
ChildFilterDescription, ChildPushdownResult, FilterDescription, FilterPushdownPhase,
FilterPushdownPropagation, PushedDownPredicate,
};
use crate::joins::Map;
use crate::joins::array_map::ArrayMap;
use crate::joins::hash_join::inlist_builder::build_struct_inlist_values;
use crate::joins::hash_join::not_in::{NotIn, NotInBuild};
use crate::joins::hash_join::shared_bounds::{
ColumnBounds, PartitionBounds, PushdownStrategy, SharedBuildAccumulator,
};
use crate::joins::hash_join::stream::{
BuildSide, BuildSideInitialState, HashJoinStream, HashJoinStreamState,
};
use crate::joins::join_hash_map::{JoinHashMapU32, JoinHashMapU64};
use crate::joins::key_range_bitmap::KeyRangeBitmap;
use crate::joins::probe_completion::{Completion, ProbeCompletion};
use crate::joins::utils::{
OnceAsync, OnceFut, asymmetric_join_output_partitioning, emits_unmatched_left_rows,
is_existence_join, reorder_output_after_swap, swap_join_projection, update_hash,
};
use crate::joins::{JoinOn, JoinOnRef, PartitionMode, SharedBitmapBuilder};
use crate::metrics::{Count, MetricBuilder, MetricCategory};
use crate::projection::{
EmbeddedProjection, JoinData, ProjectionExec, try_embed_projection,
try_pushdown_through_join_with_column_indices,
};
use crate::repartition::REPARTITION_RANDOM_STATE;
use crate::statistics::{ChildStats, StatisticsArgs, with_per_partition_fetch};
use crate::{
ChildrenPropertiesMode, ExecutionPlanProperties, ReplaceChildrenOptions,
validate_child_count,
};
use crate::{
DisplayAs, DisplayFormatType, Distribution, ExecutionPlan,
InputDistributionRequirements, Partitioning, PlanProperties,
SendableRecordBatchStream, Statistics,
common::can_project,
joins::utils::{
BuildProbeJoinMetrics, ColumnIndex, JoinFilter, JoinHashMapType,
build_join_schema, check_join_is_valid, estimate_join_statistics,
need_produce_result_in_final, symmetric_join_output_partitioning,
},
metrics::{ExecutionPlanMetricsSet, MetricsSet},
};
use arrow::array::{Array, ArrayRef, BooleanBufferBuilder};
use arrow::compute::concat_batches;
use arrow::datatypes::SchemaRef;
use arrow::record_batch::RecordBatch;
use arrow::util::bit_util;
use arrow_schema::{DataType, Schema};
use datafusion_common::config::ConfigOptions;
use datafusion_common::float_semantics::normalize_floats;
use datafusion_common::stats::Precision;
use datafusion_common::tree_node::{Transformed, TreeNode, TreeNodeRecursion};
use datafusion_common::utils::memory::{
RecordBatchMemoryCounter, estimate_memory_size, get_record_batch_memory_size,
};
use datafusion_common::{
JoinSide, JoinType, NullEquality, Result, assert_or_internal_err, internal_err,
plan_err, project_schema,
};
use datafusion_execution::TaskContext;
use datafusion_execution::memory_pool::{MemoryConsumer, MemoryReservation};
use datafusion_expr::Accumulator;
use datafusion_functions_aggregate_common::min_max::{MaxAccumulator, MinAccumulator};
use datafusion_physical_expr::equivalence::{
ProjectionMapping, join_equivalence_properties,
};
use datafusion_physical_expr::expressions::{Column, DynamicFilterPhysicalExpr, lit};
use datafusion_physical_expr::projection::{ProjectionRef, combine_projections};
use datafusion_physical_expr::{PhysicalExpr, PhysicalExprRef};
use datafusion_common::hash_utils::RandomState;
use datafusion_physical_expr_common::physical_expr::fmt_sql;
use datafusion_physical_expr_common::utils::evaluate_expressions_to_arrays;
use futures::TryStreamExt;
use parking_lot::Mutex;
use super::partitioned_hash_eval::SeededRandomState;
mod prepared;
pub use prepared::PreparedHashJoinBuild;
pub(crate) const HASH_JOIN_SEED: SeededRandomState =
SeededRandomState::with_seed(12210250226015887276);
const ARRAY_MAP_CREATED_COUNT_METRIC_NAME: &str = "array_map_created_count";
#[expect(clippy::too_many_arguments)]
fn array_map_key_range(
bounds: Option<&PartitionBounds>,
schema: &SchemaRef,
batches: &[RecordBatch],
on_left: &[PhysicalExprRef],
reservation: &mut MemoryReservation,
perfect_hash_join_small_build_threshold: usize,
perfect_hash_join_min_key_density: f64,
null_equality: NullEquality,
) -> Result<Option<(u64, u64)>> {
if !is_perfect_hash_join_candidate(on_left, schema)? {
return Ok(None);
}
if null_equality == NullEquality::NullEqualsNull {
for batch in batches.iter() {
let arrays = evaluate_expressions_to_arrays(on_left, batch)?;
if arrays[0].null_count() > 0 {
return Ok(None);
}
}
}
let (min_val, max_val) = if let Some(bounds) = bounds {
let (min_val, max_val) = if let Some(cb) = bounds.get_column_bounds(0) {
(cb.min.clone(), cb.max.clone())
} else {
return Ok(None);
};
if min_val.is_null() || max_val.is_null() {
return Ok(None);
}
if min_val > max_val {
return internal_err!("min_val>max_val");
}
if let Some((mi, ma)) =
ArrayMap::key_to_u64(&min_val).zip(ArrayMap::key_to_u64(&max_val))
{
(mi, ma)
} else {
return Ok(None);
}
} else {
return Ok(None);
};
let range = ArrayMap::calculate_range(min_val, max_val);
let num_row: usize = batches.iter().map(|x| x.num_rows()).sum();
if num_row >= u32::MAX as usize {
return Ok(None);
}
if range == usize::MAX as u64 {
return Ok(None);
}
let dense_ratio = (num_row as f64) / ((range + 1) as f64);
if range >= perfect_hash_join_small_build_threshold as u64
&& dense_ratio <= perfect_hash_join_min_key_density
{
return Ok(None);
}
let mem_size = ArrayMap::estimate_memory_size(min_val, max_val, num_row);
reservation.try_grow(mem_size)?;
Ok(Some((min_val, max_val)))
}
struct JoinBuildData {
map: Arc<Map>,
batch: RecordBatch,
values: Vec<ArrayRef>,
bounds: Option<PartitionBounds>,
membership: PushdownStrategy,
reservation: MemoryReservation,
}
pub(super) struct JoinLeftData {
not_in: Option<NotInBuild>,
visited_indices_bitmap: SharedBitmapBuilder,
probe_completion: ProbeCompletion,
build: Arc<JoinBuildData>,
}
impl JoinLeftData {
pub(super) fn map(&self) -> &Map {
&self.build.map
}
pub(super) fn not_in(&self) -> Option<&NotInBuild> {
self.not_in.as_ref()
}
pub(super) fn batch(&self) -> &RecordBatch {
&self.build.batch
}
pub(super) fn has_build_rows(&self) -> bool {
self.batch().num_rows() > 0
}
pub(super) fn has_matchable_build_rows(&self) -> bool {
!self.map().is_empty()
}
pub(super) fn values(&self) -> &[ArrayRef] {
&self.build.values
}
pub(super) fn visited_indices_bitmap(&self) -> &SharedBitmapBuilder {
&self.visited_indices_bitmap
}
pub(super) fn membership(&self) -> &PushdownStrategy {
&self.build.membership
}
pub(super) fn bounds(&self) -> Option<&PartitionBounds> {
self.build.bounds.as_ref()
}
pub(super) fn record_probe_batch(&self, non_empty: bool, has_null: bool) {
self.probe_completion.record_batch(non_empty, has_null);
}
pub(super) fn probe_side_has_null_hint(&self) -> bool {
self.probe_completion.saw_null_key_hint()
}
pub(super) fn report_probe_completed(&self) -> Completion {
self.probe_completion.report_completed()
}
}
pub struct HashJoinExecBuilder {
exec: HashJoinExec,
preserve_properties: bool,
}
impl HashJoinExecBuilder {
pub fn new(
left: Arc<dyn ExecutionPlan>,
right: Arc<dyn ExecutionPlan>,
on: Vec<(PhysicalExprRef, PhysicalExprRef)>,
join_type: JoinType,
) -> Self {
Self {
exec: HashJoinExec {
left,
right,
on,
filter: None,
join_type,
left_fut: Default::default(),
prepared_build: None,
random_state: HASH_JOIN_SEED,
mode: PartitionMode::Auto,
fetch: None,
metrics: ExecutionPlanMetricsSet::new(),
projection: None,
column_indices: vec![],
null_equality: NullEquality::NullEqualsNothing,
null_aware: false,
null_aware_value_keys: 0,
dynamic_filter: None,
cache: stub_properties(),
join_schema: Arc::new(Schema::empty()),
},
preserve_properties: false,
}
}
pub fn with_type(mut self, join_type: JoinType) -> Self {
self.exec.join_type = join_type;
self.preserve_properties = false;
self
}
pub fn with_projection(self, projection: Option<Vec<usize>>) -> Self {
self.with_projection_ref(projection.map(Into::into))
}
pub fn with_projection_ref(mut self, projection: Option<ProjectionRef>) -> Self {
self.exec.projection = projection;
self.preserve_properties = false;
self
}
pub fn with_filter(mut self, filter: Option<JoinFilter>) -> Self {
self.exec.filter = filter;
self
}
pub fn with_on(mut self, on: Vec<(PhysicalExprRef, PhysicalExprRef)>) -> Self {
self.exec.on = on;
self.preserve_properties = false;
self
}
pub fn with_partition_mode(mut self, mode: PartitionMode) -> Self {
self.exec.mode = mode;
self.preserve_properties = false;
self
}
pub fn with_null_equality(mut self, null_equality: NullEquality) -> Self {
self.exec.null_equality = null_equality;
self
}
pub fn with_null_aware(mut self, null_aware: bool) -> Self {
self.exec.null_aware = null_aware;
self
}
pub fn with_null_aware_value_keys(mut self, null_aware_value_keys: usize) -> Self {
self.exec.null_aware_value_keys = null_aware_value_keys;
self
}
pub fn with_fetch(mut self, fetch: Option<usize>) -> Self {
self.exec.fetch = fetch;
self
}
pub fn recompute_properties(mut self) -> Self {
self.preserve_properties = false;
self
}
pub fn with_new_children(
mut self,
mut children: Vec<Arc<dyn ExecutionPlan>>,
) -> Result<Self> {
assert_or_internal_err!(
children.len() == 2,
"wrong number of children passed into `HashJoinExecBuilder`"
);
if self.exec.prepared_build.is_some()
&& !Arc::ptr_eq(&self.exec.left, &children[0])
{
return plan_err!(
"Cannot replace the build child after attaching a prepared hash-join build"
);
}
self.preserve_properties &= has_same_children_properties(&self.exec, &children)?;
self.exec.right = children.swap_remove(1);
self.exec.left = children.swap_remove(0);
Ok(self)
}
pub fn reset_state(mut self) -> Self {
self.exec.left_fut = Default::default();
if let Some(dynamic_filter) = &mut self.exec.dynamic_filter {
dynamic_filter.filter.reset();
dynamic_filter.build_accumulator = OnceLock::new();
}
self.exec.metrics = ExecutionPlanMetricsSet::new();
self
}
pub fn build_exec(self) -> Result<Arc<dyn ExecutionPlan>> {
self.build().map(|p| Arc::new(p) as _)
}
pub fn build(self) -> Result<HashJoinExec> {
let Self {
mut exec,
preserve_properties,
} = self;
if let Some(prepared) = &exec.prepared_build {
prepared.validate(&exec)?;
exec.left_fut = Default::default();
exec.metrics = ExecutionPlanMetricsSet::new();
if let Some(filter) = &mut exec.dynamic_filter {
filter.build_accumulator = OnceLock::new();
}
}
if exec.on.is_empty() {
return plan_err!("On constraints in HashJoinExec should be non-empty");
}
exec.not_in()?;
if preserve_properties {
return Ok(exec);
}
let HashJoinExec {
left,
right,
on,
filter,
join_type,
left_fut,
prepared_build,
random_state,
mode,
metrics,
projection,
null_equality,
null_aware,
null_aware_value_keys,
dynamic_filter,
fetch,
join_schema: _,
column_indices: _,
cache: _,
} = exec;
let left_schema = left.schema();
let right_schema = right.schema();
check_join_is_valid(&left_schema, &right_schema, &on)?;
let (join_schema, column_indices) =
build_join_schema(&left_schema, &right_schema, &join_type);
let join_schema = Arc::new(join_schema);
can_project(&join_schema, projection.as_deref())?;
let cache = HashJoinExec::compute_properties(
&left,
&right,
&join_schema,
join_type,
&on,
mode,
projection.as_deref(),
)?;
Ok(HashJoinExec {
left,
right,
on,
filter,
join_type,
join_schema,
left_fut,
prepared_build,
random_state,
mode,
metrics,
projection,
column_indices,
null_equality,
null_aware,
null_aware_value_keys,
cache: Arc::new(cache),
dynamic_filter,
fetch,
})
}
fn with_dynamic_filter(mut self, filter: Option<HashJoinExecDynamicFilter>) -> Self {
self.exec.dynamic_filter = filter;
self
}
}
impl From<&HashJoinExec> for HashJoinExecBuilder {
fn from(exec: &HashJoinExec) -> Self {
Self {
exec: HashJoinExec {
left: Arc::clone(exec.left()),
right: Arc::clone(exec.right()),
on: exec.on.clone(),
filter: exec.filter.clone(),
join_type: exec.join_type,
join_schema: Arc::clone(&exec.join_schema),
left_fut: Arc::clone(&exec.left_fut),
prepared_build: exec.prepared_build.clone(),
random_state: exec.random_state.clone(),
mode: exec.mode,
metrics: exec.metrics.clone(),
projection: exec.projection.clone(),
column_indices: exec.column_indices.clone(),
null_equality: exec.null_equality,
null_aware: exec.null_aware,
null_aware_value_keys: exec.null_aware_value_keys,
cache: Arc::clone(&exec.cache),
dynamic_filter: exec.dynamic_filter.clone(),
fetch: exec.fetch,
},
preserve_properties: true,
}
}
}
#[expect(rustdoc::private_intra_doc_links)]
pub struct HashJoinExec {
pub left: Arc<dyn ExecutionPlan>,
pub right: Arc<dyn ExecutionPlan>,
pub on: Vec<(PhysicalExprRef, PhysicalExprRef)>,
pub filter: Option<JoinFilter>,
pub join_type: JoinType,
join_schema: SchemaRef,
left_fut: Arc<OnceAsync<JoinLeftData>>,
prepared_build: Option<Arc<PreparedHashJoinBuild>>,
random_state: SeededRandomState,
pub mode: PartitionMode,
metrics: ExecutionPlanMetricsSet,
pub projection: Option<ProjectionRef>,
column_indices: Vec<ColumnIndex>,
pub null_equality: NullEquality,
pub null_aware: bool,
pub null_aware_value_keys: usize,
cache: Arc<PlanProperties>,
dynamic_filter: Option<HashJoinExecDynamicFilter>,
fetch: Option<usize>,
}
#[derive(Clone)]
struct HashJoinExecDynamicFilter {
filter: Arc<DynamicFilterPhysicalExpr>,
build_accumulator: OnceLock<Arc<SharedBuildAccumulator>>,
}
impl fmt::Debug for HashJoinExec {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("HashJoinExec")
.field("left", &self.left)
.field("right", &self.right)
.field("on", &self.on)
.field("filter", &self.filter)
.field("join_type", &self.join_type)
.field("join_schema", &self.join_schema)
.field("left_fut", &self.left_fut)
.field("prepared_build", &self.prepared_build)
.field("random_state", &self.random_state)
.field("mode", &self.mode)
.field("null_aware", &self.null_aware)
.field("null_aware_value_keys", &self.null_aware_value_keys)
.field("metrics", &self.metrics)
.field("projection", &self.projection)
.field("column_indices", &self.column_indices)
.field("null_equality", &self.null_equality)
.field("cache", &self.cache)
.finish()
}
}
impl EmbeddedProjection for HashJoinExec {
fn with_projection(&self, projection: Option<Vec<usize>>) -> Result<Self> {
self.with_projection(projection)
}
}
impl HashJoinExec {
#[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,
projection: Option<Vec<usize>>,
partition_mode: PartitionMode,
null_equality: NullEquality,
null_aware: bool,
) -> Result<Self> {
HashJoinExecBuilder::new(left, right, on, *join_type)
.with_filter(filter)
.with_projection(projection)
.with_partition_mode(partition_mode)
.with_null_equality(null_equality)
.with_null_aware(null_aware)
.build()
}
pub fn builder(&self) -> HashJoinExecBuilder {
self.into()
}
fn create_dynamic_filter(on: &JoinOn) -> Arc<DynamicFilterPhysicalExpr> {
let right_keys: Vec<_> = on.iter().map(|(_, r)| Arc::clone(r)).collect();
Arc::new(DynamicFilterPhysicalExpr::new(right_keys, lit(true)))
}
fn supports_key_transfer(join_type: JoinType) -> bool {
matches!(
join_type,
JoinType::Inner | JoinType::LeftSemi | JoinType::RightSemi
)
}
fn key_transfer_maps(
&self,
column_indices: &[ColumnIndex],
) -> (KeyTransferMap, KeyTransferMap) {
debug_assert!(
self.on.iter().all(|(left_key, right_key)| {
left_key.data_type(&self.left.schema()).ok()
== right_key.data_type(&self.right.schema()).ok()
}),
"join key data types differ: {:?}",
self.on
);
let mut to_right = HashMap::new();
let mut to_left = HashMap::new();
for (output_idx, ci) in column_indices.iter().enumerate() {
let (map, other_key) = match ci.side {
JoinSide::Left => (
&mut to_right,
self.on
.iter()
.find(|(left_key, _)| is_column_at(left_key, ci.index))
.map(|(_, right_key)| right_key),
),
JoinSide::Right => (
&mut to_left,
self.on
.iter()
.find(|(_, right_key)| is_column_at(right_key, ci.index))
.map(|(left_key, _)| left_key),
),
JoinSide::None => continue,
};
if let Some(other_key) = other_key {
map.insert(output_idx, Arc::clone(other_key));
}
}
(to_right, to_left)
}
fn allow_join_dynamic_filter_pushdown(&self, config: &ConfigOptions) -> bool {
let (_, probe_preserved) = self.join_type.on_lr_is_preserved();
if !probe_preserved || !config.optimizer.enable_join_dynamic_filter_pushdown {
return false;
}
if self.null_aware
&& self.on.iter().any(|(build_key, _)| {
build_key.nullable(&self.left.schema()).unwrap_or(true)
})
{
return false;
}
if config.optimizer.preserve_file_partitions > 0
&& self.mode == PartitionMode::Partitioned
&& matches!(
(
self.left.output_partitioning(),
self.right.output_partitioning()
),
(Partitioning::Hash(_, _), Partitioning::Hash(_, _))
)
{
return false;
}
if self.mode == PartitionMode::Partitioned
&& !self.has_partitioned_dynamic_filter_routing()
{
return false;
}
true
}
fn has_partitioned_dynamic_filter_routing(&self) -> bool {
match (
self.left.output_partitioning(),
self.right.output_partitioning(),
) {
(
Partitioning::Hash(_, left_partition_count),
Partitioning::Hash(_, right_partition_count),
) => left_partition_count == right_partition_count,
(Partitioning::Range(_), Partitioning::Range(_)) => {
let children = [self.left.as_ref(), self.right.as_ref()];
matches!(
self.input_distribution_requirements()
.unsatisfied_co_partitioned_children(self.name(), &children),
Ok(unsatisfied) if unsatisfied.is_empty()
)
}
(left_partitioning, right_partitioning) => {
left_partitioning.partition_count() == 1
&& right_partitioning.partition_count() == 1
}
}
}
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 join_schema(&self) -> &SchemaRef {
&self.join_schema
}
pub fn partition_mode(&self) -> &PartitionMode {
&self.mode
}
pub fn null_equality(&self) -> NullEquality {
self.null_equality
}
#[deprecated(
since = "55.0.0",
note = "Use ExecutionPlan::dynamic_expressions_produced instead"
)]
pub fn dynamic_filter_expr(&self) -> Option<&Arc<DynamicFilterPhysicalExpr>> {
self.dynamic_filter.as_ref().map(|df| &df.filter)
}
#[deprecated(
since = "56.0.0",
note = "unused by DataFusion; `HashJoinExec` restores its dynamic filter in `HashJoinExec::try_from_proto`, which sets the field directly. There is no replacement; please open an issue if you have a use case for it."
)]
pub fn with_dynamic_filter_expr(
self,
filter: Arc<DynamicFilterPhysicalExpr>,
) -> Result<Self> {
self.set_dynamic_filter(filter)
}
fn set_dynamic_filter(
mut self,
filter: Arc<DynamicFilterPhysicalExpr>,
) -> Result<Self> {
let probe_schema = self.right.schema();
for child in filter.children() {
child.data_type(&probe_schema)?;
}
self.dynamic_filter = Some(HashJoinExecDynamicFilter {
filter,
build_accumulator: OnceLock::new(),
});
Ok(self)
}
pub(super) fn not_in(&self) -> Result<Option<NotIn>> {
self.null_aware
.then(|| {
NotIn::try_new(
self.join_type,
self.mode,
self.on.len(),
self.null_aware_value_keys,
self.filter.is_some(),
)
})
.transpose()
}
fn maintains_input_order(join_type: JoinType) -> Vec<bool> {
vec![false, !need_produce_result_in_final(join_type)]
}
pub fn probe_side() -> JoinSide {
JoinSide::Right
}
pub fn contains_projection(&self) -> bool {
self.projection.is_some()
}
pub fn with_projection(&self, projection: Option<Vec<usize>>) -> Result<Self> {
let projection = projection.map(Into::into);
can_project(&self.schema(), projection.as_deref())?;
let projection =
combine_projections(projection.as_ref(), self.projection.as_ref())?;
self.builder().with_projection_ref(projection).build()
}
fn compute_properties(
left: &Arc<dyn ExecutionPlan>,
right: &Arc<dyn ExecutionPlan>,
schema: &SchemaRef,
join_type: JoinType,
on: JoinOnRef,
mode: PartitionMode,
projection: Option<&[usize]>,
) -> Result<PlanProperties> {
let mut eq_properties = join_equivalence_properties(
left.equivalence_properties().clone(),
right.equivalence_properties().clone(),
&join_type,
Arc::clone(schema),
&Self::maintains_input_order(join_type),
Some(Self::probe_side()),
on,
)?;
let mut output_partitioning = match mode {
PartitionMode::CollectLeft => {
asymmetric_join_output_partitioning(left, right, &join_type)?
}
PartitionMode::Auto => Partitioning::UnknownPartitioning(
right.output_partitioning().partition_count(),
),
PartitionMode::Partitioned => {
symmetric_join_output_partitioning(left, right, &join_type)?
}
};
let emission_type =
if left.boundedness().is_unbounded() || join_type == JoinType::LeftSemi {
EmissionType::Final
} else if right.pipeline_behavior() == EmissionType::Incremental {
if emits_unmatched_left_rows(join_type) {
EmissionType::Both
} else {
EmissionType::Incremental
}
} else {
right.pipeline_behavior()
};
if let Some(projection) = projection {
let projection_mapping = ProjectionMapping::from_indices(projection, schema)?;
let out_schema = project_schema(schema, Some(&projection))?;
output_partitioning =
output_partitioning.project(&projection_mapping, &eq_properties);
eq_properties = eq_properties.project(&projection_mapping, out_schema);
}
Ok(PlanProperties::new(
eq_properties,
output_partitioning,
emission_type,
boundedness_from_children([left, right]),
))
}
#[doc(hidden)]
pub fn swap_inputs(
&self,
partition_mode: PartitionMode,
) -> Result<Arc<dyn ExecutionPlan>> {
assert_or_internal_err!(
self.dynamic_filter.is_none(),
"Cannot swap HashJoinExec inputs after dynamic filters have been constructed. \
Optimizer rules that reorder join inputs must run before optimizer rules `FilterPushdown::new_post_optimization()`"
);
let left = self.left();
let right = self.right();
let new_join = self
.builder()
.with_type(self.join_type.swap())
.with_new_children(vec![Arc::clone(right), Arc::clone(left)])?
.with_on(
self.on()
.iter()
.map(|(l, r)| (Arc::clone(r), Arc::clone(l)))
.collect(),
)
.with_filter(self.filter().map(JoinFilter::swap))
.with_projection(swap_join_projection(
left.schema().fields().len(),
right.schema().fields().len(),
self.projection.as_deref(),
self.join_type(),
))
.with_partition_mode(partition_mode)
.build()?;
if is_existence_join(self.join_type) || self.projection.is_some() {
Ok(Arc::new(new_join))
} else {
reorder_output_after_swap(Arc::new(new_join), &left.schema(), &right.schema())
}
}
}
impl DisplayAs for HashJoinExec {
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 display_projections = if self.contains_projection() {
format!(
", projection=[{}]",
self.projection
.as_ref()
.unwrap()
.iter()
.map(|index| format!(
"{}@{}",
self.join_schema.fields().get(*index).unwrap().name(),
index
))
.collect::<Vec<_>>()
.join(", ")
)
} else {
"".to_string()
};
let display_null_equality =
if self.null_equality() == NullEquality::NullEqualsNull {
", NullsEqual: true"
} else {
""
};
let display_fetch = self
.fetch
.map_or_else(String::new, |f| format!(", fetch={f}"));
let display_null_aware =
match (self.null_aware, self.null_aware_value_keys) {
(false, _) => String::new(),
(true, 0 | 1) => ", null_aware".to_string(),
(true, n) => format!(", null_aware(value_keys={n})"),
};
let display_prepared = self
.prepared_build
.as_ref()
.map_or_else(String::new, |prepared| {
format!(", prepared_build={} rows", prepared.num_rows())
});
let on = self
.on
.iter()
.map(|(c1, c2)| format!("({c1}, {c2})"))
.collect::<Vec<String>>()
.join(", ");
write!(
f,
"HashJoinExec: mode={:?}, join_type={:?}, on=[{}]{}{}{}{}{}{}",
self.mode,
self.join_type,
on,
display_filter,
display_projections,
display_null_equality,
display_fetch,
display_null_aware,
display_prepared,
)
}
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(", ");
if *self.join_type() != JoinType::Inner {
writeln!(f, "join_type={:?}", self.join_type)?;
}
writeln!(f, "on={on}")?;
if let Some(prepared) = &self.prepared_build {
writeln!(f, "prepared_build={} rows", prepared.num_rows())?;
}
if self.null_equality() == NullEquality::NullEqualsNull {
writeln!(f, "NullsEqual: true")?;
}
if self.null_aware {
if self.null_aware_value_keys <= 1 {
writeln!(f, "null_aware")?;
} else {
writeln!(
f,
"null_aware(value_keys={})",
self.null_aware_value_keys
)?;
}
}
if let Some(filter) = self.filter.as_ref() {
writeln!(f, "filter={filter}")?;
}
if let Some(fetch) = self.fetch {
writeln!(f, "fetch={fetch}")?;
}
Ok(())
}
}
}
}
impl ExecutionPlan for HashJoinExec {
fn name(&self) -> &'static str {
"HashJoinExec"
}
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 {
PartitionMode::Partitioned => {
let (left_expr, right_expr) = self
.on
.iter()
.map(|(l, r)| (Arc::clone(l), Arc::clone(r)))
.unzip();
InputDistributionRequirements::co_partitioned(vec![
Distribution::KeyPartitioned(left_expr),
Distribution::KeyPartitioned(right_expr),
])
}
PartitionMode::CollectLeft => InputDistributionRequirements::new(vec![
Distribution::SinglePartition,
Distribution::UnspecifiedDistribution,
]),
PartitionMode::Auto => InputDistributionRequirements::new(vec![
Distribution::UnspecifiedDistribution,
Distribution::UnspecifiedDistribution,
]),
}
}
fn maintains_input_order(&self) -> Vec<bool> {
Self::maintains_input_order(self.join_type)
}
fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
vec![&self.left, &self.right]
}
fn apply_expressions(
&self,
f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
) -> Result<TreeNodeRecursion> {
let join_keys = self
.on
.iter()
.flat_map(|(left, right)| [Arc::clone(left), Arc::clone(right)]);
let filter = self
.filter
.iter()
.map(|filter| Arc::clone(filter.expression()));
let dynamic_filter = self.dynamic_filter.iter().map(|dynamic_filter| {
Arc::<DynamicFilterPhysicalExpr>::clone(&dynamic_filter.filter)
as Arc<dyn PhysicalExpr>
});
crate::apply_expression_roots(join_keys.chain(filter).chain(dynamic_filter), f)
}
fn dynamic_expressions_produced(&self) -> Vec<Arc<dyn PhysicalExpr>> {
self.dynamic_filter
.iter()
.map(|dynamic_filter| {
Arc::<DynamicFilterPhysicalExpr>::clone(&dynamic_filter.filter)
as Arc<dyn PhysicalExpr>
})
.collect()
}
fn replace_children(
self: Arc<Self>,
children: Vec<Arc<dyn ExecutionPlan>>,
options: ReplaceChildrenOptions,
) -> Result<Arc<dyn ExecutionPlan>> {
validate_child_count!(self, children);
match options.children_properties {
ChildrenPropertiesMode::Keep => {
self.builder().with_new_children(children)?.build_exec()
}
ChildrenPropertiesMode::Recompute => self
.builder()
.recompute_properties()
.with_new_children(children)?
.build_exec(),
}
}
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 reset_state(self: Arc<Self>) -> Result<Arc<dyn ExecutionPlan>> {
self.builder().reset_state().build_exec()
}
fn execute(
&self,
partition: usize,
context: Arc<TaskContext>,
) -> Result<SendableRecordBatchStream> {
let on_left = self
.on
.iter()
.map(|on| Arc::clone(&on.0))
.collect::<Vec<_>>();
let left_partitions = self.left.output_partitioning().partition_count();
let right_partitions = self.right.output_partitioning().partition_count();
assert_or_internal_err!(
self.mode != PartitionMode::Partitioned
|| left_partitions == right_partitions,
"Invalid HashJoinExec, partition count mismatch {left_partitions}!={right_partitions},\
consider using RepartitionExec"
);
assert_or_internal_err!(
self.mode != PartitionMode::CollectLeft || left_partitions == 1,
"Invalid HashJoinExec, the output partition count of the left child must be 1 in CollectLeft mode,\
consider using CoalescePartitionsExec or the EnforceDistribution rule"
);
let enable_dynamic_filter_pushdown = self
.allow_join_dynamic_filter_pushdown(context.session_config().options())
&& self.dynamic_filter.is_some();
let join_metrics = BuildProbeJoinMetrics::new(partition, &self.metrics);
let not_in = self.not_in()?;
let array_map_created_count = MetricBuilder::new(&self.metrics)
.with_category(MetricCategory::Rows)
.counter(ARRAY_MAP_CREATED_COUNT_METRIC_NAME, partition);
let repartition_random_state = REPARTITION_RANDOM_STATE;
let build_accumulator = enable_dynamic_filter_pushdown
.then(|| {
self.dynamic_filter.as_ref().map(|df| {
let filter = Arc::clone(&df.filter);
let on_right = self
.on
.iter()
.map(|(_, right_expr)| Arc::clone(right_expr))
.collect::<Vec<_>>();
Some(Arc::clone(df.build_accumulator.get_or_init(|| {
Arc::new(SharedBuildAccumulator::new_from_partition_mode(
self.mode,
self.left.as_ref(),
self.right.as_ref(),
filter,
on_right,
repartition_random_state,
self.null_equality,
not_in,
&context.session_config().options().optimizer,
))
})))
})
})
.flatten()
.flatten();
let left_fut = match (&self.prepared_build, self.mode) {
(Some(prepared), _) => {
prepared.validate(self)?;
let prepared = Arc::clone(prepared);
self.left_fut.try_once(|| {
Ok(async move { Ok(prepared.probe_data(right_partitions)) })
})?
}
(None, PartitionMode::CollectLeft) => self.left_fut.try_once(|| {
let left_stream = self.left.execute(0, Arc::clone(&context))?;
let reservation =
MemoryConsumer::new("HashJoinInput").register(context.memory_pool());
Ok(collect_left_input(
self.random_state.random_state().clone(),
left_stream,
on_left.clone(),
join_metrics.clone(),
reservation,
need_produce_result_in_final(self.join_type),
right_partitions,
enable_dynamic_filter_pushdown,
Arc::clone(context.session_config().options()),
self.null_equality,
not_in,
array_map_created_count,
BuildMode::Ordinary,
))
})?,
(None, PartitionMode::Partitioned) => {
let left_stream = self.left.execute(partition, Arc::clone(&context))?;
let reservation =
MemoryConsumer::new(format!("HashJoinInput[{partition}]"))
.register(context.memory_pool());
OnceFut::new(collect_left_input(
self.random_state.random_state().clone(),
left_stream,
on_left.clone(),
join_metrics.clone(),
reservation,
need_produce_result_in_final(self.join_type),
1,
enable_dynamic_filter_pushdown,
Arc::clone(context.session_config().options()),
self.null_equality,
not_in,
array_map_created_count,
BuildMode::Ordinary,
))
}
(None, PartitionMode::Auto) => {
return plan_err!(
"Invalid HashJoinExec, unsupported PartitionMode {:?} in execute()",
PartitionMode::Auto
);
}
};
let batch_size = context.session_config().batch_size();
let right_stream = self.right.execute(partition, context)?;
let column_indices_after_projection = match self.projection.as_ref() {
Some(projection) => projection
.iter()
.map(|i| self.column_indices[*i].clone())
.collect(),
None => self.column_indices.clone(),
};
let on_right = self
.on
.iter()
.map(|(_, right_expr)| Arc::clone(right_expr))
.collect::<Vec<_>>();
Ok(Box::pin(HashJoinStream::new(
partition,
self.schema(),
on_right,
self.filter.clone(),
self.join_type,
right_stream,
self.random_state.random_state().clone(),
join_metrics,
column_indices_after_projection,
self.null_equality,
HashJoinStreamState::WaitBuildSide,
BuildSide::Initial(BuildSideInitialState { left_fut }),
batch_size,
vec![],
self.right.output_ordering().is_some(),
build_accumulator,
self.mode,
self.fetch,
)))
}
fn metrics(&self) -> Option<MetricsSet> {
Some(self.metrics.clone_inner().with_output_rows_skew())
}
fn child_stats_requests(&self, partition: Option<usize>) -> Vec<ChildStats> {
match (partition, self.mode) {
(Some(_), PartitionMode::CollectLeft) => {
vec![ChildStats::At(None), ChildStats::At(partition)]
}
(Some(_), PartitionMode::Partitioned) => {
vec![ChildStats::At(partition), ChildStats::At(partition)]
}
(None, _) => vec![ChildStats::At(None), ChildStats::At(None)],
(Some(_), PartitionMode::Auto) => {
vec![ChildStats::At(None), ChildStats::At(None)]
}
}
}
fn statistics_from_inputs(
&self,
input_stats: &[Arc<Statistics>],
args: &StatisticsArgs,
) -> Result<Arc<Statistics>> {
let left_stats = if let Some(prepared) = &self.prepared_build {
Statistics::new_unknown(self.left.schema().as_ref())
.with_num_rows(Precision::Exact(prepared.num_rows()))
} else {
input_stats[0].as_ref().clone()
};
let right_stats = input_stats[1].as_ref().clone();
let stats = estimate_join_statistics(
left_stats,
right_stats,
&self.on,
self.null_equality,
&self.join_type,
&self.join_schema,
)?;
let stats = stats.project(self.projection.as_ref());
Ok(Arc::new(with_per_partition_fetch(
stats,
self.fetch,
self.properties().output_partitioning().partition_count(),
args,
)?))
}
fn try_swapping_with_projection(
&self,
projection: &ProjectionExec,
) -> Result<Option<Arc<dyn ExecutionPlan>>> {
if self.contains_projection() {
return Ok(None);
}
if self.prepared_build.is_some() {
return try_embed_projection(projection, self);
}
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(),
)? {
self.builder()
.with_new_children(vec![
Arc::new(projected_left_child),
Arc::new(projected_right_child),
])?
.with_on(join_on)
.with_filter(join_filter)
.with_projection(None)
.build_exec()
.map(Some)
} else {
try_embed_projection(projection, self)
}
}
fn gather_filters_for_pushdown(
&self,
phase: FilterPushdownPhase,
parent_filters: Vec<Arc<dyn PhysicalExpr>>,
config: &ConfigOptions,
) -> Result<FilterDescription> {
let (left_preserved, right_preserved) = lr_is_preserved(self.join_type);
let column_indices: Vec<ColumnIndex> = match self.projection.as_ref() {
Some(projection) => projection
.iter()
.map(|i| self.column_indices[*i].clone())
.collect(),
None => self.column_indices.clone(),
};
let (mut left_mapping, mut right_mapping) = (HashMap::new(), HashMap::new());
for (output_idx, ci) in column_indices.iter().enumerate() {
match ci.side {
JoinSide::Left => {
left_mapping.insert(output_idx, ci.index);
}
JoinSide::Right => {
right_mapping.insert(output_idx, ci.index);
}
JoinSide::None => {}
}
}
let (to_right, to_left) = if Self::supports_key_transfer(self.join_type) {
self.key_transfer_maps(&column_indices)
} else {
Default::default()
};
let describe_child = |preserved: bool,
column_mapping: HashMap<usize, usize>,
key_map: &KeyTransferMap,
child: &Arc<dyn ExecutionPlan>|
-> Result<ChildFilterDescription> {
if !preserved {
return Ok(ChildFilterDescription::all_unsupported(&parent_filters));
}
let mut description = ChildFilterDescription::from_child_with_column_mapping(
&parent_filters,
column_mapping,
child,
)?;
transfer_key_filters(&parent_filters, key_map, &mut description)?;
Ok(description)
};
let left_child =
describe_child(left_preserved, left_mapping, &to_left, self.left())?;
let mut right_child =
describe_child(right_preserved, right_mapping, &to_right, self.right())?;
if phase == FilterPushdownPhase::Post
&& self.dynamic_filter.is_none()
&& self.allow_join_dynamic_filter_pushdown(config)
{
let dynamic_filter = Self::create_dynamic_filter(&self.on);
right_child = right_child.with_self_filter(dynamic_filter);
}
Ok(FilterDescription::new()
.with_child(left_child)
.with_child(right_child))
}
fn handle_child_pushdown_result(
&self,
_phase: FilterPushdownPhase,
child_pushdown_result: ChildPushdownResult,
_config: &ConfigOptions,
) -> Result<FilterPushdownPropagation<Arc<dyn ExecutionPlan>>> {
let mut result = FilterPushdownPropagation::if_any(child_pushdown_result.clone());
assert_eq!(child_pushdown_result.self_filters.len(), 2); let right_child_self_filters = &child_pushdown_result.self_filters[1]; if let Some(filter) = right_child_self_filters.first() {
let predicate = Arc::clone(&filter.predicate);
if let Ok(dynamic_filter) =
Arc::downcast::<DynamicFilterPhysicalExpr>(predicate)
{
let has_consumer = dynamic_filter
.expression_id()
.map(|id| plan_contains_expression_id(&self.right, id))
.transpose()?
.unwrap_or(false);
if has_consumer {
let new_node = self
.builder()
.with_dynamic_filter(Some(HashJoinExecDynamicFilter {
filter: dynamic_filter,
build_accumulator: OnceLock::new(),
}))
.build_exec()?;
result = result.with_updated_node(new_node);
}
}
}
Ok(result)
}
fn fetch(&self) -> Option<usize> {
self.fetch
}
fn with_fetch(&self, limit: Option<usize>) -> Option<Arc<dyn ExecutionPlan>> {
self.builder()
.with_fetch(limit)
.build()
.ok()
.map(|exec| Arc::new(exec) as _)
}
#[cfg(feature = "proto")]
fn try_to_proto(
&self,
ctx: &crate::proto::ExecutionPlanEncodeCtx<'_>,
) -> Result<Option<datafusion_proto_models::protobuf::PhysicalPlanNode>> {
use datafusion_common::internal_datafusion_err;
use datafusion_proto_models::protobuf;
let Self {
left,
right,
on,
filter,
join_type,
mode,
projection,
null_equality,
null_aware,
null_aware_value_keys,
dynamic_filter,
fetch,
join_schema: _,
left_fut: _,
prepared_build,
random_state: _,
metrics: _,
column_indices: _,
cache: _,
} = self;
if prepared_build.is_some() {
return datafusion_common::not_impl_err!(
"HashJoinExec with a prepared build cannot be serialized"
);
}
let left = ctx.encode_child(left)?;
let right = ctx.encode_child(right)?;
let on = on
.iter()
.map(|(l, r)| -> Result<protobuf::JoinOn> {
Ok(protobuf::JoinOn {
left: Some(ctx.encode_expr(l)?),
right: Some(ctx.encode_expr(r)?),
})
})
.collect::<Result<Vec<_>>>()?;
let join_type = crate::joins::proto::join_type_to_proto(*join_type);
let null_equality = crate::joins::proto::null_equality_to_proto(*null_equality);
let partition_mode = match mode {
PartitionMode::CollectLeft => protobuf::PartitionMode::CollectLeft,
PartitionMode::Partitioned => protobuf::PartitionMode::Partitioned,
PartitionMode::Auto => protobuf::PartitionMode::Auto,
};
let filter = filter
.as_ref()
.map(|f| crate::joins::proto::join_filter_to_proto(f, ctx))
.transpose()?;
let dynamic_filter = dynamic_filter
.as_ref()
.map(|df| {
let df_expr: Arc<dyn PhysicalExpr> =
Arc::clone(&df.filter) as Arc<dyn PhysicalExpr>;
ctx.encode_expr(&df_expr)
})
.transpose()?;
Ok(Some(protobuf::PhysicalPlanNode {
physical_plan_type: Some(
protobuf::physical_plan_node::PhysicalPlanType::HashJoin(Box::new(
protobuf::HashJoinExecNode {
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,
projection: match projection.as_ref() {
None => Vec::new(),
Some(v) if v.is_empty() => vec![u32::MAX],
Some(v) => v.iter().map(|x| *x as u32).collect(),
},
null_aware: *null_aware,
null_aware_value_keys: u32::try_from(*null_aware_value_keys)
.map_err(|_| {
internal_datafusion_err!(
"HashJoinExec: null_aware_value_keys {null_aware_value_keys} does not fit in u32"
)
})?,
dynamic_filter,
fetch: fetch.map(|f| f as u64),
},
)),
),
}))
}
}
#[cfg(feature = "proto")]
impl HashJoinExec {
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, utils::usize_from_wire};
use datafusion_proto_models::protobuf;
use std::any::Any;
let hashjoin = crate::expect_plan_variant!(
node,
protobuf::physical_plan_node::PhysicalPlanType::HashJoin,
"HashJoinExec",
);
let protobuf::HashJoinExecNode {
left,
right,
on,
join_type,
partition_mode,
null_equality,
filter,
projection,
null_aware,
null_aware_value_keys,
dynamic_filter,
fetch,
} = &**hashjoin;
let left = ctx.decode_required_child(left.as_deref(), "HashJoinExec", "left")?;
let right =
ctx.decode_required_child(right.as_deref(), "HashJoinExec", "right")?;
let left_schema = left.schema();
let right_schema = right.schema();
let on: Vec<(PhysicalExprRef, PhysicalExprRef)> = on
.iter()
.map(|col| {
let l = ctx.decode_required_expr(
col.left.as_ref(),
left_schema.as_ref(),
"HashJoinExec",
"on.left",
)?;
let r = ctx.decode_required_expr(
col.right.as_ref(),
right_schema.as_ref(),
"HashJoinExec",
"on.right",
)?;
Ok((l, r))
})
.collect::<Result<_>>()?;
let join_type =
crate::joins::proto::join_type_from_proto(*join_type, "HashJoinExec")?;
let null_equality = crate::joins::proto::null_equality_from_proto(
*null_equality,
"HashJoinExec",
)?;
let partition_mode = match protobuf::PartitionMode::try_from(*partition_mode)
.map_err(|_| {
internal_datafusion_err!(
"HashJoinExec: unknown PartitionMode {partition_mode}"
)
})? {
protobuf::PartitionMode::CollectLeft => PartitionMode::CollectLeft,
protobuf::PartitionMode::Partitioned => PartitionMode::Partitioned,
protobuf::PartitionMode::Auto => PartitionMode::Auto,
};
let filter = filter
.as_ref()
.map(|f| crate::joins::proto::join_filter_from_proto(f, ctx, "HashJoinExec"))
.transpose()?;
let projection = match projection.as_slice() {
[] => None,
[u32::MAX] => Some(Vec::new()),
indices => Some(indices.iter().map(|i| *i as usize).collect()),
};
let fetch = fetch
.map(|fetch| usize_from_wire(fetch, "HashJoinExec", "fetch"))
.transpose()?;
let mut hash_join = HashJoinExecBuilder::new(left, right, on, join_type)
.with_filter(filter)
.with_projection(projection)
.with_partition_mode(partition_mode)
.with_null_equality(null_equality)
.with_null_aware(*null_aware)
.with_null_aware_value_keys(usize_from_wire(
u64::from(*null_aware_value_keys),
"HashJoinExec",
"null_aware_value_keys",
)?)
.with_fetch(fetch)
.build()?;
if let Some(dynamic_filter_proto) = dynamic_filter {
let dynamic_filter_expr =
ctx.decode_expr(dynamic_filter_proto, right_schema.as_ref())?;
let df = (dynamic_filter_expr as Arc<dyn Any + Send + Sync>)
.downcast::<DynamicFilterPhysicalExpr>()
.map_err(|_| {
internal_datafusion_err!(
"HashJoinExec dynamic_filter did not decode to a DynamicFilterPhysicalExpr"
)
})?;
hash_join = hash_join.set_dynamic_filter(df)?;
}
Ok(Arc::new(hash_join))
}
}
#[cfg(all(test, feature = "proto"))]
mod proto_tests {
use super::*;
use crate::proto::{ExecutionPlanDecodeCtx, ExecutionPlanEncodeCtx};
use crate::proto_test_util::{
StubPlanDecoder, StubPlanEncoder, UnreachablePlanDecoder, column_node,
encoded_child_node, stub_child,
};
use datafusion_physical_expr::expressions::Column;
use datafusion_proto_models::protobuf;
fn join_builder() -> HashJoinExecBuilder {
let on: Vec<(PhysicalExprRef, PhysicalExprRef)> =
vec![(Arc::new(Column::new("a", 0)), Arc::new(Column::new("a", 0)))];
HashJoinExecBuilder::new(stub_child(), stub_child(), on, JoinType::Inner)
}
fn encode(
plan: &HashJoinExec,
encoder: &StubPlanEncoder,
) -> protobuf::HashJoinExecNode {
let ctx = ExecutionPlanEncodeCtx::new(encoder);
let node = plan
.try_to_proto(&ctx)
.unwrap()
.expect("HashJoinExec should encode to Some(node)");
match node.physical_plan_type {
Some(protobuf::physical_plan_node::PhysicalPlanType::HashJoin(join)) => *join,
other => panic!("expected a HashJoin node, got {other:?}"),
}
}
fn encode_projection(projection: Option<Vec<usize>>) -> Vec<u32> {
let plan = join_builder().with_projection(projection).build().unwrap();
encode(&plan, &StubPlanEncoder::ok()).projection
}
fn join_node(node: protobuf::HashJoinExecNode) -> protobuf::PhysicalPlanNode {
protobuf::PhysicalPlanNode {
physical_plan_type: Some(
protobuf::physical_plan_node::PhysicalPlanType::HashJoin(Box::new(node)),
),
}
}
fn decodable_node() -> protobuf::HashJoinExecNode {
protobuf::HashJoinExecNode {
left: Some(Box::new(encoded_child_node())),
right: Some(Box::new(encoded_child_node())),
on: vec![protobuf::JoinOn {
left: Some(column_node("a", 0)),
right: Some(column_node("a", 0)),
}],
join_type: protobuf::JoinType::Inner.into(),
partition_mode: protobuf::PartitionMode::Partitioned.into(),
null_equality: protobuf::NullEquality::NullEqualsNothing.into(),
filter: None,
projection: vec![],
null_aware: false,
null_aware_value_keys: 0,
dynamic_filter: None,
fetch: None,
}
}
fn decode(node: protobuf::HashJoinExecNode) -> Arc<dyn ExecutionPlan> {
let decoder = StubPlanDecoder::ok();
let ctx = ExecutionPlanDecodeCtx::new(&decoder);
HashJoinExec::try_from_proto(&join_node(node), &ctx).unwrap()
}
fn as_join(plan: &Arc<dyn ExecutionPlan>) -> &HashJoinExec {
plan.downcast_ref::<HashJoinExec>()
.expect("decoded plan should be a HashJoinExec")
}
#[test]
fn try_to_proto_encodes_an_absent_projection_as_empty() {
assert_eq!(encode_projection(None), Vec::<u32>::new());
}
#[test]
fn try_to_proto_encodes_an_empty_projection_as_the_sentinel() {
assert_eq!(encode_projection(Some(vec![])), vec![u32::MAX]);
}
#[test]
fn try_to_proto_encodes_a_non_empty_projection_as_is() {
assert_eq!(encode_projection(Some(vec![0, 2])), vec![0, 2]);
}
#[test]
fn try_from_proto_decodes_an_empty_projection_field_as_absent() {
let plan = decode(decodable_node());
assert!(as_join(&plan).projection.is_none());
}
#[test]
fn try_from_proto_decodes_the_sentinel_as_an_empty_projection() {
let mut node = decodable_node();
node.projection = vec![u32::MAX];
let plan = decode(node);
let projection = as_join(&plan)
.projection
.as_ref()
.expect("the sentinel decodes to Some(empty)");
assert!(projection.is_empty());
}
#[test]
fn try_from_proto_decodes_a_non_empty_projection_as_is() {
let mut node = decodable_node();
node.projection = vec![0, 2];
let plan = decode(node);
assert_eq!(
as_join(&plan).projection.as_deref(),
Some([0, 2].as_slice())
);
}
#[test]
fn try_to_proto_encodes_fetch_by_presence() {
let unlimited = join_builder().build().unwrap();
assert_eq!(encode(&unlimited, &StubPlanEncoder::ok()).fetch, None);
let limited = join_builder().with_fetch(Some(10)).build().unwrap();
assert_eq!(encode(&limited, &StubPlanEncoder::ok()).fetch, Some(10));
let empty = join_builder().with_fetch(Some(0)).build().unwrap();
assert_eq!(encode(&empty, &StubPlanEncoder::ok()).fetch, Some(0));
}
#[test]
fn try_from_proto_decodes_an_absent_fetch_as_no_limit() {
assert_eq!(as_join(&decode(decodable_node())).fetch, None);
}
#[test]
fn try_from_proto_decodes_a_present_fetch() {
let mut node = decodable_node();
node.fetch = Some(10);
assert_eq!(as_join(&decode(node)).fetch, Some(10));
let mut node = decodable_node();
node.fetch = Some(0);
assert_eq!(as_join(&decode(node)).fetch, Some(0));
}
#[test]
#[cfg(target_pointer_width = "64")]
fn try_from_proto_decodes_the_largest_fetch_without_truncating() {
let plan = decode({
let mut node = decodable_node();
node.fetch = Some(u64::MAX);
node
});
assert_eq!(as_join(&plan).fetch, Some(usize::MAX));
}
#[test]
fn partition_mode_round_trips_by_name() {
for (mode, wire) in [
(
PartitionMode::CollectLeft,
protobuf::PartitionMode::CollectLeft,
),
(
PartitionMode::Partitioned,
protobuf::PartitionMode::Partitioned,
),
(PartitionMode::Auto, protobuf::PartitionMode::Auto),
] {
let plan = join_builder().with_partition_mode(mode).build().unwrap();
let node = encode(&plan, &StubPlanEncoder::ok());
assert_eq!(node.partition_mode, i32::from(wire), "encoding {mode:?}");
let mut decodable = decodable_node();
decodable.partition_mode = node.partition_mode;
assert_eq!(*as_join(&decode(decodable)).partition_mode(), mode);
}
}
#[test]
fn try_from_proto_rejects_an_unknown_partition_mode() {
let decoder = StubPlanDecoder::ok();
let ctx = ExecutionPlanDecodeCtx::new(&decoder);
let mut node = decodable_node();
node.partition_mode = 42;
let err = HashJoinExec::try_from_proto(&join_node(node), &ctx).unwrap_err();
assert!(
err.to_string()
.contains("HashJoinExec: unknown PartitionMode 42")
);
}
#[test]
fn null_aware_round_trips() {
let plan = join_builder()
.with_type(JoinType::LeftAnti)
.with_null_aware(true)
.build()
.unwrap();
assert!(encode(&plan, &StubPlanEncoder::ok()).null_aware);
let mut node = decodable_node();
node.join_type = protobuf::JoinType::Leftanti.into();
node.null_aware = true;
node.partition_mode = protobuf::PartitionMode::CollectLeft.into();
assert!(as_join(&decode(node)).null_aware);
}
#[test]
fn try_from_proto_rejects_a_null_aware_partitioned_join() {
let decoder = StubPlanDecoder::ok();
let ctx = ExecutionPlanDecodeCtx::new(&decoder);
let mut node = decodable_node();
node.join_type = protobuf::JoinType::Leftanti.into();
node.null_aware = true;
assert_eq!(
node.partition_mode,
protobuf::PartitionMode::Partitioned as i32
);
let err = HashJoinExec::try_from_proto(&join_node(node), &ctx).unwrap_err();
assert!(
err.to_string()
.contains("null_aware joins require PartitionMode::CollectLeft"),
"{err}"
);
}
#[test]
fn null_aware_value_keys_round_trip() {
let on: Vec<(PhysicalExprRef, PhysicalExprRef)> = vec![
(Arc::new(Column::new("a", 0)), Arc::new(Column::new("a", 0))),
(Arc::new(Column::new("a", 0)), Arc::new(Column::new("a", 0))),
];
let plan =
HashJoinExecBuilder::new(stub_child(), stub_child(), on, JoinType::LeftAnti)
.with_partition_mode(PartitionMode::CollectLeft)
.with_null_aware(true)
.with_null_aware_value_keys(2)
.build()
.unwrap();
assert_eq!(
encode(&plan, &StubPlanEncoder::ok()).null_aware_value_keys,
2
);
let mut node = decodable_node();
node.join_type = protobuf::JoinType::Leftanti.into();
node.partition_mode = protobuf::PartitionMode::CollectLeft.into();
node.null_aware = true;
node.on = vec![node.on[0].clone(), node.on[0].clone()];
node.null_aware_value_keys = 2;
assert_eq!(as_join(&decode(node.clone())).null_aware_value_keys, 2);
node.null_aware_value_keys = 0;
let decoder = StubPlanDecoder::ok();
let ctx = ExecutionPlanDecodeCtx::new(&decoder);
let err =
HashJoinExec::try_from_proto(&join_node(node.clone()), &ctx).unwrap_err();
assert!(
err.to_string().contains("with_null_aware_value_keys"),
"{err}"
);
node.on.truncate(1);
assert_eq!(as_join(&decode(node)).null_aware_value_keys, 0);
}
#[test]
fn try_to_proto_encodes_both_children_and_both_key_sides() {
let encoder = StubPlanEncoder::ok();
let node = encode(&join_builder().build().unwrap(), &encoder);
assert_eq!(encoder.plan_calls(), 2);
assert_eq!(encoder.expr_calls(), 2);
assert_eq!(node.left, Some(Box::new(encoded_child_node())));
assert_eq!(node.right, Some(Box::new(encoded_child_node())));
}
#[test]
fn try_to_proto_propagates_child_encode_error() {
let plan = join_builder().build().unwrap();
let encoder = StubPlanEncoder::failing_on_plan(2);
let ctx = ExecutionPlanEncodeCtx::new(&encoder);
let err = plan.try_to_proto(&ctx).unwrap_err();
assert!(
err.to_string()
.contains("stub plan encode failure on call 2")
);
}
#[test]
fn try_from_proto_rejects_a_different_plan_variant() {
let decoder = UnreachablePlanDecoder::new();
let ctx = ExecutionPlanDecodeCtx::new(&decoder);
let err = HashJoinExec::try_from_proto(&encoded_child_node(), &ctx).unwrap_err();
assert!(err.to_string().contains("not a HashJoinExec"));
}
#[test]
fn try_from_proto_rejects_a_missing_child() {
let decoder = UnreachablePlanDecoder::new();
let ctx = ExecutionPlanDecodeCtx::new(&decoder);
let mut node = decodable_node();
node.left = None;
let err = HashJoinExec::try_from_proto(&join_node(node), &ctx).unwrap_err();
assert!(
err.to_string()
.contains("HashJoinExec is missing required field 'left'")
);
}
}
type KeyTransferMap = HashMap<usize, PhysicalExprRef>;
fn is_column_at(expr: &PhysicalExprRef, index: usize) -> bool {
expr.downcast_ref::<Column>()
.is_some_and(|column| column.index() == index)
}
fn transfer_key_filters(
parent_filters: &[Arc<dyn PhysicalExpr>],
key_map: &KeyTransferMap,
child: &mut ChildFilterDescription,
) -> Result<()> {
if key_map.is_empty() {
return Ok(());
}
for (filter, pushed) in parent_filters.iter().zip(child.parent_filters.iter_mut()) {
if let Some(transferred) = transfer_filter_across_keys(filter, key_map)? {
*pushed = PushedDownPredicate::supported(transferred);
}
}
Ok(())
}
fn transfer_filter_across_keys(
filter: &Arc<dyn PhysicalExpr>,
key_map: &KeyTransferMap,
) -> Result<Option<Arc<dyn PhysicalExpr>>> {
let mut all_keys = true;
let transformed = Arc::clone(filter).transform_down(|expr| {
let Some(column) = expr.downcast_ref::<Column>() else {
return Ok(Transformed::no(expr));
};
match key_map.get(&column.index()) {
Some(other_key) => Ok(Transformed::new(
Arc::clone(other_key),
true,
TreeNodeRecursion::Jump,
)),
None => {
all_keys = false;
Ok(Transformed::new(expr, false, TreeNodeRecursion::Stop))
}
}
})?;
Ok(all_keys.then_some(transformed.data))
}
fn lr_is_preserved(join_type: JoinType) -> (bool, bool) {
match join_type {
JoinType::Inner => (true, true),
JoinType::Left => (true, false),
JoinType::Right => (false, true),
JoinType::Full => (false, false),
JoinType::LeftSemi | JoinType::RightSemi => (true, true),
JoinType::LeftAnti | JoinType::LeftMark => (true, false),
JoinType::RightAnti | JoinType::RightMark => (false, true),
}
}
struct CollectLeftAccumulator {
expr: Arc<dyn PhysicalExpr>,
min: MinAccumulator,
max: MaxAccumulator,
}
impl CollectLeftAccumulator {
fn try_new(expr: Arc<dyn PhysicalExpr>, schema: &SchemaRef) -> Result<Self> {
fn dictionary_value_type(data_type: &DataType) -> DataType {
match data_type {
DataType::Dictionary(_, value_type) => {
dictionary_value_type(value_type.as_ref())
}
_ => data_type.clone(),
}
}
let data_type = expr
.data_type(schema)
.map(|dt| dictionary_value_type(&dt))?;
Ok(Self {
expr,
min: MinAccumulator::try_new(&data_type)?,
max: MaxAccumulator::try_new(&data_type)?,
})
}
fn update_batch(&mut self, batch: &RecordBatch) -> Result<()> {
let array = self.expr.evaluate(batch)?.into_array(batch.num_rows())?;
self.min.update_batch(std::slice::from_ref(&array))?;
self.max.update_batch(std::slice::from_ref(&array))?;
Ok(())
}
fn evaluate(mut self) -> Result<ColumnBounds> {
Ok(ColumnBounds::new(
self.min.evaluate()?,
self.max.evaluate()?,
))
}
}
#[derive(PartialEq, Eq)]
enum BuildMode {
Ordinary,
Prepared,
}
struct BuildSideState {
batches: Vec<RecordBatch>,
num_rows: usize,
metrics: BuildProbeJoinMetrics,
reservation: MemoryReservation,
bounds_accumulators: Option<Vec<CollectLeftAccumulator>>,
memory_counter: RecordBatchMemoryCounter,
}
impl BuildSideState {
fn try_new(
metrics: BuildProbeJoinMetrics,
reservation: MemoryReservation,
on_left: Vec<Arc<dyn PhysicalExpr>>,
schema: &SchemaRef,
should_compute_dynamic_filters: bool,
) -> Result<Self> {
Ok(Self {
batches: Vec::new(),
num_rows: 0,
metrics,
reservation,
memory_counter: RecordBatchMemoryCounter::new(),
bounds_accumulators: should_compute_dynamic_filters
.then(|| {
on_left
.into_iter()
.map(|expr| CollectLeftAccumulator::try_new(expr, schema))
.collect::<Result<Vec<_>>>()
})
.transpose()?,
})
}
}
fn is_perfect_hash_join_candidate(
on_left: &[PhysicalExprRef],
schema: &SchemaRef,
) -> Result<bool> {
if on_left.len() != 1 {
return Ok(false);
}
let expr = &on_left[0];
let data_type = expr.data_type(schema)?;
Ok(ArrayMap::is_supported_type(&data_type))
}
pub(super) fn new_join_hashmap(
num_rows: usize,
reservation: &mut MemoryReservation,
metrics: &BuildProbeJoinMetrics,
) -> Result<Box<dyn JoinHashMapType>> {
let fixed_size_u32 = size_of::<JoinHashMapU32>();
let fixed_size_u64 = size_of::<JoinHashMapU64>();
if num_rows > u32::MAX as usize {
let estimated_hashtable_size =
estimate_memory_size::<(u64, u64)>(num_rows, fixed_size_u64)?
.checked_add(num_rows * size_of::<u64>())
.ok_or_else(|| {
datafusion_common::exec_datafusion_err!(
"Hash join table size overflow"
)
})?;
reservation.try_grow(estimated_hashtable_size)?;
metrics.build_mem_used.add(estimated_hashtable_size);
Ok(Box::new(JoinHashMapU64::with_capacity(num_rows)))
} else {
let estimated_hashtable_size =
estimate_memory_size::<(u32, u64)>(num_rows, fixed_size_u32)?
.checked_add(num_rows * size_of::<u32>())
.ok_or_else(|| {
datafusion_common::exec_datafusion_err!(
"Hash join table size overflow"
)
})?;
reservation.try_grow(estimated_hashtable_size)?;
metrics.build_mem_used.add(estimated_hashtable_size);
Ok(Box::new(JoinHashMapU32::with_capacity(num_rows)))
}
}
fn estimate_concat_allocation(array: &dyn Array) -> Result<usize> {
match array.data_type() {
DataType::Utf8View | DataType::BinaryView => {
let nulls = array
.nulls()
.map(|_| bit_util::ceil(array.len(), 8))
.unwrap_or_default();
Ok(array.len() * size_of::<u128>() + nulls)
}
_ => Ok(array.to_data().get_slice_memory_size()?),
}
}
fn concat_build_batches(
schema: &SchemaRef,
batches: &mut Vec<RecordBatch>,
inputs_reserved: usize,
reservation: &mut MemoryReservation,
metrics: &BuildProbeJoinMetrics,
) -> Result<RecordBatch> {
let copy_size = if batches.len() > 1 {
let mut copy_size = 0;
for batch in batches.iter() {
for array in batch.columns() {
copy_size += estimate_concat_allocation(array.as_ref())?;
}
}
copy_size
} else {
0
};
reservation.try_grow(copy_size)?;
metrics.build_mem_used.add(copy_size);
let batch = concat_batches(schema, batches.iter())?;
batches.clear();
batches.push(batch.clone());
let held = inputs_reserved + copy_size;
let retained = get_record_batch_memory_size(&batch);
if retained > held {
reservation.try_grow(retained - held)?;
metrics.build_mem_used.add(retained - held);
} else {
reservation.shrink(held - retained);
metrics.build_mem_used.sub(held - retained);
}
Ok(batch)
}
#[expect(clippy::too_many_arguments)]
async fn collect_left_input(
random_state: RandomState,
mut left_stream: SendableRecordBatchStream,
on_left: Vec<PhysicalExprRef>,
metrics: BuildProbeJoinMetrics,
reservation: MemoryReservation,
with_visited_indices_bitmap: bool,
probe_threads_count: usize,
should_compute_dynamic_filters: bool,
config: Arc<ConfigOptions>,
null_equality: NullEquality,
not_in: Option<NotIn>,
array_map_created_count: Count,
mode: BuildMode,
) -> Result<JoinLeftData> {
let schema = left_stream.schema();
let prepared = mode == BuildMode::Prepared;
let is_phj_candidate = is_perfect_hash_join_candidate(&on_left, &schema)?;
let mut state = BuildSideState::try_new(
metrics,
reservation,
on_left.clone(),
&schema,
should_compute_dynamic_filters || is_phj_candidate,
)?;
let mut max_batch_rows = 0;
while let Some(batch) = left_stream.try_next().await? {
max_batch_rows = max_batch_rows.max(batch.num_rows());
if let Some(accumulators) = &mut state.bounds_accumulators {
for accumulator in accumulators {
accumulator.update_batch(&batch)?;
}
}
let batch_size = state.memory_counter.count_batch(&batch);
state.reservation.try_grow(batch_size)?;
state.metrics.build_mem_used.add(batch_size);
state.metrics.build_input_batches.add(1);
state.metrics.build_input_rows.add(batch.num_rows());
state.num_rows += batch.num_rows();
state.batches.push(batch);
}
drop(left_stream);
if prepared && state.batches.is_empty() {
let empty = RecordBatch::new_empty(Arc::clone(&schema));
state
.reservation
.try_grow(state.memory_counter.count_batch(&empty))?;
state.batches.push(empty);
}
let input_bytes = state.memory_counter.memory_usage();
let BuildSideState {
reservation,
mut batches,
num_rows,
metrics,
bounds_accumulators,
memory_counter: _,
} = state;
let copy_bytes = if prepared && batches.len() > 1 {
let copy_bytes = prepared::prepared_copy_bytes(&batches)?;
reservation.try_grow(copy_bytes)?;
copy_bytes
} else {
0
};
let bounds = match bounds_accumulators {
Some(accumulators) if num_rows > 0 => {
let bounds = accumulators
.into_iter()
.map(CollectLeftAccumulator::evaluate)
.collect::<Result<Vec<_>>>()?;
Some(PartitionBounds::new(bounds))
}
_ => None,
};
build_in_memory(
&random_state,
&schema,
&mut batches,
num_rows,
max_batch_rows,
input_bytes,
copy_bytes,
&on_left,
&metrics,
reservation,
bounds,
with_visited_indices_bitmap,
probe_threads_count,
should_compute_dynamic_filters,
&config,
null_equality,
not_in,
&array_map_created_count,
prepared,
)
}
#[expect(clippy::too_many_arguments)]
fn build_in_memory(
random_state: &RandomState,
schema: &SchemaRef,
batches: &mut Vec<RecordBatch>,
num_rows: usize,
max_batch_rows: usize,
input_bytes: usize,
copy_bytes: usize,
on_left: &[PhysicalExprRef],
metrics: &BuildProbeJoinMetrics,
mut reservation: MemoryReservation,
mut bounds: Option<PartitionBounds>,
with_visited_indices_bitmap: bool,
probe_threads_count: usize,
should_compute_dynamic_filters: bool,
config: &ConfigOptions,
null_equality: NullEquality,
not_in: Option<NotIn>,
array_map_created_count: &Count,
prepared: bool,
) -> Result<JoinLeftData> {
let is_phj_candidate = is_perfect_hash_join_candidate(on_left, schema)?;
let (join_hash_map, batch, left_values) = if let Some((min_val, max_val)) =
array_map_key_range(
bounds.as_ref(),
schema,
batches,
on_left,
&mut reservation,
config.execution.perfect_hash_join_small_build_threshold,
config.execution.perfect_hash_join_min_key_density,
null_equality,
)? {
let batch = if prepared {
concat_batches(schema, batches.iter())?
} else {
concat_build_batches(schema, batches, input_bytes, &mut reservation, metrics)?
};
let left_values = evaluate_expressions_to_arrays(on_left, &batch)?;
let array_map = ArrayMap::try_new(&left_values[0], min_val, max_val)?;
array_map_created_count.add(1);
metrics.build_mem_used.add(array_map.size());
(Map::ArrayMap(array_map), batch, left_values)
} else {
let mut hashmap = new_join_hashmap(num_rows, &mut reservation, metrics)?;
let scratch_reservation = reservation.new_empty();
if prepared {
scratch_reservation.try_grow(prepared::prepared_scratch_bytes(
max_batch_rows,
on_left.len(),
null_equality,
)?)?;
}
let mut hashes_buffer = Vec::with_capacity(max_batch_rows);
let mut offset = num_rows;
for batch in batches.iter().rev() {
offset -= batch.num_rows();
hashes_buffer.clear();
hashes_buffer.resize(batch.num_rows(), 0);
update_hash(
on_left,
batch,
&mut *hashmap,
offset,
random_state,
&mut hashes_buffer,
0,
true,
null_equality,
)?;
}
let batch = if prepared {
concat_batches(schema, batches.iter())?
} else {
concat_build_batches(schema, batches, input_bytes, &mut reservation, metrics)?
};
let left_values = evaluate_expressions_to_arrays(on_left, &batch)?;
(Map::HashMap(hashmap), batch, left_values)
};
let normalized_values: Vec<ArrayRef> =
left_values.iter().map(normalize_floats).collect();
let mut key_counter = RecordBatchMemoryCounter::new();
key_counter.count_batch(&batch);
let keys_size = left_values
.iter()
.chain(&normalized_values)
.map(|values| key_counter.count_array(values.as_ref()))
.sum::<usize>();
reservation.try_grow(keys_size)?;
metrics.build_mem_used.add(keys_size);
let allocate_bitmap = || -> Result<BooleanBufferBuilder> {
let bitmap_size = bit_util::ceil(batch.num_rows(), 8);
reservation.try_grow(bitmap_size)?;
metrics.build_mem_used.add(bitmap_size);
let mut bitmap = BooleanBufferBuilder::new(batch.num_rows());
bitmap.append_n(num_rows, false);
Ok(bitmap)
};
let visited_indices_bitmap = if with_visited_indices_bitmap {
allocate_bitmap()?
} else {
BooleanBufferBuilder::new(0)
};
let not_in = not_in
.map(|not_in| {
NotInBuild::try_new(
not_in,
on_left,
&batch,
&left_values,
&normalized_values,
random_state,
&mut reservation,
metrics,
)
})
.transpose()?;
let map = Arc::new(join_hash_map);
let membership = if num_rows == 0 || (!prepared && !should_compute_dynamic_filters) {
PushdownStrategy::Empty
} else {
let estimated_size = left_values
.iter()
.map(|arr| arr.get_array_memory_size())
.sum::<usize>();
let pushdown_inlist = !left_values.is_empty()
&& !left_values[0].is_empty()
&& estimated_size <= config.optimizer.hash_join_inlist_pushdown_max_size
&& map.num_of_distinct_key()
<= config
.optimizer
.hash_join_inlist_pushdown_max_distinct_values;
if pushdown_inlist
&& let Some(in_list_values) = build_struct_inlist_values(&left_values)?
{
PushdownStrategy::InList(in_list_values)
} else {
let pruning_bitmap = match (left_values.as_slice(), bounds.as_ref()) {
([keys], Some(bounds)) if !keys.is_empty() => bounds
.get_column_bounds(0)
.and_then(|b| {
KeyRangeBitmap::try_new(
keys,
&b.min,
&b.max,
map.num_of_distinct_key(),
)
})
.map(Arc::new),
_ => None,
};
let pruning_bitmap = pruning_bitmap.filter(|bitmap| {
let ok = reservation.try_grow(bitmap.size()).is_ok();
if ok {
metrics.build_mem_used.add(bitmap.size());
}
ok
});
PushdownStrategy::Map(Arc::clone(&map), pruning_bitmap)
}
};
if is_phj_candidate && !should_compute_dynamic_filters {
bounds = None;
}
if prepared {
batches.clear();
let retained = RecordBatchMemoryCounter::new().count_batch(&batch);
prepared::reconcile_prepared_copy_reservation(
&reservation,
input_bytes,
copy_bytes,
retained,
)?;
}
let data = JoinLeftData {
build: Arc::new(JoinBuildData {
map,
batch,
values: normalized_values,
bounds,
membership,
reservation,
}),
not_in,
visited_indices_bitmap: Mutex::new(visited_indices_bitmap),
probe_completion: ProbeCompletion::new(probe_threads_count),
};
Ok(data)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::joins::hash_join::not_in::{NotInOutput, NotInScope};
fn assert_phj_used(metrics: &MetricsSet, use_phj: bool) {
if use_phj {
assert!(
metrics
.sum_by_name(ARRAY_MAP_CREATED_COUNT_METRIC_NAME)
.expect("should have array_map_created_count metrics")
.as_usize()
>= 1
);
} else {
assert_eq!(
metrics
.sum_by_name(ARRAY_MAP_CREATED_COUNT_METRIC_NAME)
.map(|v| v.as_usize())
.unwrap_or(0),
0
)
}
}
#[track_caller]
fn assert_ratio_metric(
metrics: &MetricsSet,
metric_name: &str,
expected_part: usize,
expected_total: usize,
) {
let Some(MetricValue::Ratio { ratio_metrics, .. }) =
metrics.sum_by_name(metric_name)
else {
panic!("should have {metric_name} metrics")
};
assert_eq!(
(ratio_metrics.part(), ratio_metrics.total()),
(expected_part, expected_total),
"{metric_name} (part, total) mismatch",
);
}
fn build_schema_and_on() -> Result<(SchemaRef, SchemaRef, JoinOn)> {
let left_schema = Arc::new(Schema::new(vec![
Field::new("a1", DataType::Int32, true),
Field::new("b1", DataType::Int32, true),
]));
let right_schema = Arc::new(Schema::new(vec![
Field::new("a2", DataType::Int32, true),
Field::new("b1", DataType::Int32, true),
]));
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left_schema)?) as _,
Arc::new(Column::new_with_schema("b1", &right_schema)?) as _,
)];
Ok((left_schema, right_schema, on))
}
use crate::coalesce_partitions::CoalescePartitionsExec;
use crate::execution_plan::Boundedness;
use crate::filter::FilterExecBuilder;
use crate::joins::hash_join::stream::lookup_join_hashmap;
use crate::statistics::StatisticsContext;
use crate::test::{TestMemoryExec, assert_join_metrics};
use crate::{ChildrenPropertiesMode, ReplaceChildrenOptions};
use crate::{
common, expressions::Column, repartition::RepartitionExec, test::build_table_i32,
test::exec::MockExec,
};
use crate::joins::join_hash_map::ProbeOffset::AtRow;
use arrow::array::{
Array, ArrayRef, AsArray, BinaryViewArray, Date32Array, DictionaryArray,
Float32Array, Float64Array, Int32Array, Int64Array, StringArray, StringViewArray,
StructArray, UInt32Array, UInt64Array,
};
use arrow::buffer::NullBuffer;
use arrow::datatypes::{DataType, Field, Float32Type, Float64Type, Int32Type};
use datafusion_common::hash_utils::create_hashes;
use datafusion_common::stats::Precision;
use datafusion_common::test_util::{batches_to_sort_string, batches_to_string};
use datafusion_common::{
ScalarValue, assert_batches_eq, assert_batches_sorted_eq, assert_contains,
exec_err, internal_err,
};
use datafusion_execution::config::SessionConfig;
use datafusion_execution::memory_pool::{
GreedyMemoryPool, MemoryPool, UnboundedMemoryPool,
};
use datafusion_execution::runtime_env::RuntimeEnvBuilder;
use datafusion_expr::Operator;
use datafusion_physical_expr::expressions::{BinaryExpr, Literal};
use datafusion_physical_expr::{
EquivalenceProperties, PhysicalSortExpr, RangePartitioning, SplitPoint,
};
use datafusion_physical_expr_common::metrics::MetricValue;
use futures::StreamExt;
use hashbrown::HashTable;
use insta::{allow_duplicates, assert_snapshot};
use rstest::*;
use rstest_reuse::*;
#[test]
fn hash_map_admits_row_indices_before_allocation() -> Result<()> {
use datafusion_execution::memory_pool::{GreedyMemoryPool, MemoryPool};
let rows = 1024;
let buckets =
estimate_memory_size::<(u32, u64)>(rows, size_of::<JoinHashMapU32>())?;
let bytes = buckets + rows * size_of::<u32>();
for (limit, succeeds) in [(bytes - 1, false), (bytes, true)] {
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(limit));
let mut reservation = MemoryConsumer::new("row indices").register(&pool);
let metrics = BuildProbeJoinMetrics::new(0, &ExecutionPlanMetricsSet::new());
let result = new_join_hashmap(rows, &mut reservation, &metrics);
if succeeds {
let map = result?;
assert_eq!(reservation.size(), bytes);
assert_eq!(metrics.build_mem_used.value(), bytes);
drop(map);
} else {
assert!(matches!(
result,
Err(datafusion_common::DataFusionError::ResourcesExhausted(_))
));
assert_eq!(reservation.size(), 0);
assert_eq!(metrics.build_mem_used.value(), 0);
}
drop(reservation);
assert_eq!(pool.reserved(), 0);
}
Ok(())
}
async fn build_mem_used(limit: usize, dynamic_filters: bool) -> Result<usize> {
let schema = Arc::new(Schema::new(vec![Field::new("k", DataType::Int64, false)]));
let batch = |keys: Vec<i64>| {
let column = Arc::new(Int64Array::from(keys)) as ArrayRef;
let batch = RecordBatch::try_new(Arc::clone(&schema), vec![column])?;
TestMemoryExec::try_new_exec(&[vec![batch]], Arc::clone(&schema), None)
};
let on = vec![(
Arc::new(Column::new_with_schema("k", &schema)?) as _,
Arc::new(Column::new_with_schema("k", &schema)?) as _,
)];
let build = batch((0..200).map(|i| i * 10_000).collect())?;
let probe = batch(vec![0, 500_000, 1_500_000])?;
let join = if dynamic_filters {
hash_join_with_dynamic_filter(build, probe, on, JoinType::Inner)?.0
} else {
join(
build,
probe,
on,
&JoinType::Inner,
NullEquality::NullEqualsNothing,
)?
};
let runtime = RuntimeEnvBuilder::new()
.with_memory_limit(limit, 1.0)
.build_arc()?;
let mut config = SessionConfig::new();
config
.options_mut()
.optimizer
.hash_join_inlist_pushdown_max_size = 0;
let task_ctx = Arc::new(
TaskContext::default()
.with_runtime(runtime)
.with_session_config(config),
);
let batches = common::collect(join.execute(0, task_ctx)?).await?;
assert_eq!(batches.iter().map(|b| b.num_rows()).sum::<usize>(), 3);
Ok(join
.metrics()
.unwrap()
.sum_by_name("build_mem_used")
.unwrap()
.as_usize())
}
#[tokio::test]
async fn pruning_bitmap_is_optional() -> Result<()> {
assert!(build_mem_used(1_000_000, false).await? < 100_000);
assert!(build_mem_used(1_000_000, true).await? > 100_000);
build_mem_used(100_000, true).await?;
Ok(())
}
#[derive(Debug)]
struct PartitionedTestExec {
cache: Arc<PlanProperties>,
}
impl PartitionedTestExec {
fn try_new(schema: SchemaRef, partitioning: Partitioning) -> Result<Self> {
Ok(Self {
cache: Arc::new(PlanProperties::new(
EquivalenceProperties::new(Arc::clone(&schema)),
partitioning,
EmissionType::Incremental,
Boundedness::Bounded,
)),
})
}
}
impl DisplayAs for PartitionedTestExec {
fn fmt_as(&self, _t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "PartitionedTestExec")
}
}
impl ExecutionPlan for PartitionedTestExec {
fn name(&self) -> &'static str {
"PartitionedTestExec"
}
fn properties(&self) -> &Arc<PlanProperties> {
&self.cache
}
fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
vec![]
}
fn apply_expressions(
&self,
_f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
) -> Result<TreeNodeRecursion> {
Ok(TreeNodeRecursion::Continue)
}
fn replace_children(
self: Arc<Self>,
_: Vec<Arc<dyn ExecutionPlan>>,
_: ReplaceChildrenOptions,
) -> Result<Arc<dyn ExecutionPlan>> {
Ok(self)
}
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 execute(
&self,
_partition: usize,
_context: Arc<TaskContext>,
) -> Result<SendableRecordBatchStream> {
unreachable!()
}
}
fn div_ceil(a: usize, b: usize) -> usize {
a.div_ceil(b)
}
#[template]
#[rstest]
fn hash_join_exec_configs(
#[values(8192, 10, 5, 2, 1)] batch_size: usize,
#[values(true, false)] use_perfect_hash_join_as_possible: bool,
) {
}
fn prepare_task_ctx(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) -> Arc<TaskContext> {
let mut session_config = SessionConfig::default().with_batch_size(batch_size);
let (small_build_threshold, min_key_density) =
if use_perfect_hash_join_as_possible {
(819200, 0.0)
} else {
(0, f64::INFINITY)
};
let execution = &mut session_config.options_mut().execution;
execution.perfect_hash_join_small_build_threshold = small_build_threshold;
execution.perfect_hash_join_min_key_density = min_key_density;
Arc::new(TaskContext::default().with_session_config(session_config))
}
fn build_table(
a: (&str, &Vec<i32>),
b: (&str, &Vec<i32>),
c: (&str, &Vec<i32>),
) -> Arc<dyn ExecutionPlan> {
let batch = build_table_i32(a, b, c);
let schema = batch.schema();
TestMemoryExec::try_new_exec(&[vec![batch]], schema, None).unwrap()
}
fn build_table_two_cols(
a: (&str, &Vec<Option<i32>>),
b: (&str, &Vec<Option<i32>>),
) -> Arc<dyn ExecutionPlan> {
let schema = Arc::new(Schema::new(vec![
Field::new(a.0, DataType::Int32, true),
Field::new(b.0, DataType::Int32, true),
]));
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(Int32Array::from(a.1.clone())),
Arc::new(Int32Array::from(b.1.clone())),
],
)
.unwrap();
TestMemoryExec::try_new_exec(&[vec![batch]], schema, None).unwrap()
}
fn build_table_dict_key(
key_name: &str,
dict_values: Vec<Option<i32>>,
keys: Vec<i32>,
dummy_name: &str,
dummy: Vec<Option<i32>>,
) -> Arc<dyn ExecutionPlan> {
let dict_type =
DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Int32));
let schema = Arc::new(Schema::new(vec![
Field::new(key_name, dict_type, true),
Field::new(dummy_name, DataType::Int32, true),
]));
let values = Int32Array::from(dict_values);
let key_array = Int32Array::from(keys);
let dict: ArrayRef = Arc::new(DictionaryArray::new(key_array, Arc::new(values)));
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![dict, Arc::new(Int32Array::from(dummy))],
)
.unwrap();
TestMemoryExec::try_new_exec(&[vec![batch]], schema, None).unwrap()
}
fn join(
left: Arc<dyn ExecutionPlan>,
right: Arc<dyn ExecutionPlan>,
on: JoinOn,
join_type: &JoinType,
null_equality: NullEquality,
) -> Result<HashJoinExec> {
HashJoinExec::try_new(
left,
right,
on,
None,
join_type,
None,
PartitionMode::CollectLeft,
null_equality,
false,
)
}
fn join_with_filter(
left: Arc<dyn ExecutionPlan>,
right: Arc<dyn ExecutionPlan>,
on: JoinOn,
filter: JoinFilter,
join_type: &JoinType,
null_equality: NullEquality,
) -> Result<HashJoinExec> {
HashJoinExec::try_new(
left,
right,
on,
Some(filter),
join_type,
None,
PartitionMode::CollectLeft,
null_equality,
false,
)
}
fn empty_build_with_probe_error_inputs()
-> (Arc<dyn ExecutionPlan>, Arc<dyn ExecutionPlan>, JoinOn) {
let left_batch =
build_table_i32(("a1", &vec![]), ("b1", &vec![]), ("c1", &vec![]));
let left_schema = left_batch.schema();
let left: Arc<dyn ExecutionPlan> = TestMemoryExec::try_new_exec(
&[vec![left_batch]],
Arc::clone(&left_schema),
None,
)
.unwrap();
let err = exec_err!("bad data error");
let right_batch =
build_table_i32(("a2", &vec![]), ("b1", &vec![]), ("c2", &vec![]));
let right_schema = right_batch.schema();
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left_schema).unwrap()) as _,
Arc::new(Column::new_with_schema("b1", &right_schema).unwrap()) as _,
)];
let right: Arc<dyn ExecutionPlan> = Arc::new(
MockExec::new(vec![Ok(right_batch), err], right_schema)
.with_use_task(false)
.with_unknown_statistics(),
);
(left, right, on)
}
async fn assert_empty_build_probe_behavior(
join_types: &[JoinType],
expect_probe_error: bool,
with_filter: bool,
) {
let (left, right, on) = empty_build_with_probe_error_inputs();
let filter = prepare_join_filter();
for join_type in join_types {
let join = if with_filter {
join_with_filter(
Arc::clone(&left),
Arc::clone(&right),
on.clone(),
filter.clone(),
join_type,
NullEquality::NullEqualsNothing,
)
.unwrap()
} else {
join(
Arc::clone(&left),
Arc::clone(&right),
on.clone(),
join_type,
NullEquality::NullEqualsNothing,
)
.unwrap()
};
let result = common::collect(
join.execute(0, Arc::new(TaskContext::default())).unwrap(),
)
.await;
if expect_probe_error {
let result_string = result.unwrap_err().to_string();
assert!(
result_string.contains("bad data error"),
"actual: {result_string}"
);
} else {
let batches = result.unwrap();
assert!(
batches.is_empty(),
"expected no output batches for {join_type}, got {batches:?}"
);
}
}
}
fn hash_join_with_dynamic_filter(
left: Arc<dyn ExecutionPlan>,
right: Arc<dyn ExecutionPlan>,
on: JoinOn,
join_type: JoinType,
) -> Result<(HashJoinExec, Arc<DynamicFilterPhysicalExpr>)> {
hash_join_with_dynamic_filter_and_mode(
left,
right,
on,
join_type,
PartitionMode::CollectLeft,
)
}
fn hash_join_with_dynamic_filter_and_mode(
left: Arc<dyn ExecutionPlan>,
right: Arc<dyn ExecutionPlan>,
on: JoinOn,
join_type: JoinType,
mode: PartitionMode,
) -> Result<(HashJoinExec, Arc<DynamicFilterPhysicalExpr>)> {
let dynamic_filter = HashJoinExec::create_dynamic_filter(&on);
let consumer: Arc<dyn PhysicalExpr> = Arc::clone(&dynamic_filter) as _;
let right = Arc::new(FilterExecBuilder::new(consumer, right).build()?);
let mut join = HashJoinExec::try_new(
left,
right,
on,
None,
&join_type,
None,
mode,
NullEquality::NullEqualsNothing,
false,
)?;
join.dynamic_filter = Some(HashJoinExecDynamicFilter {
filter: Arc::clone(&dynamic_filter),
build_accumulator: OnceLock::new(),
});
Ok((join, dynamic_filter))
}
async fn join_collect(
left: Arc<dyn ExecutionPlan>,
right: Arc<dyn ExecutionPlan>,
on: JoinOn,
join_type: &JoinType,
null_equality: NullEquality,
context: Arc<TaskContext>,
) -> Result<(Vec<String>, Vec<RecordBatch>, MetricsSet)> {
let join = join(left, right, on, join_type, null_equality)?;
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))
}
async fn partitioned_join_collect(
left: Arc<dyn ExecutionPlan>,
right: Arc<dyn ExecutionPlan>,
on: JoinOn,
join_type: &JoinType,
null_equality: NullEquality,
context: Arc<TaskContext>,
) -> Result<(Vec<String>, Vec<RecordBatch>, MetricsSet)> {
join_collect_with_partition_mode(
left,
right,
on,
join_type,
PartitionMode::Partitioned,
null_equality,
context,
)
.await
}
async fn join_collect_with_partition_mode(
left: Arc<dyn ExecutionPlan>,
right: Arc<dyn ExecutionPlan>,
on: JoinOn,
join_type: &JoinType,
partition_mode: PartitionMode,
null_equality: NullEquality,
context: Arc<TaskContext>,
) -> Result<(Vec<String>, Vec<RecordBatch>, MetricsSet)> {
let partition_count = 4;
let (left_expr, right_expr) = on
.iter()
.map(|(l, r)| (Arc::clone(l), Arc::clone(r)))
.unzip();
let left_repartitioned: Arc<dyn ExecutionPlan> = match partition_mode {
PartitionMode::CollectLeft => Arc::new(CoalescePartitionsExec::new(left)),
PartitionMode::Partitioned => Arc::new(RepartitionExec::try_new(
left,
Partitioning::Hash(left_expr, partition_count),
)?),
PartitionMode::Auto => {
return internal_err!("Unexpected PartitionMode::Auto in join tests");
}
};
let right_repartitioned: Arc<dyn ExecutionPlan> = match partition_mode {
PartitionMode::CollectLeft => {
let partition_column_name = right.schema().field(0).name().clone();
let partition_expr = vec![Arc::new(Column::new_with_schema(
&partition_column_name,
&right.schema(),
)?) as _];
Arc::new(RepartitionExec::try_new(
right,
Partitioning::Hash(partition_expr, partition_count),
)?) as _
}
PartitionMode::Partitioned => Arc::new(RepartitionExec::try_new(
right,
Partitioning::Hash(right_expr, partition_count),
)?),
PartitionMode::Auto => {
return internal_err!("Unexpected PartitionMode::Auto in join tests");
}
};
let join = HashJoinExec::try_new(
left_repartitioned,
right_repartitioned,
on,
None,
join_type,
None,
partition_mode,
null_equality,
false,
)?;
let columns = columns(&join.schema());
let mut batches = vec![];
for i in 0..partition_count {
let stream = join.execute(i, Arc::clone(&context))?;
let more_batches = common::collect(stream).await?;
batches.extend(
more_batches
.into_iter()
.filter(|b| b.num_rows() > 0)
.collect::<Vec<_>>(),
);
}
let metrics = join.metrics().unwrap();
Ok((columns, batches, metrics))
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn join_inner_one(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let left = build_table(
("a1", &vec![1, 2, 3]),
("b1", &vec![4, 5, 5]), ("c1", &vec![7, 8, 9]),
);
let right = build_table(
("a2", &vec![10, 20, 30]),
("b1", &vec![4, 5, 6]),
("c2", &vec![70, 80, 90]),
);
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
)];
let (columns, batches, metrics) = join_collect(
Arc::clone(&left),
Arc::clone(&right),
on.clone(),
&JoinType::Inner,
NullEquality::NullEqualsNothing,
task_ctx,
)
.await?;
assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b1", "c2"]);
allow_duplicates! {
assert_snapshot!(batches_to_string(&batches), @r"
+----+----+----+----+----+----+
| a1 | b1 | c1 | a2 | b1 | c2 |
+----+----+----+----+----+----+
| 1 | 4 | 7 | 10 | 4 | 70 |
| 2 | 5 | 8 | 20 | 5 | 80 |
| 3 | 5 | 9 | 20 | 5 | 80 |
+----+----+----+----+----+----+
");
}
assert_join_metrics!(metrics, 3);
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn partitioned_join_inner_one(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let left = build_table(
("a1", &vec![1, 2, 3]),
("b1", &vec![4, 5, 5]), ("c1", &vec![7, 8, 9]),
);
let right = build_table(
("a2", &vec![10, 20, 30]),
("b1", &vec![4, 5, 6]),
("c2", &vec![70, 80, 90]),
);
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
)];
let (columns, batches, metrics) = partitioned_join_collect(
Arc::clone(&left),
Arc::clone(&right),
on.clone(),
&JoinType::Inner,
NullEquality::NullEqualsNothing,
task_ctx,
)
.await?;
assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b1", "c2"]);
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+----+----+----+----+
| a1 | b1 | c1 | a2 | b1 | c2 |
+----+----+----+----+----+----+
| 1 | 4 | 7 | 10 | 4 | 70 |
| 2 | 5 | 8 | 20 | 5 | 80 |
| 3 | 5 | 9 | 20 | 5 | 80 |
+----+----+----+----+----+----+
");
}
assert_join_metrics!(metrics, 3);
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
Ok(())
}
#[rstest]
#[tokio::test]
async fn join_inner_multi_key_float_zero_and_nulls_across_chunks(
#[values(8192, 3, 2, 1)] batch_size: usize,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, false);
let schema = |suffix: &str| {
Arc::new(Schema::new(vec![
Field::new(format!("k{suffix}"), DataType::Int32, true),
Field::new(format!("f{suffix}"), DataType::Float64, true),
Field::new(format!("v{suffix}"), DataType::Int32, true),
]))
};
let table = |suffix: &str,
k: Vec<Option<i32>>,
f: Vec<Option<f64>>,
v: Vec<i32>|
-> Result<Arc<dyn ExecutionPlan>> {
let schema = schema(suffix);
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(Int32Array::from(k)),
Arc::new(Float64Array::from(f)),
Arc::new(Int32Array::from(v)),
],
)?;
TestMemoryExec::try_new_exec(&[vec![batch]], schema, None)
.map(|exec| exec as _)
};
let left = table(
"1",
vec![Some(1), Some(1), Some(1), Some(2), Some(1)],
vec![Some(-0.0), Some(0.0), None, Some(1.5), Some(-0.0)],
vec![10, 11, 12, 13, 14],
)?;
let right = table(
"2",
vec![Some(1), Some(1), Some(2), Some(1)],
vec![Some(0.0), None, Some(1.5), Some(-0.0)],
vec![100, 101, 102, 103],
)?;
let on = vec![
(
Arc::new(Column::new_with_schema("k1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("k2", &right.schema())?) as _,
),
(
Arc::new(Column::new_with_schema("f1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("f2", &right.schema())?) as _,
),
];
let (_, batches, _) = join_collect(
left,
right,
on,
&JoinType::Inner,
NullEquality::NullEqualsNothing,
task_ctx,
)
.await?;
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+------+----+----+------+-----+
| k1 | f1 | v1 | k2 | f2 | v2 |
+----+------+----+----+------+-----+
| 1 | -0.0 | 10 | 1 | -0.0 | 103 |
| 1 | -0.0 | 10 | 1 | 0.0 | 100 |
| 1 | -0.0 | 14 | 1 | -0.0 | 103 |
| 1 | -0.0 | 14 | 1 | 0.0 | 100 |
| 1 | 0.0 | 11 | 1 | -0.0 | 103 |
| 1 | 0.0 | 11 | 1 | 0.0 | 100 |
| 2 | 1.5 | 13 | 2 | 1.5 | 102 |
+----+------+----+----+------+-----+
");
}
Ok(())
}
async fn collect_float_build(
keys: ArrayRef,
) -> Result<(JoinLeftData, BuildProbeJoinMetrics)> {
let schema = Arc::new(Schema::new(vec![Field::new(
"f",
keys.data_type().clone(),
true,
)]));
let batch = RecordBatch::try_new(Arc::clone(&schema), vec![keys])?;
let exec = TestMemoryExec::try_new_exec(&[vec![batch]], schema, None)?;
let stream = exec.execute(0, Arc::new(TaskContext::default()))?;
let pool: Arc<dyn MemoryPool> = Arc::new(UnboundedMemoryPool::default());
let metrics = BuildProbeJoinMetrics::new(0, &ExecutionPlanMetricsSet::new());
let on_left: Vec<PhysicalExprRef> = vec![Arc::new(Column::new("f", 0))];
let left_data = collect_left_input(
RandomState::with_seed(0),
stream,
on_left,
metrics.clone(),
MemoryConsumer::new("HashJoinInput").register(&pool),
false,
1,
false,
Arc::new(ConfigOptions::default()),
NullEquality::NullEqualsNothing,
None,
Count::new(),
BuildMode::Ordinary,
)
.await?;
Ok((left_data, metrics))
}
#[tokio::test]
async fn collect_left_input_stores_normalized_float_keys() -> Result<()> {
let (with_neg_zero, neg_metrics) =
collect_float_build(Arc::new(Float64Array::from(vec![-0.0, 1.0]))).await?;
let stored = with_neg_zero.values()[0].as_primitive::<Float64Type>();
assert_eq!(stored.value(0).to_bits(), 0.0_f64.to_bits());
assert_eq!(stored.value(1), 1.0);
let original = with_neg_zero
.batch()
.column(0)
.as_primitive::<Float64Type>();
assert_eq!(original.value(0).to_bits(), (-0.0_f64).to_bits());
let (without_neg_zero, pos_metrics) =
collect_float_build(Arc::new(Float64Array::from(vec![0.0, 1.0]))).await?;
assert!(Arc::ptr_eq(
&without_neg_zero.values()[0],
without_neg_zero.batch().column(0)
));
assert_eq!(
neg_metrics.build_mem_used.value(),
pos_metrics.build_mem_used.value() + stored.values().inner().capacity()
);
let (f32_build, _) =
collect_float_build(Arc::new(Float32Array::from(vec![-0.0_f32, 1.0])))
.await?;
let stored = f32_build.values()[0].as_primitive::<Float32Type>();
assert_eq!(stored.value(0).to_bits(), 0.0_f32.to_bits());
let original = f32_build.batch().column(0).as_primitive::<Float32Type>();
assert_eq!(original.value(0).to_bits(), (-0.0_f32).to_bits());
Ok(())
}
#[rstest]
#[tokio::test]
async fn join_inner_single_float_key_negative_zero(
#[values(8192, 1)] batch_size: usize,
#[values(NullEquality::NullEqualsNothing, NullEquality::NullEqualsNull)]
null_equality: NullEquality,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, false);
let table = |suffix: &str,
f: Vec<Option<f64>>,
v: Vec<i32>|
-> Result<Arc<dyn ExecutionPlan>> {
let schema = Arc::new(Schema::new(vec![
Field::new(format!("f{suffix}"), DataType::Float64, true),
Field::new(format!("v{suffix}"), DataType::Int32, true),
]));
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(Float64Array::from(f)),
Arc::new(Int32Array::from(v)),
],
)?;
TestMemoryExec::try_new_exec(&[vec![batch]], schema, None)
.map(|exec| exec as _)
};
let left = table(
"1",
vec![Some(-0.0), Some(0.0), Some(1.5), None],
vec![10, 11, 12, 13],
)?;
let right = table(
"2",
vec![Some(0.0), Some(-0.0), Some(1.5), None],
vec![20, 21, 22, 23],
)?;
let on = vec![(
Arc::new(Column::new_with_schema("f1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("f2", &right.schema())?) as _,
)];
let (_, batches, _) =
join_collect(left, right, on, &JoinType::Inner, null_equality, task_ctx)
.await?;
allow_duplicates! {
match null_equality {
NullEquality::NullEqualsNothing => {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+------+----+------+----+
| f1 | v1 | f2 | v2 |
+------+----+------+----+
| -0.0 | 10 | -0.0 | 21 |
| -0.0 | 10 | 0.0 | 20 |
| 0.0 | 11 | -0.0 | 21 |
| 0.0 | 11 | 0.0 | 20 |
| 1.5 | 12 | 1.5 | 22 |
+------+----+------+----+
");
}
NullEquality::NullEqualsNull => {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+------+----+------+----+
| f1 | v1 | f2 | v2 |
+------+----+------+----+
| | 13 | | 23 |
| -0.0 | 10 | -0.0 | 21 |
| -0.0 | 10 | 0.0 | 20 |
| 0.0 | 11 | -0.0 | 21 |
| 0.0 | 11 | 0.0 | 20 |
| 1.5 | 12 | 1.5 | 22 |
+------+----+------+----+
");
}
}
}
Ok(())
}
#[rstest]
#[tokio::test]
async fn join_inner_multi_key_across_probe_batches(
#[values(8192, 1)] batch_size: usize,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, false);
let left = build_table_two_cols(
("a1", &vec![Some(1), Some(1)]),
("b1", &vec![Some(10), Some(20)]),
);
let right_schema = Arc::new(Schema::new(vec![
Field::new("a2", DataType::Int32, true),
Field::new("b2", DataType::Int32, true),
]));
let probe_batch = |b: i32| {
RecordBatch::try_new(
Arc::clone(&right_schema),
vec![
Arc::new(Int32Array::from(vec![1])),
Arc::new(Int32Array::from(vec![b])),
],
)
};
let right = TestMemoryExec::try_new_exec(
&[vec![probe_batch(10)?, probe_batch(20)?]],
Arc::clone(&right_schema),
None,
)?;
let on = vec![
(
Arc::new(Column::new_with_schema("a1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("a2", &right.schema())?) as _,
),
(
Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
),
];
let (_, batches, _) = join_collect(
left,
right,
on,
&JoinType::Inner,
NullEquality::NullEqualsNothing,
task_ctx,
)
.await?;
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+----+----+
| a1 | b1 | a2 | b2 |
+----+----+----+----+
| 1 | 10 | 1 | 10 |
| 1 | 20 | 1 | 20 |
+----+----+----+----+
");
}
Ok(())
}
#[rstest]
#[tokio::test]
async fn join_inner_array_map_across_chunks(
#[values(8192, 3, 2, 1)] batch_size: usize,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, true);
let left = build_table(
("a1", &vec![1, 2, 3, 4, 5, 6]),
("b1", &vec![1, 1, 1, 2, 2, 3]),
("c1", &vec![7, 8, 9, 10, 11, 12]),
);
let right = build_table(
("a2", &vec![10, 20, 30, 40]),
("b1", &vec![1, 2, 3, 4]),
("c2", &vec![70, 80, 90, 100]),
);
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
)];
let (_, batches, metrics) = join_collect(
left,
right,
on,
&JoinType::Inner,
NullEquality::NullEqualsNothing,
task_ctx,
)
.await?;
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+----+----+----+----+
| a1 | b1 | c1 | a2 | b1 | c2 |
+----+----+----+----+----+----+
| 1 | 1 | 7 | 10 | 1 | 70 |
| 2 | 1 | 8 | 10 | 1 | 70 |
| 3 | 1 | 9 | 10 | 1 | 70 |
| 4 | 2 | 10 | 20 | 2 | 80 |
| 5 | 2 | 11 | 20 | 2 | 80 |
| 6 | 3 | 12 | 30 | 3 | 90 |
+----+----+----+----+----+----+
");
}
assert_join_metrics!(metrics, 6);
assert_phj_used(&metrics, true);
Ok(())
}
#[tokio::test]
async fn join_inner_one_no_shared_column_names() -> Result<()> {
let task_ctx = Arc::new(TaskContext::default());
let left = build_table(
("a1", &vec![1, 2, 3]),
("b1", &vec![4, 5, 5]), ("c1", &vec![7, 8, 9]),
);
let right = build_table(
("a2", &vec![10, 20, 30]),
("b2", &vec![4, 5, 6]),
("c2", &vec![70, 80, 90]),
);
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
)];
let (columns, batches, metrics) = join_collect(
left,
right,
on,
&JoinType::Inner,
NullEquality::NullEqualsNothing,
task_ctx,
)
.await?;
assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b2", "c2"]);
allow_duplicates! {
assert_snapshot!(batches_to_string(&batches), @r"
+----+----+----+----+----+----+
| a1 | b1 | c1 | a2 | b2 | c2 |
+----+----+----+----+----+----+
| 1 | 4 | 7 | 10 | 4 | 70 |
| 2 | 5 | 8 | 20 | 5 | 80 |
| 3 | 5 | 9 | 20 | 5 | 80 |
+----+----+----+----+----+----+
");
}
assert_join_metrics!(metrics, 3);
Ok(())
}
#[tokio::test]
async fn join_inner_one_randomly_ordered() -> Result<()> {
let task_ctx = Arc::new(TaskContext::default());
let left = build_table(
("a1", &vec![0, 3, 2, 1]),
("b1", &vec![4, 5, 5, 4]),
("c1", &vec![6, 9, 8, 7]),
);
let right = build_table(
("a2", &vec![20, 30, 10]),
("b2", &vec![5, 6, 4]),
("c2", &vec![80, 90, 70]),
);
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
)];
let (columns, batches, metrics) = join_collect(
left,
right,
on,
&JoinType::Inner,
NullEquality::NullEqualsNothing,
task_ctx,
)
.await?;
assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b2", "c2"]);
allow_duplicates! {
assert_snapshot!(batches_to_string(&batches), @r"
+----+----+----+----+----+----+
| a1 | b1 | c1 | a2 | b2 | c2 |
+----+----+----+----+----+----+
| 3 | 5 | 9 | 20 | 5 | 80 |
| 2 | 5 | 8 | 20 | 5 | 80 |
| 0 | 4 | 6 | 10 | 4 | 70 |
| 1 | 4 | 7 | 10 | 4 | 70 |
+----+----+----+----+----+----+
");
}
assert_join_metrics!(metrics, 4);
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn join_inner_two(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let left = build_table(
("a1", &vec![1, 2, 2]),
("b2", &vec![1, 2, 2]),
("c1", &vec![7, 8, 9]),
);
let right = build_table(
("a1", &vec![1, 2, 3]),
("b2", &vec![1, 2, 2]),
("c2", &vec![70, 80, 90]),
);
let on = vec![
(
Arc::new(Column::new_with_schema("a1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("a1", &right.schema())?) as _,
),
(
Arc::new(Column::new_with_schema("b2", &left.schema())?) as _,
Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
),
];
let (columns, batches, metrics) = join_collect(
left,
right,
on,
&JoinType::Inner,
NullEquality::NullEqualsNothing,
task_ctx,
)
.await?;
assert_eq!(columns, vec!["a1", "b2", "c1", "a1", "b2", "c2"]);
let expected_batch_count = if cfg!(not(feature = "force_hash_collisions")) {
let mut expected_batch_count = div_ceil(3, batch_size);
if batch_size == 1 {
expected_batch_count += 1;
}
expected_batch_count
} else {
div_ceil(9, batch_size)
};
assert!(
batches.len() <= expected_batch_count,
"expected at most {expected_batch_count} batches, got {}",
batches.len()
);
allow_duplicates! {
assert_snapshot!(batches_to_string(&batches), @r"
+----+----+----+----+----+----+
| a1 | b2 | c1 | a1 | b2 | c2 |
+----+----+----+----+----+----+
| 1 | 1 | 7 | 1 | 1 | 70 |
| 2 | 2 | 8 | 2 | 2 | 80 |
| 2 | 2 | 9 | 2 | 2 | 80 |
+----+----+----+----+----+----+
");
}
assert_join_metrics!(metrics, 3);
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn join_inner_one_two_parts_left(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let batch1 = build_table_i32(
("a1", &vec![1, 2]),
("b2", &vec![1, 2]),
("c1", &vec![7, 8]),
);
let batch2 =
build_table_i32(("a1", &vec![2]), ("b2", &vec![2]), ("c1", &vec![9]));
let schema = batch1.schema();
let left =
TestMemoryExec::try_new_exec(&[vec![batch1], vec![batch2]], schema, None)
.unwrap();
let left = Arc::new(CoalescePartitionsExec::new(left));
let right = build_table(
("a1", &vec![1, 2, 3]),
("b2", &vec![1, 2, 2]),
("c2", &vec![70, 80, 90]),
);
let on = vec![
(
Arc::new(Column::new_with_schema("a1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("a1", &right.schema())?) as _,
),
(
Arc::new(Column::new_with_schema("b2", &left.schema())?) as _,
Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
),
];
let (columns, batches, metrics) = join_collect(
left,
right,
on,
&JoinType::Inner,
NullEquality::NullEqualsNothing,
task_ctx,
)
.await?;
assert_eq!(columns, vec!["a1", "b2", "c1", "a1", "b2", "c2"]);
let expected_batch_count = if cfg!(not(feature = "force_hash_collisions")) {
let mut expected_batch_count = div_ceil(3, batch_size);
if batch_size == 1 {
expected_batch_count += 1;
}
expected_batch_count
} else {
div_ceil(9, batch_size)
};
assert!(
batches.len() <= expected_batch_count,
"expected at most {expected_batch_count} batches, got {}",
batches.len()
);
allow_duplicates! {
assert_snapshot!(batches_to_string(&batches), @r"
+----+----+----+----+----+----+
| a1 | b2 | c1 | a1 | b2 | c2 |
+----+----+----+----+----+----+
| 1 | 1 | 7 | 1 | 1 | 70 |
| 2 | 2 | 8 | 2 | 2 | 80 |
| 2 | 2 | 9 | 2 | 2 | 80 |
+----+----+----+----+----+----+
");
}
assert_join_metrics!(metrics, 3);
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn join_inner_one_two_parts_left_randomly_ordered(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let batch1 = build_table_i32(
("a1", &vec![0, 3]),
("b1", &vec![4, 5]),
("c1", &vec![6, 9]),
);
let batch2 = build_table_i32(
("a1", &vec![2, 1]),
("b1", &vec![5, 4]),
("c1", &vec![8, 7]),
);
let schema = batch1.schema();
let left =
TestMemoryExec::try_new_exec(&[vec![batch1], vec![batch2]], schema, None)
.unwrap();
let left = Arc::new(CoalescePartitionsExec::new(left));
let right = build_table(
("a2", &vec![20, 30, 10]),
("b2", &vec![5, 6, 4]),
("c2", &vec![80, 90, 70]),
);
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
)];
let (columns, batches, metrics) = join_collect(
left,
right,
on,
&JoinType::Inner,
NullEquality::NullEqualsNothing,
task_ctx,
)
.await?;
assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b2", "c2"]);
allow_duplicates! {
assert_snapshot!(batches_to_string(&batches), @r"
+----+----+----+----+----+----+
| a1 | b1 | c1 | a2 | b2 | c2 |
+----+----+----+----+----+----+
| 3 | 5 | 9 | 20 | 5 | 80 |
| 2 | 5 | 8 | 20 | 5 | 80 |
| 0 | 4 | 6 | 10 | 4 | 70 |
| 1 | 4 | 7 | 10 | 4 | 70 |
+----+----+----+----+----+----+
");
}
assert_join_metrics!(metrics, 4);
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn join_inner_one_two_parts_right(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let left = build_table(
("a1", &vec![1, 2, 3]),
("b1", &vec![4, 5, 5]), ("c1", &vec![7, 8, 9]),
);
let batch1 = build_table_i32(
("a2", &vec![10, 20]),
("b1", &vec![4, 6]),
("c2", &vec![70, 80]),
);
let batch2 =
build_table_i32(("a2", &vec![30]), ("b1", &vec![5]), ("c2", &vec![90]));
let schema = batch1.schema();
let right =
TestMemoryExec::try_new_exec(&[vec![batch1], vec![batch2]], schema, None)
.unwrap();
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
)];
let join = join(
left,
right,
on,
&JoinType::Inner,
NullEquality::NullEqualsNothing,
)?;
let columns = columns(&join.schema());
assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b1", "c2"]);
let stream = join.execute(0, Arc::clone(&task_ctx))?;
let batches = common::collect(stream).await?;
let expected_batch_count = if cfg!(not(feature = "force_hash_collisions")) {
let mut expected_batch_count = div_ceil(1, batch_size);
if batch_size == 1 {
expected_batch_count += 1;
}
expected_batch_count
} else {
div_ceil(6, batch_size)
};
assert!(
batches.len() <= expected_batch_count,
"expected at most {expected_batch_count} batches, got {}",
batches.len()
);
allow_duplicates! {
assert_snapshot!(batches_to_string(&batches), @r"
+----+----+----+----+----+----+
| a1 | b1 | c1 | a2 | b1 | c2 |
+----+----+----+----+----+----+
| 1 | 4 | 7 | 10 | 4 | 70 |
+----+----+----+----+----+----+
");
}
let stream = join.execute(1, Arc::clone(&task_ctx))?;
let batches = common::collect(stream).await?;
let expected_batch_count = if cfg!(not(feature = "force_hash_collisions")) {
div_ceil(2, batch_size)
} else {
div_ceil(3, batch_size)
};
assert!(
batches.len() <= expected_batch_count,
"expected at most {expected_batch_count} batches, got {}",
batches.len()
);
allow_duplicates! {
assert_snapshot!(batches_to_string(&batches), @r"
+----+----+----+----+----+----+
| a1 | b1 | c1 | a2 | b1 | c2 |
+----+----+----+----+----+----+
| 2 | 5 | 8 | 30 | 5 | 90 |
| 3 | 5 | 9 | 30 | 5 | 90 |
+----+----+----+----+----+----+
");
}
let metrics = join.metrics().unwrap();
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
Ok(())
}
fn build_table_two_batches(
a: (&str, &Vec<i32>),
b: (&str, &Vec<i32>),
c: (&str, &Vec<i32>),
) -> Arc<dyn ExecutionPlan> {
let batch = build_table_i32(a, b, c);
let schema = batch.schema();
TestMemoryExec::try_new_exec(&[vec![batch.clone(), batch]], schema, None).unwrap()
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn join_left_anti_keeps_build_order_across_batches(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let batch1 = build_table_i32(
("a1", &vec![1, 2]),
("b1", &vec![10, 20]),
("c1", &vec![7, 8]),
);
let batch2 = build_table_i32(
("a1", &vec![3, 4]),
("b1", &vec![3000, 4000]),
("c1", &vec![9, 10]),
);
let schema = batch1.schema();
let left =
TestMemoryExec::try_new_exec(&[vec![batch1, batch2]], schema, None).unwrap();
let right = build_table(("a2", &vec![1]), ("b1", &vec![1]), ("c2", &vec![1]));
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
)];
let (columns, batches, metrics) = join_collect(
left,
right,
on,
&JoinType::LeftAnti,
NullEquality::NullEqualsNothing,
task_ctx,
)
.await?;
assert_eq!(columns, vec!["a1", "b1", "c1"]);
allow_duplicates! {
assert_snapshot!(batches_to_string(&batches), @r"
+----+------+----+
| a1 | b1 | c1 |
+----+------+----+
| 1 | 10 | 7 |
| 2 | 20 | 8 |
| 3 | 3000 | 9 |
| 4 | 4000 | 10 |
+----+------+----+
");
}
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn join_probe_metrics_count_each_probe_row_once(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let left = build_table(
("a1", &vec![1, 2, 3]),
("b1", &vec![2, 2, 2]),
("c1", &vec![3, 4, 5]),
);
let right = build_table(
("a2", &vec![10, 20, 30]),
("b1", &vec![2, 2, 2]),
("c2", &vec![30, 40, 50]),
);
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
)];
let (columns, batches, metrics) = join_collect(
Arc::clone(&left),
Arc::clone(&right),
on.clone(),
&JoinType::Inner,
NullEquality::NullEqualsNothing,
task_ctx,
)
.await?;
assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b1", "c2"]);
allow_duplicates! {
assert_snapshot!(batches_to_string(&batches), @r"
+----+----+----+----+----+----+
| a1 | b1 | c1 | a2 | b1 | c2 |
+----+----+----+----+----+----+
| 1 | 2 | 3 | 10 | 2 | 30 |
| 2 | 2 | 4 | 10 | 2 | 30 |
| 3 | 2 | 5 | 10 | 2 | 30 |
| 1 | 2 | 3 | 20 | 2 | 40 |
| 2 | 2 | 4 | 20 | 2 | 40 |
| 3 | 2 | 5 | 20 | 2 | 40 |
| 1 | 2 | 3 | 30 | 2 | 50 |
| 2 | 2 | 4 | 30 | 2 | 50 |
| 3 | 2 | 5 | 30 | 2 | 50 |
+----+----+----+----+----+----+
");
}
assert_join_metrics!(metrics, 9);
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
assert_ratio_metric(&metrics, "probe_hit_rate", 3, 3);
assert_ratio_metric(&metrics, "avg_fanout", 9, 3);
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn join_probe_metrics_count_probe_row_starting_new_chunk(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let left = build_table(
("a1", &vec![1, 2, 3]),
("b1", &vec![4, 5, 6]),
("c1", &vec![7, 8, 9]),
);
let right = build_table(
("a2", &vec![10, 20, 25, 30]),
("b1", &vec![4, 4, 4, 40]),
("c2", &vec![70, 80, 85, 90]),
);
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
)];
let (columns, batches, metrics) = join_collect(
Arc::clone(&left),
Arc::clone(&right),
on.clone(),
&JoinType::Inner,
NullEquality::NullEqualsNothing,
task_ctx,
)
.await?;
assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b1", "c2"]);
allow_duplicates! {
assert_snapshot!(batches_to_string(&batches), @"
+----+----+----+----+----+----+
| a1 | b1 | c1 | a2 | b1 | c2 |
+----+----+----+----+----+----+
| 1 | 4 | 7 | 10 | 4 | 70 |
| 1 | 4 | 7 | 20 | 4 | 80 |
| 1 | 4 | 7 | 25 | 4 | 85 |
+----+----+----+----+----+----+
");
}
assert_join_metrics!(metrics, 3);
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
assert_ratio_metric(&metrics, "probe_hit_rate", 3, 4);
assert_ratio_metric(&metrics, "avg_fanout", 3, 3);
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn join_left_multi_batch(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let left = build_table(
("a1", &vec![1, 2, 3]),
("b1", &vec![4, 5, 7]), ("c1", &vec![7, 8, 9]),
);
let right = build_table_two_batches(
("a2", &vec![10, 20, 30]),
("b1", &vec![4, 5, 6]),
("c2", &vec![70, 80, 90]),
);
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema()).unwrap()) as _,
Arc::new(Column::new_with_schema("b1", &right.schema()).unwrap()) as _,
)];
let join = join(
Arc::clone(&left),
Arc::clone(&right),
on.clone(),
&JoinType::Left,
NullEquality::NullEqualsNothing,
)
.unwrap();
let columns = columns(&join.schema());
assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b1", "c2"]);
let (_, batches, metrics) = join_collect(
Arc::clone(&left),
Arc::clone(&right),
on.clone(),
&JoinType::Left,
NullEquality::NullEqualsNothing,
task_ctx,
)
.await?;
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+----+----+----+----+
| a1 | b1 | c1 | a2 | b1 | c2 |
+----+----+----+----+----+----+
| 1 | 4 | 7 | 10 | 4 | 70 |
| 1 | 4 | 7 | 10 | 4 | 70 |
| 2 | 5 | 8 | 20 | 5 | 80 |
| 2 | 5 | 8 | 20 | 5 | 80 |
| 3 | 7 | 9 | | | |
+----+----+----+----+----+----+
");
}
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
return Ok(());
}
fn final_build_rows_inputs(
num_build_rows: i32,
matched_keys: &[i32],
) -> (Arc<dyn ExecutionPlan>, Arc<dyn ExecutionPlan>, JoinOn) {
let build_keys: Vec<i32> = (0..num_build_rows).collect();
let probe_keys = matched_keys.to_vec();
let left = build_table(
("a1", &build_keys),
("b1", &build_keys),
("c1", &build_keys),
);
let right = build_table(
("a2", &probe_keys),
("b2", &probe_keys),
("c2", &probe_keys),
);
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema()).unwrap()) as _,
Arc::new(Column::new_with_schema("b2", &right.schema()).unwrap()) as _,
)];
(left, right, on)
}
fn build_rows_with_match_flag(batches: &[RecordBatch]) -> Vec<(i32, Option<bool>)> {
let mut rows = vec![];
for batch in batches {
let a1 = batch
.column_by_name("a1")
.unwrap()
.as_primitive::<Int32Type>();
let matched: Vec<Option<bool>> = match batch.column_by_name("mark") {
Some(mark) => mark.as_boolean().iter().collect(),
None => match batch.column_by_name("a2") {
Some(a2) => (0..a2.len()).map(|i| Some(a2.is_valid(i))).collect(),
None => vec![None; batch.num_rows()],
},
};
rows.extend(a1.values().iter().copied().zip(matched));
}
rows.sort_unstable();
rows
}
fn expected_final_build_rows(
join_type: JoinType,
num_build_rows: i32,
matched_keys: &[i32],
) -> Vec<(i32, Option<bool>)> {
(0..num_build_rows)
.filter_map(|key| {
let matched = matched_keys.contains(&key);
match join_type {
JoinType::LeftSemi => matched.then_some((key, None)),
JoinType::LeftAnti => (!matched).then_some((key, None)),
_ => Some((key, Some(matched))),
}
})
.collect()
}
#[rstest]
#[tokio::test]
async fn join_emits_final_build_rows_in_batch_size_chunks(
#[values(
JoinType::Left,
JoinType::Full,
JoinType::LeftAnti,
JoinType::LeftSemi,
JoinType::LeftMark
)]
join_type: JoinType,
#[values(1, 7, 8192)] batch_size: usize,
#[values(true, false)] use_perfect_hash_join_as_possible: bool,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let num_build_rows = 100;
let matched_keys = [3, 50, 97];
let (left, right, on) = final_build_rows_inputs(num_build_rows, &matched_keys);
let (_, batches, metrics) = join_collect(
left,
right,
on,
&join_type,
NullEquality::NullEqualsNothing,
task_ctx,
)
.await?;
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
let expected =
expected_final_build_rows(join_type, num_build_rows, &matched_keys);
assert_eq!(build_rows_with_match_flag(&batches), expected);
for batch in &batches {
assert!(
batch.num_rows() <= batch_size,
"{join_type} join emitted a batch of {} rows with batch_size {batch_size}",
batch.num_rows()
);
}
assert!(
batches.len() >= expected.len().div_ceil(batch_size),
"{join_type} join emitted {} batches for {} rows with batch_size {batch_size}",
batches.len(),
expected.len()
);
Ok(())
}
#[rstest]
#[tokio::test]
async fn join_fetch_stops_final_build_rows_mid_chunk(
#[values(JoinType::Left, JoinType::LeftAnti, JoinType::LeftMark)]
join_type: JoinType,
) -> Result<()> {
let batch_size = 7;
let fetch = 20;
let num_build_rows = 100;
let matched_keys = [3, 50, 97];
let task_ctx = prepare_task_ctx(batch_size, false);
let (left, right, on) = final_build_rows_inputs(num_build_rows, &matched_keys);
let join = HashJoinExecBuilder::new(left, right, on, join_type)
.with_partition_mode(PartitionMode::CollectLeft)
.with_fetch(Some(fetch))
.build()?;
let batches = common::collect(join.execute(0, task_ctx)?).await?;
let num_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
assert_eq!(num_rows, fetch);
for batch in &batches {
assert!(batch.num_rows() <= batch_size);
}
let expected =
expected_final_build_rows(join_type, num_build_rows, &matched_keys);
for row in build_rows_with_match_flag(&batches) {
assert!(expected.contains(&row), "unexpected output row {row:?}");
}
Ok(())
}
#[tokio::test]
async fn join_fetch_statistics_count_every_output_partition() -> Result<()> {
let values: Vec<i32> = (0..100).collect();
let left = build_table(("a1", &values), ("b1", &values), ("c1", &values));
let batch = build_table_i32(("a2", &values), ("b2", &values), ("c2", &values));
let schema = batch.schema();
let right = TestMemoryExec::try_new_exec(&vec![vec![batch]; 4], schema, None)?;
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
)];
let join: Arc<dyn ExecutionPlan> = Arc::new(
HashJoinExecBuilder::new(left, right, on, JoinType::Inner)
.with_partition_mode(PartitionMode::CollectLeft)
.with_fetch(Some(10))
.build()?,
);
assert_eq!(join.properties().output_partitioning().partition_count(), 4);
let emitted: usize =
crate::collect(Arc::clone(&join), prepare_task_ctx(8192, false))
.await?
.iter()
.map(|batch| batch.num_rows())
.sum();
assert_eq!(emitted, 40);
let num_rows = |partition| {
StatisticsContext::new()
.compute(
join.as_ref(),
&StatisticsArgs::new().with_partition(partition),
)
.map(|stats| stats.num_rows)
};
assert_eq!(num_rows(None)?, Precision::Inexact(40));
assert_eq!(num_rows(Some(0))?, Precision::Inexact(10));
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn join_full_multi_batch(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let left = build_table(
("a1", &vec![1, 2, 3]),
("b1", &vec![4, 5, 7]), ("c1", &vec![7, 8, 9]),
);
let right = build_table_two_batches(
("a2", &vec![10, 20, 30]),
("b2", &vec![4, 5, 6]),
("c2", &vec![70, 80, 90]),
);
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema()).unwrap()) as _,
Arc::new(Column::new_with_schema("b2", &right.schema()).unwrap()) as _,
)];
let join = join(
left,
right,
on,
&JoinType::Full,
NullEquality::NullEqualsNothing,
)
.unwrap();
let columns = columns(&join.schema());
assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b2", "c2"]);
let stream = join.execute(0, task_ctx).unwrap();
let batches = common::collect(stream).await.unwrap();
let metrics = join.metrics().unwrap();
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+----+----+----+----+
| a1 | b1 | c1 | a2 | b2 | c2 |
+----+----+----+----+----+----+
| | | | 30 | 6 | 90 |
| | | | 30 | 6 | 90 |
| 1 | 4 | 7 | 10 | 4 | 70 |
| 1 | 4 | 7 | 10 | 4 | 70 |
| 2 | 5 | 8 | 20 | 5 | 80 |
| 2 | 5 | 8 | 20 | 5 | 80 |
| 3 | 7 | 9 | | | |
+----+----+----+----+----+----+
");
}
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn join_left_empty_right(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let left = build_table(
("a1", &vec![1, 2, 3]),
("b1", &vec![4, 5, 7]),
("c1", &vec![7, 8, 9]),
);
let right = build_table_i32(("a2", &vec![]), ("b1", &vec![]), ("c2", &vec![]));
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema()).unwrap()) as _,
Arc::new(Column::new_with_schema("b1", &right.schema()).unwrap()) as _,
)];
let schema = right.schema();
let right = TestMemoryExec::try_new_exec(&[vec![right]], schema, None).unwrap();
let join = join(
left,
right,
on,
&JoinType::Left,
NullEquality::NullEqualsNothing,
)
.unwrap();
let columns = columns(&join.schema());
assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b1", "c2"]);
let stream = join.execute(0, task_ctx).unwrap();
let batches = common::collect(stream).await.unwrap();
let metrics = join.metrics().unwrap();
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+----+----+----+----+
| a1 | b1 | c1 | a2 | b1 | c2 |
+----+----+----+----+----+----+
| 1 | 4 | 7 | | | |
| 2 | 5 | 8 | | | |
| 3 | 7 | 9 | | | |
+----+----+----+----+----+----+
");
}
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn join_full_empty_right(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let left = build_table(
("a1", &vec![1, 2, 3]),
("b1", &vec![4, 5, 7]),
("c1", &vec![7, 8, 9]),
);
let right = build_table_i32(("a2", &vec![]), ("b2", &vec![]), ("c2", &vec![]));
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema()).unwrap()) as _,
Arc::new(Column::new_with_schema("b2", &right.schema()).unwrap()) as _,
)];
let schema = right.schema();
let right = TestMemoryExec::try_new_exec(&[vec![right]], schema, None).unwrap();
let join = join(
left,
right,
on,
&JoinType::Full,
NullEquality::NullEqualsNothing,
)
.unwrap();
let columns = columns(&join.schema());
assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b2", "c2"]);
let stream = join.execute(0, task_ctx).unwrap();
let batches = common::collect(stream).await.unwrap();
let metrics = join.metrics().unwrap();
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+----+----+----+----+
| a1 | b1 | c1 | a2 | b2 | c2 |
+----+----+----+----+----+----+
| 1 | 4 | 7 | | | |
| 2 | 5 | 8 | | | |
| 3 | 7 | 9 | | | |
+----+----+----+----+----+----+
");
}
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn join_left_one(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let left = build_table(
("a1", &vec![1, 2, 3]),
("b1", &vec![4, 5, 7]), ("c1", &vec![7, 8, 9]),
);
let right = build_table(
("a2", &vec![10, 20, 30]),
("b1", &vec![4, 5, 6]),
("c2", &vec![70, 80, 90]),
);
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
)];
let (columns, batches, metrics) = join_collect(
Arc::clone(&left),
Arc::clone(&right),
on.clone(),
&JoinType::Left,
NullEquality::NullEqualsNothing,
task_ctx,
)
.await?;
assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b1", "c2"]);
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+----+----+----+----+
| a1 | b1 | c1 | a2 | b1 | c2 |
+----+----+----+----+----+----+
| 1 | 4 | 7 | 10 | 4 | 70 |
| 2 | 5 | 8 | 20 | 5 | 80 |
| 3 | 7 | 9 | | | |
+----+----+----+----+----+----+
");
}
assert_join_metrics!(metrics, 3);
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
Ok(())
}
#[rstest]
#[tokio::test]
async fn join_all_null_build_keys(
#[values(PartitionMode::CollectLeft, PartitionMode::Partitioned)]
partition_mode: PartitionMode,
) -> Result<()> {
let left = build_table_two_cols(
("a1", &vec![Some(1), Some(2)]),
("b1", &vec![None, None]), );
let right = build_table_two_cols(
("a2", &vec![Some(10), Some(20), Some(30)]),
("b1", &vec![Some(4), None, Some(6)]),
);
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
)];
for join_type in [
JoinType::Inner,
JoinType::Left,
JoinType::Right,
JoinType::Full,
JoinType::LeftSemi,
JoinType::LeftAnti,
JoinType::RightSemi,
JoinType::RightAnti,
JoinType::LeftMark,
JoinType::RightMark,
] {
let (_, batches, metrics) = join_collect_with_partition_mode(
Arc::clone(&left),
Arc::clone(&right),
on.clone(),
&join_type,
partition_mode,
NullEquality::NullEqualsNothing,
Arc::new(TaskContext::default()),
)
.await?;
let probe_rows = metrics
.sum_by_name("input_rows")
.map(|v| v.as_usize())
.unwrap_or(0);
if join_type.empty_map_produces_empty_result() {
assert_eq!(
probe_rows, 0,
"{join_type} should skip the probe side for an all-NULL build"
);
} else {
assert!(probe_rows > 0, "{join_type} must scan the probe side");
}
match join_type {
JoinType::Inner | JoinType::LeftSemi | JoinType::RightSemi => {
let num_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
assert_eq!(num_rows, 0, "unexpected rows for {join_type}");
}
JoinType::Left => {
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+----+----+
| a1 | b1 | a2 | b1 |
+----+----+----+----+
| 1 | | | |
| 2 | | | |
+----+----+----+----+
");
}
}
JoinType::Right => {
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+----+----+
| a1 | b1 | a2 | b1 |
+----+----+----+----+
| | | 10 | 4 |
| | | 20 | |
| | | 30 | 6 |
+----+----+----+----+
");
}
}
JoinType::Full => {
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+----+----+
| a1 | b1 | a2 | b1 |
+----+----+----+----+
| | | 10 | 4 |
| | | 20 | |
| | | 30 | 6 |
| 1 | | | |
| 2 | | | |
+----+----+----+----+
");
}
}
JoinType::LeftAnti => {
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+
| a1 | b1 |
+----+----+
| 1 | |
| 2 | |
+----+----+
");
}
}
JoinType::RightAnti => {
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+
| a2 | b1 |
+----+----+
| 10 | 4 |
| 20 | |
| 30 | 6 |
+----+----+
");
}
}
JoinType::LeftMark => {
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+-------+
| a1 | b1 | mark |
+----+----+-------+
| 1 | | false |
| 2 | | false |
+----+----+-------+
");
}
}
JoinType::RightMark => {
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+-------+
| a2 | b1 | mark |
+----+----+-------+
| 10 | 4 | false |
| 20 | | false |
| 30 | 6 | false |
+----+----+-------+
");
}
}
}
}
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn partitioned_join_left_one(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let left = build_table(
("a1", &vec![1, 2, 3]),
("b1", &vec![4, 5, 7]), ("c1", &vec![7, 8, 9]),
);
let right = build_table(
("a2", &vec![10, 20, 30]),
("b1", &vec![4, 5, 6]),
("c2", &vec![70, 80, 90]),
);
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
)];
let (columns, batches, metrics) = partitioned_join_collect(
Arc::clone(&left),
Arc::clone(&right),
on.clone(),
&JoinType::Left,
NullEquality::NullEqualsNothing,
task_ctx,
)
.await?;
assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b1", "c2"]);
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+----+----+----+----+
| a1 | b1 | c1 | a2 | b1 | c2 |
+----+----+----+----+----+----+
| 1 | 4 | 7 | 10 | 4 | 70 |
| 2 | 5 | 8 | 20 | 5 | 80 |
| 3 | 7 | 9 | | | |
+----+----+----+----+----+----+
");
}
assert_join_metrics!(metrics, 3);
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
Ok(())
}
fn build_semi_anti_left_table() -> Arc<dyn ExecutionPlan> {
build_table(
("a1", &vec![1, 3, 5, 7, 9, 11, 13]),
("b1", &vec![1, 3, 5, 7, 8, 8, 10]),
("c1", &vec![10, 30, 50, 70, 90, 110, 130]),
)
}
fn build_semi_anti_right_table() -> Arc<dyn ExecutionPlan> {
build_table(
("a2", &vec![8, 12, 6, 2, 10, 4]),
("b2", &vec![8, 10, 6, 2, 10, 4]),
("c2", &vec![20, 40, 60, 80, 100, 120]),
)
}
#[tokio::test]
async fn test_semi_left_join_reports_final_emission() -> Result<()> {
let (left_schema, right_schema, on) = build_schema_and_on()?;
let left = TestMemoryExec::try_new_exec(&[vec![]], left_schema, None)?;
let right = TestMemoryExec::try_new_exec(&[vec![]], right_schema, None)?;
let join = HashJoinExec::try_new(
left,
right,
on,
None,
&JoinType::LeftSemi,
None,
PartitionMode::CollectLeft,
NullEquality::NullEqualsNothing,
false,
)?;
assert_eq!(join.properties().emission_type, EmissionType::Final);
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn join_left_semi(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let left = build_semi_anti_left_table();
let right = build_semi_anti_right_table();
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
)];
let join = join(
left,
right,
on,
&JoinType::LeftSemi,
NullEquality::NullEqualsNothing,
)?;
let columns = columns(&join.schema());
assert_eq!(columns, vec!["a1", "b1", "c1"]);
let stream = join.execute(0, task_ctx)?;
let batches = common::collect(stream).await?;
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+-----+
| a1 | b1 | c1 |
+----+----+-----+
| 11 | 8 | 110 |
| 13 | 10 | 130 |
| 9 | 8 | 90 |
+----+----+-----+
");
}
let metrics = join.metrics().unwrap();
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn join_left_semi_with_filter(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let left = build_semi_anti_left_table();
let right = build_semi_anti_right_table();
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
)];
let column_indices = vec![ColumnIndex {
index: 0,
side: JoinSide::Right,
}];
let intermediate_schema =
Schema::new(vec![Field::new("x", DataType::Int32, true)]);
let filter_expression = Arc::new(BinaryExpr::new(
Arc::new(Column::new("x", 0)),
Operator::NotEq,
Arc::new(Literal::new(ScalarValue::Int32(Some(10)))),
)) as Arc<dyn PhysicalExpr>;
let filter = JoinFilter::new(
filter_expression,
column_indices.clone(),
Arc::new(intermediate_schema.clone()),
);
let join = join_with_filter(
Arc::clone(&left),
Arc::clone(&right),
on.clone(),
filter,
&JoinType::LeftSemi,
NullEquality::NullEqualsNothing,
)?;
let columns_header = columns(&join.schema());
assert_eq!(columns_header.clone(), vec!["a1", "b1", "c1"]);
let stream = join.execute(0, Arc::clone(&task_ctx))?;
let batches = common::collect(stream).await?;
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+-----+
| a1 | b1 | c1 |
+----+----+-----+
| 11 | 8 | 110 |
| 13 | 10 | 130 |
| 9 | 8 | 90 |
+----+----+-----+
");
}
let metrics = join.metrics().unwrap();
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
let filter_expression = Arc::new(BinaryExpr::new(
Arc::new(Column::new("x", 0)),
Operator::Gt,
Arc::new(Literal::new(ScalarValue::Int32(Some(10)))),
)) as Arc<dyn PhysicalExpr>;
let filter = JoinFilter::new(
filter_expression,
column_indices,
Arc::new(intermediate_schema),
);
let join = join_with_filter(
left,
right,
on,
filter,
&JoinType::LeftSemi,
NullEquality::NullEqualsNothing,
)?;
let columns_header = columns(&join.schema());
assert_eq!(columns_header, vec!["a1", "b1", "c1"]);
let stream = join.execute(0, task_ctx)?;
let batches = common::collect(stream).await?;
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+-----+
| a1 | b1 | c1 |
+----+----+-----+
| 13 | 10 | 130 |
+----+----+-----+
");
}
let metrics = join.metrics().unwrap();
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn join_right_semi(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let left = build_semi_anti_left_table();
let right = build_semi_anti_right_table();
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
)];
let join = join(
left,
right,
on,
&JoinType::RightSemi,
NullEquality::NullEqualsNothing,
)?;
let columns = columns(&join.schema());
assert_eq!(columns, vec!["a2", "b2", "c2"]);
let stream = join.execute(0, task_ctx)?;
let batches = common::collect(stream).await?;
allow_duplicates! {
assert_snapshot!(batches_to_string(&batches), @r"
+----+----+-----+
| a2 | b2 | c2 |
+----+----+-----+
| 8 | 8 | 20 |
| 12 | 10 | 40 |
| 10 | 10 | 100 |
+----+----+-----+
");
}
let metrics = join.metrics().unwrap();
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn join_right_semi_with_filter(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let left = build_semi_anti_left_table();
let right = build_semi_anti_right_table();
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
)];
let column_indices = vec![ColumnIndex {
index: 0,
side: JoinSide::Left,
}];
let intermediate_schema =
Schema::new(vec![Field::new("x", DataType::Int32, true)]);
let filter_expression = Arc::new(BinaryExpr::new(
Arc::new(Column::new("x", 0)),
Operator::NotEq,
Arc::new(Literal::new(ScalarValue::Int32(Some(9)))),
)) as Arc<dyn PhysicalExpr>;
let filter = JoinFilter::new(
filter_expression,
column_indices.clone(),
Arc::new(intermediate_schema.clone()),
);
let join = join_with_filter(
Arc::clone(&left),
Arc::clone(&right),
on.clone(),
filter,
&JoinType::RightSemi,
NullEquality::NullEqualsNothing,
)?;
let columns = columns(&join.schema());
assert_eq!(columns, vec!["a2", "b2", "c2"]);
let stream = join.execute(0, Arc::clone(&task_ctx))?;
let batches = common::collect(stream).await?;
allow_duplicates! {
assert_snapshot!(batches_to_string(&batches), @r"
+----+----+-----+
| a2 | b2 | c2 |
+----+----+-----+
| 8 | 8 | 20 |
| 12 | 10 | 40 |
| 10 | 10 | 100 |
+----+----+-----+
");
}
let metrics = join.metrics().unwrap();
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
let filter_expression = Arc::new(BinaryExpr::new(
Arc::new(Column::new("x", 0)),
Operator::Gt,
Arc::new(Literal::new(ScalarValue::Int32(Some(11)))),
)) as Arc<dyn PhysicalExpr>;
let filter = JoinFilter::new(
filter_expression,
column_indices,
Arc::new(intermediate_schema.clone()),
);
let join = join_with_filter(
left,
right,
on,
filter,
&JoinType::RightSemi,
NullEquality::NullEqualsNothing,
)?;
let stream = join.execute(0, task_ctx)?;
let batches = common::collect(stream).await?;
allow_duplicates! {
assert_snapshot!(batches_to_string(&batches), @r"
+----+----+-----+
| a2 | b2 | c2 |
+----+----+-----+
| 12 | 10 | 40 |
| 10 | 10 | 100 |
+----+----+-----+
");
}
let metrics = join.metrics().unwrap();
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn join_left_anti(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let left = build_semi_anti_left_table();
let right = build_semi_anti_right_table();
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
)];
let join = join(
left,
right,
on,
&JoinType::LeftAnti,
NullEquality::NullEqualsNothing,
)?;
let columns = columns(&join.schema());
assert_eq!(columns, vec!["a1", "b1", "c1"]);
let stream = join.execute(0, task_ctx)?;
let batches = common::collect(stream).await?;
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+----+
| a1 | b1 | c1 |
+----+----+----+
| 1 | 1 | 10 |
| 3 | 3 | 30 |
| 5 | 5 | 50 |
| 7 | 7 | 70 |
+----+----+----+
");
}
let metrics = join.metrics().unwrap();
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn join_left_anti_with_filter(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let left = build_semi_anti_left_table();
let right = build_semi_anti_right_table();
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
)];
let column_indices = vec![ColumnIndex {
index: 0,
side: JoinSide::Right,
}];
let intermediate_schema =
Schema::new(vec![Field::new("x", DataType::Int32, true)]);
let filter_expression = Arc::new(BinaryExpr::new(
Arc::new(Column::new("x", 0)),
Operator::NotEq,
Arc::new(Literal::new(ScalarValue::Int32(Some(8)))),
)) as Arc<dyn PhysicalExpr>;
let filter = JoinFilter::new(
filter_expression,
column_indices.clone(),
Arc::new(intermediate_schema.clone()),
);
let join = join_with_filter(
Arc::clone(&left),
Arc::clone(&right),
on.clone(),
filter,
&JoinType::LeftAnti,
NullEquality::NullEqualsNothing,
)?;
let columns_header = columns(&join.schema());
assert_eq!(columns_header, vec!["a1", "b1", "c1"]);
let stream = join.execute(0, Arc::clone(&task_ctx))?;
let batches = common::collect(stream).await?;
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+-----+
| a1 | b1 | c1 |
+----+----+-----+
| 1 | 1 | 10 |
| 11 | 8 | 110 |
| 3 | 3 | 30 |
| 5 | 5 | 50 |
| 7 | 7 | 70 |
| 9 | 8 | 90 |
+----+----+-----+
");
}
let metrics = join.metrics().unwrap();
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
let filter_expression = Arc::new(BinaryExpr::new(
Arc::new(Column::new("x", 0)),
Operator::NotEq,
Arc::new(Literal::new(ScalarValue::Int32(Some(8)))),
)) as Arc<dyn PhysicalExpr>;
let filter = JoinFilter::new(
filter_expression,
column_indices,
Arc::new(intermediate_schema),
);
let join = join_with_filter(
left,
right,
on,
filter,
&JoinType::LeftAnti,
NullEquality::NullEqualsNothing,
)?;
let columns_header = columns(&join.schema());
assert_eq!(columns_header, vec!["a1", "b1", "c1"]);
let stream = join.execute(0, task_ctx)?;
let batches = common::collect(stream).await?;
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+-----+
| a1 | b1 | c1 |
+----+----+-----+
| 1 | 1 | 10 |
| 11 | 8 | 110 |
| 3 | 3 | 30 |
| 5 | 5 | 50 |
| 7 | 7 | 70 |
| 9 | 8 | 90 |
+----+----+-----+
");
}
let metrics = join.metrics().unwrap();
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn join_right_anti(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let left = build_semi_anti_left_table();
let right = build_semi_anti_right_table();
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
)];
let join = join(
left,
right,
on,
&JoinType::RightAnti,
NullEquality::NullEqualsNothing,
)?;
let columns = columns(&join.schema());
assert_eq!(columns, vec!["a2", "b2", "c2"]);
let stream = join.execute(0, task_ctx)?;
let batches = common::collect(stream).await?;
allow_duplicates! {
assert_snapshot!(batches_to_string(&batches), @r"
+----+----+-----+
| a2 | b2 | c2 |
+----+----+-----+
| 6 | 6 | 60 |
| 2 | 2 | 80 |
| 4 | 4 | 120 |
+----+----+-----+
");
}
let metrics = join.metrics().unwrap();
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn join_right_anti_with_filter(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let left = build_semi_anti_left_table();
let right = build_semi_anti_right_table();
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
)];
let column_indices = vec![ColumnIndex {
index: 0,
side: JoinSide::Left,
}];
let intermediate_schema =
Schema::new(vec![Field::new("x", DataType::Int32, true)]);
let filter_expression = Arc::new(BinaryExpr::new(
Arc::new(Column::new("x", 0)),
Operator::NotEq,
Arc::new(Literal::new(ScalarValue::Int32(Some(13)))),
)) as Arc<dyn PhysicalExpr>;
let filter = JoinFilter::new(
filter_expression,
column_indices,
Arc::new(intermediate_schema.clone()),
);
let join = join_with_filter(
Arc::clone(&left),
Arc::clone(&right),
on.clone(),
filter,
&JoinType::RightAnti,
NullEquality::NullEqualsNothing,
)?;
let columns_header = columns(&join.schema());
assert_eq!(columns_header, vec!["a2", "b2", "c2"]);
let stream = join.execute(0, Arc::clone(&task_ctx))?;
let batches = common::collect(stream).await?;
allow_duplicates! {
assert_snapshot!(batches_to_string(&batches), @r"
+----+----+-----+
| a2 | b2 | c2 |
+----+----+-----+
| 12 | 10 | 40 |
| 6 | 6 | 60 |
| 2 | 2 | 80 |
| 10 | 10 | 100 |
| 4 | 4 | 120 |
+----+----+-----+
");
}
let metrics = join.metrics().unwrap();
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
let column_indices = vec![ColumnIndex {
index: 1,
side: JoinSide::Right,
}];
let filter_expression = Arc::new(BinaryExpr::new(
Arc::new(Column::new("x", 0)),
Operator::NotEq,
Arc::new(Literal::new(ScalarValue::Int32(Some(8)))),
)) as Arc<dyn PhysicalExpr>;
let filter = JoinFilter::new(
filter_expression,
column_indices,
Arc::new(intermediate_schema),
);
let join = join_with_filter(
left,
right,
on,
filter,
&JoinType::RightAnti,
NullEquality::NullEqualsNothing,
)?;
let columns_header = columns(&join.schema());
assert_eq!(columns_header, vec!["a2", "b2", "c2"]);
let stream = join.execute(0, task_ctx)?;
let batches = common::collect(stream).await?;
allow_duplicates! {
assert_snapshot!(batches_to_string(&batches), @r"
+----+----+-----+
| a2 | b2 | c2 |
+----+----+-----+
| 8 | 8 | 20 |
| 6 | 6 | 60 |
| 2 | 2 | 80 |
| 4 | 4 | 120 |
+----+----+-----+
");
}
let metrics = join.metrics().unwrap();
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn join_right_one(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let left = build_table(
("a1", &vec![1, 2, 3]),
("b1", &vec![4, 5, 7]),
("c1", &vec![7, 8, 9]),
);
let right = build_table(
("a2", &vec![10, 20, 30]),
("b1", &vec![4, 5, 6]), ("c2", &vec![70, 80, 90]),
);
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
)];
let (columns, batches, metrics) = join_collect(
left,
right,
on,
&JoinType::Right,
NullEquality::NullEqualsNothing,
task_ctx,
)
.await?;
assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b1", "c2"]);
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+----+----+----+----+
| a1 | b1 | c1 | a2 | b1 | c2 |
+----+----+----+----+----+----+
| | | | 30 | 6 | 90 |
| 1 | 4 | 7 | 10 | 4 | 70 |
| 2 | 5 | 8 | 20 | 5 | 80 |
+----+----+----+----+----+----+
");
}
assert_join_metrics!(metrics, 3);
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn partitioned_join_right_one(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let left = build_table(
("a1", &vec![1, 2, 3]),
("b1", &vec![4, 5, 7]),
("c1", &vec![7, 8, 9]),
);
let right = build_table(
("a2", &vec![10, 20, 30]),
("b1", &vec![4, 5, 6]), ("c2", &vec![70, 80, 90]),
);
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
)];
let (columns, batches, metrics) = partitioned_join_collect(
left,
right,
on,
&JoinType::Right,
NullEquality::NullEqualsNothing,
task_ctx,
)
.await?;
assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b1", "c2"]);
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+----+----+----+----+
| a1 | b1 | c1 | a2 | b1 | c2 |
+----+----+----+----+----+----+
| | | | 30 | 6 | 90 |
| 1 | 4 | 7 | 10 | 4 | 70 |
| 2 | 5 | 8 | 20 | 5 | 80 |
+----+----+----+----+----+----+
");
}
assert_join_metrics!(metrics, 3);
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn join_full_one(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let left = build_table(
("a1", &vec![1, 2, 3]),
("b1", &vec![4, 5, 7]), ("c1", &vec![7, 8, 9]),
);
let right = build_table(
("a2", &vec![10, 20, 30]),
("b2", &vec![4, 5, 6]),
("c2", &vec![70, 80, 90]),
);
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema()).unwrap()) as _,
Arc::new(Column::new_with_schema("b2", &right.schema()).unwrap()) as _,
)];
let join = join(
left,
right,
on,
&JoinType::Full,
NullEquality::NullEqualsNothing,
)?;
let columns = columns(&join.schema());
assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b2", "c2"]);
let stream = join.execute(0, task_ctx)?;
let batches = common::collect(stream).await?;
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+----+----+----+----+
| a1 | b1 | c1 | a2 | b2 | c2 |
+----+----+----+----+----+----+
| | | | 30 | 6 | 90 |
| 1 | 4 | 7 | 10 | 4 | 70 |
| 2 | 5 | 8 | 20 | 5 | 80 |
| 3 | 7 | 9 | | | |
+----+----+----+----+----+----+
");
}
let metrics = join.metrics().unwrap();
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn join_left_mark(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let left = build_table(
("a1", &vec![1, 2, 3]),
("b1", &vec![4, 5, 7]), ("c1", &vec![7, 8, 9]),
);
let right = build_table(
("a2", &vec![10, 20, 30]),
("b1", &vec![4, 5, 6]),
("c2", &vec![70, 80, 90]),
);
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
)];
let (columns, batches, metrics) = join_collect(
Arc::clone(&left),
Arc::clone(&right),
on.clone(),
&JoinType::LeftMark,
NullEquality::NullEqualsNothing,
task_ctx,
)
.await?;
assert_eq!(columns, vec!["a1", "b1", "c1", "mark"]);
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+----+-------+
| a1 | b1 | c1 | mark |
+----+----+----+-------+
| 1 | 4 | 7 | true |
| 2 | 5 | 8 | true |
| 3 | 7 | 9 | false |
+----+----+----+-------+
");
}
assert_join_metrics!(metrics, 3);
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn partitioned_join_left_mark(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let left = build_table(
("a1", &vec![1, 2, 3]),
("b1", &vec![4, 5, 7]), ("c1", &vec![7, 8, 9]),
);
let right = build_table(
("a2", &vec![10, 20, 30, 40]),
("b1", &vec![4, 4, 5, 6]),
("c2", &vec![60, 70, 80, 90]),
);
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
)];
let (columns, batches, metrics) = partitioned_join_collect(
Arc::clone(&left),
Arc::clone(&right),
on.clone(),
&JoinType::LeftMark,
NullEquality::NullEqualsNothing,
task_ctx,
)
.await?;
assert_eq!(columns, vec!["a1", "b1", "c1", "mark"]);
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+----+-------+
| a1 | b1 | c1 | mark |
+----+----+----+-------+
| 1 | 4 | 7 | true |
| 2 | 5 | 8 | true |
| 3 | 7 | 9 | false |
+----+----+----+-------+
");
}
assert_join_metrics!(metrics, 3);
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn join_right_mark(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let left = build_table(
("a1", &vec![1, 2, 3]),
("b1", &vec![4, 5, 7]), ("c1", &vec![7, 8, 9]),
);
let right = build_table(
("a2", &vec![10, 20, 30]),
("b1", &vec![4, 5, 6]), ("c2", &vec![70, 80, 90]),
);
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
)];
let (columns, batches, metrics) = join_collect(
Arc::clone(&left),
Arc::clone(&right),
on.clone(),
&JoinType::RightMark,
NullEquality::NullEqualsNothing,
task_ctx,
)
.await?;
assert_eq!(columns, vec!["a2", "b1", "c2", "mark"]);
let expected = [
"+----+----+----+-------+",
"| a2 | b1 | c2 | mark |",
"+----+----+----+-------+",
"| 10 | 4 | 70 | true |",
"| 20 | 5 | 80 | true |",
"| 30 | 6 | 90 | false |",
"+----+----+----+-------+",
];
assert_batches_sorted_eq!(expected, &batches);
assert_join_metrics!(metrics, 3);
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn partitioned_join_right_mark(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let left = build_table(
("a1", &vec![1, 2, 3]),
("b1", &vec![4, 5, 7]), ("c1", &vec![7, 8, 9]),
);
let right = build_table(
("a2", &vec![10, 20, 30, 40]),
("b1", &vec![4, 4, 5, 6]), ("c2", &vec![60, 70, 80, 90]),
);
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
)];
let (columns, batches, metrics) = partitioned_join_collect(
Arc::clone(&left),
Arc::clone(&right),
on.clone(),
&JoinType::RightMark,
NullEquality::NullEqualsNothing,
task_ctx,
)
.await?;
assert_eq!(columns, vec!["a2", "b1", "c2", "mark"]);
let expected = [
"+----+----+----+-------+",
"| a2 | b1 | c2 | mark |",
"+----+----+----+-------+",
"| 10 | 4 | 60 | true |",
"| 20 | 4 | 70 | true |",
"| 30 | 5 | 80 | true |",
"| 40 | 6 | 90 | false |",
"+----+----+----+-------+",
];
assert_batches_sorted_eq!(expected, &batches);
assert_join_metrics!(metrics, 4);
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
Ok(())
}
#[test]
fn join_with_hash_collisions_64() -> Result<()> {
let mut hashmap_left = HashTable::with_capacity(4);
let left = build_table_i32(
("a", &vec![10, 20]),
("x", &vec![100, 200]),
("y", &vec![200, 300]),
);
let random_state = RandomState::with_seed(0);
let hashes_buff = &mut vec![0; left.num_rows()];
let hashes = create_hashes([&left.columns()[0]], &random_state, hashes_buff)?;
hashmap_left.insert_unique(hashes[0], (hashes[0], 1), |(h, _)| *h);
hashmap_left.insert_unique(hashes[0], (hashes[0], 2), |(h, _)| *h);
hashmap_left.insert_unique(hashes[1], (hashes[1], 1), |(h, _)| *h);
hashmap_left.insert_unique(hashes[1], (hashes[1], 2), |(h, _)| *h);
let next = vec![2, 0];
let right = build_table_i32(
("a", &vec![10, 20]),
("b", &vec![0, 0]),
("c", &vec![30, 40]),
);
let key_column: PhysicalExprRef = Arc::new(Column::new("a", 0)) as _;
let join_hash_map = JoinHashMapU64::new(hashmap_left, next);
let left_keys_values = key_column.evaluate(&left)?.into_array(left.num_rows())?;
let right_keys_values =
key_column.evaluate(&right)?.into_array(right.num_rows())?;
let mut hashes_buffer = vec![0; right.num_rows()];
create_hashes([&right_keys_values], &random_state, &mut hashes_buffer)?;
let mut probe_indices_buffer = Vec::new();
let mut build_indices_buffer = Vec::new();
let (l, r, _) = lookup_join_hashmap(
&join_hash_map,
&[left_keys_values],
&[right_keys_values],
NullEquality::NullEqualsNothing,
&hashes_buffer,
None,
8192,
AtRow { row: 0 },
&mut probe_indices_buffer,
&mut build_indices_buffer,
&mut None,
)?;
let left_ids: UInt64Array = vec![0, 1].into();
let right_ids: UInt32Array = vec![0, 1].into();
assert_eq!(left_ids, l);
assert_eq!(right_ids, r);
Ok(())
}
#[test]
fn join_with_hash_collisions_u32() -> Result<()> {
let mut hashmap_left = HashTable::with_capacity(4);
let left = build_table_i32(
("a", &vec![10, 20]),
("x", &vec![100, 200]),
("y", &vec![200, 300]),
);
let random_state = RandomState::with_seed(0);
let hashes_buff = &mut vec![0; left.num_rows()];
let hashes = create_hashes([&left.columns()[0]], &random_state, hashes_buff)?;
hashmap_left.insert_unique(hashes[0], (hashes[0], 1u32), |(h, _)| *h);
hashmap_left.insert_unique(hashes[0], (hashes[0], 2u32), |(h, _)| *h);
hashmap_left.insert_unique(hashes[1], (hashes[1], 1u32), |(h, _)| *h);
hashmap_left.insert_unique(hashes[1], (hashes[1], 2u32), |(h, _)| *h);
let next: Vec<u32> = vec![2, 0];
let right = build_table_i32(
("a", &vec![10, 20]),
("b", &vec![0, 0]),
("c", &vec![30, 40]),
);
let key_column: PhysicalExprRef = Arc::new(Column::new("a", 0)) as _;
let join_hash_map = JoinHashMapU32::new(hashmap_left, next);
let left_keys_values = key_column.evaluate(&left)?.into_array(left.num_rows())?;
let right_keys_values =
key_column.evaluate(&right)?.into_array(right.num_rows())?;
let mut hashes_buffer = vec![0; right.num_rows()];
create_hashes([&right_keys_values], &random_state, &mut hashes_buffer)?;
let mut probe_indices_buffer = Vec::new();
let mut build_indices_buffer = Vec::new();
let (l, r, _) = lookup_join_hashmap(
&join_hash_map,
&[left_keys_values],
&[right_keys_values],
NullEquality::NullEqualsNothing,
&hashes_buffer,
None,
8192,
AtRow { row: 0 },
&mut probe_indices_buffer,
&mut build_indices_buffer,
&mut None,
)?;
let left_ids: UInt64Array = vec![0, 1].into();
let right_ids: UInt32Array = vec![0, 1].into();
assert_eq!(left_ids, l);
assert_eq!(right_ids, r);
Ok(())
}
#[tokio::test]
async fn join_with_duplicated_column_names() -> Result<()> {
let task_ctx = Arc::new(TaskContext::default());
let left = build_table(
("a", &vec![1, 2, 3]),
("b", &vec![4, 5, 7]),
("c", &vec![7, 8, 9]),
);
let right = build_table(
("a", &vec![10, 20, 30]),
("b", &vec![1, 2, 7]),
("c", &vec![70, 80, 90]),
);
let on = vec![(
Arc::new(Column::new_with_schema("a", &left.schema()).unwrap()) as _,
Arc::new(Column::new_with_schema("b", &right.schema()).unwrap()) as _,
)];
let join = join(
left,
right,
on,
&JoinType::Inner,
NullEquality::NullEqualsNothing,
)?;
let columns = columns(&join.schema());
assert_eq!(columns, vec!["a", "b", "c", "a", "b", "c"]);
let stream = join.execute(0, task_ctx)?;
let batches = common::collect(stream).await?;
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+---+---+---+----+---+----+
| a | b | c | a | b | c |
+---+---+---+----+---+----+
| 1 | 4 | 7 | 10 | 1 | 70 |
| 2 | 5 | 8 | 20 | 2 | 80 |
+---+---+---+----+---+----+
");
}
Ok(())
}
fn prepare_join_filter() -> JoinFilter {
let column_indices = vec![
ColumnIndex {
index: 2,
side: JoinSide::Left,
},
ColumnIndex {
index: 2,
side: JoinSide::Right,
},
];
let intermediate_schema = Schema::new(vec![
Field::new("c", DataType::Int32, true),
Field::new("c", DataType::Int32, true),
]);
let filter_expression = Arc::new(BinaryExpr::new(
Arc::new(Column::new("c", 0)),
Operator::Gt,
Arc::new(Column::new("c", 1)),
)) as Arc<dyn PhysicalExpr>;
JoinFilter::new(
filter_expression,
column_indices,
Arc::new(intermediate_schema),
)
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn join_inner_with_filter(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let left = build_table(
("a", &vec![0, 1, 2, 2]),
("b", &vec![4, 5, 7, 8]),
("c", &vec![7, 8, 9, 1]),
);
let right = build_table(
("a", &vec![10, 20, 30, 40]),
("b", &vec![2, 2, 3, 4]),
("c", &vec![7, 5, 6, 4]),
);
let on = vec![(
Arc::new(Column::new_with_schema("a", &left.schema()).unwrap()) as _,
Arc::new(Column::new_with_schema("b", &right.schema()).unwrap()) as _,
)];
let filter = prepare_join_filter();
let join = join_with_filter(
left,
right,
on,
filter,
&JoinType::Inner,
NullEquality::NullEqualsNothing,
)?;
let columns = columns(&join.schema());
assert_eq!(columns, vec!["a", "b", "c", "a", "b", "c"]);
let stream = join.execute(0, task_ctx)?;
let batches = common::collect(stream).await?;
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+---+---+---+----+---+---+
| a | b | c | a | b | c |
+---+---+---+----+---+---+
| 2 | 7 | 9 | 10 | 2 | 7 |
| 2 | 7 | 9 | 20 | 2 | 5 |
+---+---+---+----+---+---+
");
}
let metrics = join.metrics().unwrap();
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn join_left_with_filter(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let left = build_table(
("a", &vec![0, 1, 2, 2]),
("b", &vec![4, 5, 7, 8]),
("c", &vec![7, 8, 9, 1]),
);
let right = build_table(
("a", &vec![10, 20, 30, 40]),
("b", &vec![2, 2, 3, 4]),
("c", &vec![7, 5, 6, 4]),
);
let on = vec![(
Arc::new(Column::new_with_schema("a", &left.schema()).unwrap()) as _,
Arc::new(Column::new_with_schema("b", &right.schema()).unwrap()) as _,
)];
let filter = prepare_join_filter();
let join = join_with_filter(
left,
right,
on,
filter,
&JoinType::Left,
NullEquality::NullEqualsNothing,
)?;
let columns = columns(&join.schema());
assert_eq!(columns, vec!["a", "b", "c", "a", "b", "c"]);
let stream = join.execute(0, task_ctx)?;
let batches = common::collect(stream).await?;
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+---+---+---+----+---+---+
| a | b | c | a | b | c |
+---+---+---+----+---+---+
| 0 | 4 | 7 | | | |
| 1 | 5 | 8 | | | |
| 2 | 7 | 9 | 10 | 2 | 7 |
| 2 | 7 | 9 | 20 | 2 | 5 |
| 2 | 8 | 1 | | | |
+---+---+---+----+---+---+
");
}
let metrics = join.metrics().unwrap();
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn join_right_with_filter(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let left = build_table(
("a", &vec![0, 1, 2, 2]),
("b", &vec![4, 5, 7, 8]),
("c", &vec![7, 8, 9, 1]),
);
let right = build_table(
("a", &vec![10, 20, 30, 40]),
("b", &vec![2, 2, 3, 4]),
("c", &vec![7, 5, 6, 4]),
);
let on = vec![(
Arc::new(Column::new_with_schema("a", &left.schema()).unwrap()) as _,
Arc::new(Column::new_with_schema("b", &right.schema()).unwrap()) as _,
)];
let filter = prepare_join_filter();
let join = join_with_filter(
left,
right,
on,
filter,
&JoinType::Right,
NullEquality::NullEqualsNothing,
)?;
let columns = columns(&join.schema());
assert_eq!(columns, vec!["a", "b", "c", "a", "b", "c"]);
let stream = join.execute(0, task_ctx)?;
let batches = common::collect(stream).await?;
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+---+---+---+----+---+---+
| a | b | c | a | b | c |
+---+---+---+----+---+---+
| | | | 30 | 3 | 6 |
| | | | 40 | 4 | 4 |
| 2 | 7 | 9 | 10 | 2 | 7 |
| 2 | 7 | 9 | 20 | 2 | 5 |
+---+---+---+----+---+---+
");
}
let metrics = join.metrics().unwrap();
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn join_full_with_filter(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let left = build_table(
("a", &vec![0, 1, 2, 2]),
("b", &vec![4, 5, 7, 8]),
("c", &vec![7, 8, 9, 1]),
);
let right = build_table(
("a", &vec![10, 20, 30, 40]),
("b", &vec![2, 2, 3, 4]),
("c", &vec![7, 5, 6, 4]),
);
let on = vec![(
Arc::new(Column::new_with_schema("a", &left.schema()).unwrap()) as _,
Arc::new(Column::new_with_schema("b", &right.schema()).unwrap()) as _,
)];
let filter = prepare_join_filter();
let join = join_with_filter(
left,
right,
on,
filter,
&JoinType::Full,
NullEquality::NullEqualsNothing,
)?;
let columns = columns(&join.schema());
assert_eq!(columns, vec!["a", "b", "c", "a", "b", "c"]);
let stream = join.execute(0, task_ctx)?;
let batches = common::collect(stream).await?;
let expected = [
"+---+---+---+----+---+---+",
"| a | b | c | a | b | c |",
"+---+---+---+----+---+---+",
"| | | | 30 | 3 | 6 |",
"| | | | 40 | 4 | 4 |",
"| 2 | 7 | 9 | 10 | 2 | 7 |",
"| 2 | 7 | 9 | 20 | 2 | 5 |",
"| 0 | 4 | 7 | | | |",
"| 1 | 5 | 8 | | | |",
"| 2 | 8 | 1 | | | |",
"+---+---+---+----+---+---+",
];
assert_batches_sorted_eq!(expected, &batches);
let metrics = join.metrics().unwrap();
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
Ok(())
}
#[tokio::test]
async fn test_collect_left_multiple_partitions_join() -> Result<()> {
let task_ctx = Arc::new(TaskContext::default());
let left = build_table(
("a1", &vec![1, 2, 3]),
("b1", &vec![4, 5, 7]),
("c1", &vec![7, 8, 9]),
);
let right = build_table(
("a2", &vec![10, 20, 30]),
("b2", &vec![4, 5, 6]),
("c2", &vec![70, 80, 90]),
);
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema()).unwrap()) as _,
Arc::new(Column::new_with_schema("b2", &right.schema()).unwrap()) as _,
)];
let expected_inner = vec![
"+----+----+----+----+----+----+",
"| a1 | b1 | c1 | a2 | b2 | c2 |",
"+----+----+----+----+----+----+",
"| 1 | 4 | 7 | 10 | 4 | 70 |",
"| 2 | 5 | 8 | 20 | 5 | 80 |",
"+----+----+----+----+----+----+",
];
let expected_left = vec![
"+----+----+----+----+----+----+",
"| a1 | b1 | c1 | a2 | b2 | c2 |",
"+----+----+----+----+----+----+",
"| 1 | 4 | 7 | 10 | 4 | 70 |",
"| 2 | 5 | 8 | 20 | 5 | 80 |",
"| 3 | 7 | 9 | | | |",
"+----+----+----+----+----+----+",
];
let expected_right = vec![
"+----+----+----+----+----+----+",
"| a1 | b1 | c1 | a2 | b2 | c2 |",
"+----+----+----+----+----+----+",
"| | | | 30 | 6 | 90 |",
"| 1 | 4 | 7 | 10 | 4 | 70 |",
"| 2 | 5 | 8 | 20 | 5 | 80 |",
"+----+----+----+----+----+----+",
];
let expected_full = vec![
"+----+----+----+----+----+----+",
"| a1 | b1 | c1 | a2 | b2 | c2 |",
"+----+----+----+----+----+----+",
"| | | | 30 | 6 | 90 |",
"| 1 | 4 | 7 | 10 | 4 | 70 |",
"| 2 | 5 | 8 | 20 | 5 | 80 |",
"| 3 | 7 | 9 | | | |",
"+----+----+----+----+----+----+",
];
let expected_left_semi = vec![
"+----+----+----+",
"| a1 | b1 | c1 |",
"+----+----+----+",
"| 1 | 4 | 7 |",
"| 2 | 5 | 8 |",
"+----+----+----+",
];
let expected_left_anti = vec![
"+----+----+----+",
"| a1 | b1 | c1 |",
"+----+----+----+",
"| 3 | 7 | 9 |",
"+----+----+----+",
];
let expected_right_semi = vec![
"+----+----+----+",
"| a2 | b2 | c2 |",
"+----+----+----+",
"| 10 | 4 | 70 |",
"| 20 | 5 | 80 |",
"+----+----+----+",
];
let expected_right_anti = vec![
"+----+----+----+",
"| a2 | b2 | c2 |",
"+----+----+----+",
"| 30 | 6 | 90 |",
"+----+----+----+",
];
let expected_left_mark = vec![
"+----+----+----+-------+",
"| a1 | b1 | c1 | mark |",
"+----+----+----+-------+",
"| 1 | 4 | 7 | true |",
"| 2 | 5 | 8 | true |",
"| 3 | 7 | 9 | false |",
"+----+----+----+-------+",
];
let expected_right_mark = vec![
"+----+----+----+-------+",
"| a2 | b2 | c2 | mark |",
"+----+----+----+-------+",
"| 10 | 4 | 70 | true |",
"| 20 | 5 | 80 | true |",
"| 30 | 6 | 90 | false |",
"+----+----+----+-------+",
];
let test_cases = vec![
(JoinType::Inner, expected_inner),
(JoinType::Left, expected_left),
(JoinType::Right, expected_right),
(JoinType::Full, expected_full),
(JoinType::LeftSemi, expected_left_semi),
(JoinType::LeftAnti, expected_left_anti),
(JoinType::RightSemi, expected_right_semi),
(JoinType::RightAnti, expected_right_anti),
(JoinType::LeftMark, expected_left_mark),
(JoinType::RightMark, expected_right_mark),
];
for (join_type, expected) in test_cases {
let (_, batches, metrics) = join_collect_with_partition_mode(
Arc::clone(&left),
Arc::clone(&right),
on.clone(),
&join_type,
PartitionMode::CollectLeft,
NullEquality::NullEqualsNothing,
Arc::clone(&task_ctx),
)
.await?;
assert_batches_sorted_eq!(expected, &batches);
assert_join_metrics!(metrics, expected.len() - 4);
}
Ok(())
}
#[tokio::test]
async fn join_date32() -> Result<()> {
let schema = Arc::new(Schema::new(vec![
Field::new("date", DataType::Date32, false),
Field::new("n", DataType::Int32, false),
]));
let dates: ArrayRef = Arc::new(Date32Array::from(vec![19107, 19108, 19109]));
let n: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3]));
let batch = RecordBatch::try_new(Arc::clone(&schema), vec![dates, n])?;
let left =
TestMemoryExec::try_new_exec(&[vec![batch]], Arc::clone(&schema), None)
.unwrap();
let dates: ArrayRef = Arc::new(Date32Array::from(vec![19108, 19108, 19109]));
let n: ArrayRef = Arc::new(Int32Array::from(vec![4, 5, 6]));
let batch = RecordBatch::try_new(Arc::clone(&schema), vec![dates, n])?;
let right = TestMemoryExec::try_new_exec(&[vec![batch]], schema, None).unwrap();
let on = vec![(
Arc::new(Column::new_with_schema("date", &left.schema()).unwrap()) as _,
Arc::new(Column::new_with_schema("date", &right.schema()).unwrap()) as _,
)];
let join = join(
left,
right,
on,
&JoinType::Inner,
NullEquality::NullEqualsNothing,
)?;
let task_ctx = Arc::new(TaskContext::default());
let stream = join.execute(0, task_ctx)?;
let batches = common::collect(stream).await?;
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+------------+---+------------+---+
| date | n | date | n |
+------------+---+------------+---+
| 2022-04-26 | 2 | 2022-04-26 | 4 |
| 2022-04-26 | 2 | 2022-04-26 | 5 |
| 2022-04-27 | 3 | 2022-04-27 | 6 |
+------------+---+------------+---+
");
}
Ok(())
}
#[tokio::test]
async fn join_with_error_right() {
let left = build_table(
("a1", &vec![1, 2, 3]),
("b1", &vec![4, 5, 7]),
("c1", &vec![7, 8, 9]),
);
let err = exec_err!("bad data error");
let right = build_table_i32(("a2", &vec![]), ("b1", &vec![]), ("c2", &vec![]));
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema()).unwrap()) as _,
Arc::new(Column::new_with_schema("b1", &right.schema()).unwrap()) as _,
)];
let schema = right.schema();
let right = build_table_i32(("a2", &vec![]), ("b1", &vec![]), ("c2", &vec![]));
let right_input = Arc::new(MockExec::new(vec![Ok(right), err], schema));
let join_types = vec![
JoinType::Inner,
JoinType::Left,
JoinType::Right,
JoinType::Full,
JoinType::LeftSemi,
JoinType::LeftAnti,
JoinType::RightSemi,
JoinType::RightAnti,
];
for join_type in join_types {
let join = join(
Arc::clone(&left),
Arc::clone(&right_input) as Arc<dyn ExecutionPlan>,
on.clone(),
&join_type,
NullEquality::NullEqualsNothing,
)
.unwrap();
let task_ctx = Arc::new(TaskContext::default());
let stream = join.execute(0, task_ctx).unwrap();
let result_string = common::collect(stream).await.unwrap_err().to_string();
assert!(
result_string.contains("bad data error"),
"actual: {result_string}"
);
}
}
#[tokio::test]
async fn join_does_not_consume_probe_when_empty_build_fixes_output() {
assert_empty_build_probe_behavior(
&[
JoinType::Inner,
JoinType::Left,
JoinType::LeftSemi,
JoinType::LeftAnti,
JoinType::LeftMark,
JoinType::RightSemi,
],
false,
false,
)
.await;
}
#[tokio::test]
async fn join_does_not_consume_probe_when_empty_build_fixes_output_with_filter() {
assert_empty_build_probe_behavior(
&[
JoinType::Inner,
JoinType::Left,
JoinType::LeftSemi,
JoinType::LeftAnti,
JoinType::LeftMark,
JoinType::RightSemi,
],
false,
true,
)
.await;
}
#[tokio::test]
async fn join_still_consumes_probe_when_empty_build_needs_probe_rows() {
assert_empty_build_probe_behavior(
&[
JoinType::Right,
JoinType::Full,
JoinType::RightAnti,
JoinType::RightMark,
],
true,
false,
)
.await;
}
#[tokio::test]
async fn join_still_consumes_probe_when_empty_build_needs_probe_rows_with_filter() {
assert_empty_build_probe_behavior(
&[
JoinType::Right,
JoinType::Full,
JoinType::RightAnti,
JoinType::RightMark,
],
true,
true,
)
.await;
}
#[tokio::test]
async fn join_split_batch() {
let left = build_table(
("a1", &vec![1, 2, 3, 4]),
("b1", &vec![1, 1, 1, 1]),
("c1", &vec![0, 0, 0, 0]),
);
let right = build_table(
("a2", &vec![10, 20, 30, 40, 50]),
("b2", &vec![1, 1, 1, 1, 1]),
("c2", &vec![0, 0, 0, 0, 0]),
);
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema()).unwrap()) as _,
Arc::new(Column::new_with_schema("b2", &right.schema()).unwrap()) as _,
)];
let join_types = vec![
JoinType::Inner,
JoinType::Left,
JoinType::Right,
JoinType::Full,
JoinType::RightSemi,
JoinType::RightAnti,
JoinType::LeftSemi,
JoinType::LeftAnti,
];
let expected_resultset_records = 20;
let common_result = [
"+----+----+----+----+----+----+",
"| a1 | b1 | c1 | a2 | b2 | c2 |",
"+----+----+----+----+----+----+",
"| 1 | 1 | 0 | 10 | 1 | 0 |",
"| 2 | 1 | 0 | 10 | 1 | 0 |",
"| 3 | 1 | 0 | 10 | 1 | 0 |",
"| 4 | 1 | 0 | 10 | 1 | 0 |",
"| 1 | 1 | 0 | 20 | 1 | 0 |",
"| 2 | 1 | 0 | 20 | 1 | 0 |",
"| 3 | 1 | 0 | 20 | 1 | 0 |",
"| 4 | 1 | 0 | 20 | 1 | 0 |",
"| 1 | 1 | 0 | 30 | 1 | 0 |",
"| 2 | 1 | 0 | 30 | 1 | 0 |",
"| 3 | 1 | 0 | 30 | 1 | 0 |",
"| 4 | 1 | 0 | 30 | 1 | 0 |",
"| 1 | 1 | 0 | 40 | 1 | 0 |",
"| 2 | 1 | 0 | 40 | 1 | 0 |",
"| 3 | 1 | 0 | 40 | 1 | 0 |",
"| 4 | 1 | 0 | 40 | 1 | 0 |",
"| 1 | 1 | 0 | 50 | 1 | 0 |",
"| 2 | 1 | 0 | 50 | 1 | 0 |",
"| 3 | 1 | 0 | 50 | 1 | 0 |",
"| 4 | 1 | 0 | 50 | 1 | 0 |",
"+----+----+----+----+----+----+",
];
let left_batch = [
"+----+----+----+",
"| a1 | b1 | c1 |",
"+----+----+----+",
"| 1 | 1 | 0 |",
"| 2 | 1 | 0 |",
"| 3 | 1 | 0 |",
"| 4 | 1 | 0 |",
"+----+----+----+",
];
let right_batch = [
"+----+----+----+",
"| a2 | b2 | c2 |",
"+----+----+----+",
"| 10 | 1 | 0 |",
"| 20 | 1 | 0 |",
"| 30 | 1 | 0 |",
"| 40 | 1 | 0 |",
"| 50 | 1 | 0 |",
"+----+----+----+",
];
let right_empty = [
"+----+----+----+",
"| a2 | b2 | c2 |",
"+----+----+----+",
"+----+----+----+",
];
let left_empty = [
"+----+----+----+",
"| a1 | b1 | c1 |",
"+----+----+----+",
"+----+----+----+",
];
for join_type in join_types {
for batch_size in (1..21).rev() {
let task_ctx = prepare_task_ctx(batch_size, true);
let join = join(
Arc::clone(&left),
Arc::clone(&right),
on.clone(),
&join_type,
NullEquality::NullEqualsNothing,
)
.unwrap();
let stream = join.execute(0, task_ctx).unwrap();
let batches = common::collect(stream).await.unwrap();
let expected_batch_count = match join_type {
JoinType::Inner
| JoinType::Right
| JoinType::RightSemi
| JoinType::RightAnti => {
div_ceil(expected_resultset_records, batch_size)
}
_ => div_ceil(expected_resultset_records, batch_size) + 1,
};
assert!(
batches.len() <= expected_batch_count,
"expected at most {expected_batch_count} output batches for {join_type} join with batch_size = {batch_size}, got {}",
batches.len()
);
let expected = match join_type {
JoinType::RightSemi => right_batch.to_vec(),
JoinType::RightAnti => right_empty.to_vec(),
JoinType::LeftSemi => left_batch.to_vec(),
JoinType::LeftAnti => left_empty.to_vec(),
_ => common_result.to_vec(),
};
if batches.is_empty() {
assert!(
matches!(join_type, JoinType::RightAnti | JoinType::LeftAnti),
"Unexpected empty result for {join_type} join"
);
} else {
assert_batches_eq!(expected, &batches);
}
}
}
}
#[tokio::test]
async fn single_partition_join_overallocation() -> Result<()> {
let left = build_table(
("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(
("a2", &vec![10, 11]),
("b2", &vec![12, 13]),
("c2", &vec![14, 15]),
);
let on = vec![(
Arc::new(Column::new_with_schema("a1", &left.schema()).unwrap()) as _,
Arc::new(Column::new_with_schema("b2", &right.schema()).unwrap()) as _,
)];
let join_types = vec![
JoinType::Inner,
JoinType::Left,
JoinType::Right,
JoinType::Full,
JoinType::LeftSemi,
JoinType::LeftAnti,
JoinType::RightSemi,
JoinType::RightAnti,
JoinType::LeftMark,
JoinType::RightMark,
];
for join_type in join_types {
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 join = join(
Arc::clone(&left),
Arc::clone(&right),
on.clone(),
&join_type,
NullEquality::NullEqualsNothing,
)?;
let stream = join.execute(0, task_ctx)?;
let err = common::collect(stream).await.unwrap_err();
assert_contains!(
err.to_string(),
"Resources exhausted: Additional allocation failed for HashJoinInput with top memory consumers (across reservations) as:\n HashJoinInput"
);
assert_contains!(
err.to_string(),
"Failed to allocate additional 120.0 B for HashJoinInput"
);
}
Ok(())
}
#[tokio::test]
async fn build_side_sliced_batches_memory_accounting() -> Result<()> {
let n = 4096;
let v: Vec<i32> = (0..n).collect();
let parent = build_table_i32(("a1", &v), ("b1", &v), ("c1", &v));
let slices: Vec<RecordBatch> =
(0..16).map(|i| parent.slice(i * 256, 256)).collect();
let left =
TestMemoryExec::try_new_exec(&[slices], parent.schema(), None).unwrap();
let right_batch = build_table_i32(
("a2", &vec![10, 11]),
("b2", &vec![0, 1]),
("c2", &vec![14, 15]),
);
let right = TestMemoryExec::try_new_exec(
&[vec![right_batch.clone()]],
right_batch.schema(),
None,
)
.unwrap();
let on = vec![(
Arc::new(Column::new_with_schema("b1", &parent.schema())?) as _,
Arc::new(Column::new_with_schema("b2", &right_batch.schema())?) as _,
)];
let runtime = RuntimeEnvBuilder::new()
.with_memory_limit(400_000, 1.0)
.build_arc()?;
let task_ctx = TaskContext::default().with_runtime(runtime);
let task_ctx = Arc::new(task_ctx);
let join = join(
left,
right,
on,
&JoinType::Inner,
NullEquality::NullEqualsNothing,
)?;
let stream = join.execute(0, task_ctx)?;
let batches = common::collect(stream).await?;
let num_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
assert_eq!(num_rows, 2);
Ok(())
}
#[tokio::test]
async fn partitioned_join_overallocation() -> Result<()> {
let left_batch = build_table_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 left = TestMemoryExec::try_new_exec(
&[vec![left_batch.clone()], vec![left_batch.clone()]],
left_batch.schema(),
None,
)
.unwrap();
let right_batch = build_table_i32(
("a2", &vec![10, 11]),
("b2", &vec![12, 13]),
("c2", &vec![14, 15]),
);
let right = TestMemoryExec::try_new_exec(
&[vec![right_batch.clone()], vec![right_batch.clone()]],
right_batch.schema(),
None,
)
.unwrap();
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left_batch.schema())?) as _,
Arc::new(Column::new_with_schema("b2", &right_batch.schema())?) as _,
)];
let join_types = vec![
JoinType::Inner,
JoinType::Left,
JoinType::Right,
JoinType::Full,
JoinType::LeftSemi,
JoinType::LeftAnti,
JoinType::RightSemi,
JoinType::RightAnti,
];
for join_type in join_types {
let runtime = RuntimeEnvBuilder::new()
.with_memory_limit(100, 1.0)
.build_arc()?;
let session_config = SessionConfig::default().with_batch_size(50);
let task_ctx = TaskContext::default()
.with_session_config(session_config)
.with_runtime(runtime);
let task_ctx = Arc::new(task_ctx);
let join = HashJoinExec::try_new(
Arc::clone(&left) as Arc<dyn ExecutionPlan>,
Arc::clone(&right) as Arc<dyn ExecutionPlan>,
on.clone(),
None,
&join_type,
None,
PartitionMode::Partitioned,
NullEquality::NullEqualsNothing,
false,
)?;
let stream = join.execute(1, task_ctx)?;
let err = common::collect(stream).await.unwrap_err();
assert_contains!(
err.to_string(),
"Resources exhausted: Additional allocation failed for HashJoinInput[1] with top memory consumers (across reservations) as:\n HashJoinInput[1]"
);
assert_contains!(
err.to_string(),
"Failed to allocate additional 120.0 B for HashJoinInput[1]"
);
}
Ok(())
}
fn concat_test_batches(num_batches: usize, num_rows: usize) -> Vec<RecordBatch> {
let schema = Arc::new(Schema::new(vec![
Field::new("k", DataType::Int32, false),
Field::new("s", DataType::Utf8, true),
Field::new("v", DataType::Utf8View, true),
Field::new("bv", DataType::BinaryView, true),
]));
(0..num_batches)
.map(|b| {
let start = (b * num_rows) as i32;
let keys = Int32Array::from_iter_values(start..start + num_rows as i32);
let strings = (0..num_rows)
.map(|i| (i % 7 != 0).then(|| format!("string-{b}-{i}")))
.collect::<StringArray>();
let views = (0..num_rows)
.map(|i| {
(i % 5 != 0).then(|| format!("a long string view value {b}-{i}"))
})
.collect::<StringViewArray>();
let binary_views = (0..num_rows)
.map(|i| {
(i % 3 != 0).then(|| format!("a long binary view value {b}-{i}"))
})
.collect::<BinaryViewArray>();
RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(keys),
Arc::new(strings),
Arc::new(views),
Arc::new(binary_views),
],
)
.unwrap()
})
.collect()
}
fn reserve_inputs(
batches: &[RecordBatch],
pool: &Arc<dyn MemoryPool>,
) -> Result<(MemoryReservation, usize)> {
let reservation = MemoryConsumer::new("HashJoinInput").register(pool);
let mut counter = RecordBatchMemoryCounter::new();
for batch in batches {
reservation.try_grow(counter.count_batch(batch))?;
}
Ok((reservation, counter.memory_usage()))
}
#[test]
fn concat_build_batches_matches_concat_batches() -> Result<()> {
let batches = concat_test_batches(4, 100);
let schema = batches[0].schema();
let metrics = BuildProbeJoinMetrics::new(0, &ExecutionPlanMetricsSet::new());
let pool: Arc<dyn MemoryPool> = Arc::new(UnboundedMemoryPool::default());
let (mut reservation, inputs_reserved) = reserve_inputs(&batches, &pool)?;
let expected = concat_batches(&schema, batches.iter())?;
let batch = concat_build_batches(
&schema,
&mut batches.clone(),
inputs_reserved,
&mut reservation,
&metrics,
)?;
assert_eq!(batch, expected);
Ok(())
}
#[test]
fn concat_build_batches_reserves_copy() -> Result<()> {
let mut batches = concat_test_batches(4, 1000);
let schema = batches[0].schema();
let metrics = BuildProbeJoinMetrics::new(0, &ExecutionPlanMetricsSet::new());
let inputs: usize = batches.iter().map(get_record_batch_memory_size).sum();
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(inputs * 5 / 4));
let (mut reservation, inputs_reserved) = reserve_inputs(&batches, &pool)?;
assert_eq!(inputs_reserved, inputs);
let original = batches.clone();
let err = concat_build_batches(
&schema,
&mut batches,
inputs_reserved,
&mut reservation,
&metrics,
)
.unwrap_err();
assert_contains!(err.to_string(), "Resources exhausted");
assert_eq!(batches, original);
drop(original);
drop(reservation);
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(inputs * 2));
let (mut reservation, inputs_reserved) = reserve_inputs(&batches, &pool)?;
let batch = concat_build_batches(
&schema,
&mut batches,
inputs_reserved,
&mut reservation,
&metrics,
)?;
assert_eq!(reservation.size(), get_record_batch_memory_size(&batch));
assert_eq!(pool.reserved(), reservation.size());
assert_eq!(batches, vec![batch]);
Ok(())
}
#[test]
fn concat_build_batches_single_batch_not_reserved_twice() -> Result<()> {
let mut batches = concat_test_batches(1, 1000);
let schema = batches[0].schema();
let metrics = BuildProbeJoinMetrics::new(0, &ExecutionPlanMetricsSet::new());
let inputs = get_record_batch_memory_size(&batches[0]);
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(inputs));
let (mut reservation, inputs_reserved) = reserve_inputs(&batches, &pool)?;
let batch = concat_build_batches(
&schema,
&mut batches,
inputs_reserved,
&mut reservation,
&metrics,
)?;
assert_eq!(batch.num_rows(), 1000);
assert_eq!(reservation.size(), inputs);
Ok(())
}
#[rstest]
fn concat_build_batches_view_data_not_reserved_twice(
#[values("v", "bv")] column: &str,
) -> Result<()> {
let batches = concat_test_batches(4, 1000);
let column = batches[0].schema().index_of(column)?;
let mut batches = batches
.into_iter()
.map(|batch| batch.project(&[column]))
.collect::<Result<Vec<_>, _>>()?;
let schema = batches[0].schema();
let metrics = BuildProbeJoinMetrics::new(0, &ExecutionPlanMetricsSet::new());
let inputs: usize = batches.iter().map(get_record_batch_memory_size).sum();
let views = 4 * 1000 * size_of::<u128>();
assert!(inputs > 2 * views);
let pool: Arc<dyn MemoryPool> =
Arc::new(GreedyMemoryPool::new(inputs + views * 5 / 4));
let (mut reservation, inputs_reserved) = reserve_inputs(&batches, &pool)?;
let batch = concat_build_batches(
&schema,
&mut batches,
inputs_reserved,
&mut reservation,
&metrics,
)?;
assert_eq!(reservation.size(), get_record_batch_memory_size(&batch));
Ok(())
}
#[rstest]
#[tokio::test]
async fn join_build_concat_is_reserved(
#[values(PartitionMode::CollectLeft, PartitionMode::Partitioned)]
mode: PartitionMode,
#[values(false, true)] use_perfect_hash_join_as_possible: bool,
) -> Result<()> {
let num_rows = 4000;
let values = (0..num_rows).collect::<Vec<i32>>();
let batches = (0..4)
.map(|_| build_table_i32(("a1", &values), ("b1", &values), ("c1", &values)))
.collect::<Vec<_>>();
let inputs: usize = batches.iter().map(get_record_batch_memory_size).sum();
let left_schema = batches[0].schema();
let right = build_table(
("a2", &vec![10, 11]),
("b2", &vec![12, 13]),
("c2", &vec![14, 15]),
);
let on = vec![(
Arc::new(Column::new_with_schema("a1", &left_schema)?) as _,
Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
)];
let build_rows = batches.len() * num_rows as usize;
let map = if use_perfect_hash_join_as_possible {
ArrayMap::estimate_memory_size(0, num_rows as u64 - 1, build_rows)
} else {
estimate_memory_size::<(u32, u64)>(build_rows, size_of::<JoinHashMapU32>())?
+ build_rows * size_of::<u32>()
};
for (limit, fits) in [(map + inputs * 3 / 2, false), (map + inputs * 3, true)] {
let left = TestMemoryExec::try_new_exec(
std::slice::from_ref(&batches),
Arc::clone(&left_schema),
None,
)?;
let join = HashJoinExec::try_new(
left,
Arc::clone(&right),
on.clone(),
None,
&JoinType::Inner,
None,
mode,
NullEquality::NullEqualsNothing,
false,
)?;
let runtime = RuntimeEnvBuilder::new()
.with_memory_limit(limit, 1.0)
.build_arc()?;
let task_ctx = prepare_task_ctx(8192, use_perfect_hash_join_as_possible);
let task_ctx = Arc::new(
TaskContext::default()
.with_session_config(task_ctx.session_config().clone())
.with_runtime(runtime),
);
let result = common::collect(join.execute(0, task_ctx)?).await;
if fits {
result?;
} else {
assert_contains!(
result.unwrap_err().to_string(),
"Resources exhausted: Additional allocation failed for HashJoinInput"
);
}
}
Ok(())
}
#[rstest]
#[tokio::test]
async fn join_build_key_arrays_are_reserved(
#[values(false, true)] use_perfect_hash_join_as_possible: bool,
) -> Result<()> {
let num_rows = 16000;
let values = (0..num_rows).collect::<Vec<i32>>();
let batch = build_table_i32(("a1", &values), ("b1", &values), ("c1", &values));
let inputs = get_record_batch_memory_size(&batch);
let keys = inputs / 3;
let left_schema = batch.schema();
let right = build_table(
("a2", &vec![10, 11]),
("b2", &vec![12, 13]),
("c2", &vec![14, 15]),
);
let map = if use_perfect_hash_join_as_possible {
ArrayMap::estimate_memory_size(1, num_rows as u64, num_rows as usize)
} else {
estimate_memory_size::<(u32, u64)>(
num_rows as usize,
size_of::<JoinHashMapU32>(),
)? + num_rows as usize * size_of::<u32>()
};
for (computed_key, limit, fits) in [
(false, inputs + map + keys / 2, true),
(true, inputs + map + keys / 2, false),
(true, inputs + map + keys * 2, true),
] {
let column = Arc::new(Column::new_with_schema("a1", &left_schema)?) as _;
let left_key: PhysicalExprRef = if computed_key {
Arc::new(BinaryExpr::new(
column,
Operator::Plus,
Arc::new(Literal::new(ScalarValue::Int32(Some(1)))),
))
} else {
column
};
let on = vec![(
left_key,
Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
)];
let left = TestMemoryExec::try_new_exec(
&[vec![batch.clone()]],
Arc::clone(&left_schema),
None,
)?;
let join = HashJoinExec::try_new(
left,
Arc::clone(&right),
on,
None,
&JoinType::Inner,
None,
PartitionMode::CollectLeft,
NullEquality::NullEqualsNothing,
false,
)?;
let runtime = RuntimeEnvBuilder::new()
.with_memory_limit(limit, 1.0)
.build_arc()?;
let task_ctx = prepare_task_ctx(8192, use_perfect_hash_join_as_possible);
let task_ctx = Arc::new(
TaskContext::default()
.with_session_config(task_ctx.session_config().clone())
.with_runtime(runtime),
);
let result = common::collect(join.execute(0, task_ctx)?).await;
if fits {
result?;
} else {
assert_contains!(
result.unwrap_err().to_string(),
"Resources exhausted: Additional allocation failed for HashJoinInput"
);
}
}
Ok(())
}
fn build_table_struct(
struct_name: &str,
field_name_and_values: (&str, &Vec<Option<i32>>),
nulls: Option<NullBuffer>,
) -> Arc<dyn ExecutionPlan> {
let (field_name, values) = field_name_and_values;
let inner_fields = vec![Field::new(field_name, DataType::Int32, true)];
let schema = Schema::new(vec![Field::new(
struct_name,
DataType::Struct(inner_fields.clone().into()),
nulls.is_some(),
)]);
let batch = RecordBatch::try_new(
Arc::new(schema),
vec![Arc::new(StructArray::new(
inner_fields.into(),
vec![Arc::new(Int32Array::from(values.clone()))],
nulls,
))],
)
.unwrap();
let schema_ref = batch.schema();
TestMemoryExec::try_new_exec(&[vec![batch]], schema_ref, None).unwrap()
}
#[tokio::test]
#[expect(
clippy::literal_string_with_formatting_args,
reason = "The braces are part of the expected struct output, not format args"
)]
async fn join_on_struct() -> Result<()> {
let task_ctx = Arc::new(TaskContext::default());
let left =
build_table_struct("n1", ("a", &vec![None, Some(1), Some(2), Some(3)]), None);
let right =
build_table_struct("n2", ("a", &vec![None, Some(1), Some(2), Some(4)]), None);
let on = vec![(
Arc::new(Column::new_with_schema("n1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("n2", &right.schema())?) as _,
)];
let (columns, batches, metrics) = join_collect(
left,
right,
on,
&JoinType::Inner,
NullEquality::NullEqualsNothing,
task_ctx,
)
.await?;
assert_eq!(columns, vec!["n1", "n2"]);
allow_duplicates! {
assert_snapshot!(batches_to_string(&batches), @r"
+--------+--------+
| n1 | n2 |
+--------+--------+
| {a: } | {a: } |
| {a: 1} | {a: 1} |
| {a: 2} | {a: 2} |
+--------+--------+
");
}
assert_join_metrics!(metrics, 3);
Ok(())
}
#[tokio::test]
async fn join_on_struct_with_nulls() -> Result<()> {
let task_ctx = Arc::new(TaskContext::default());
let left =
build_table_struct("n1", ("a", &vec![None]), Some(NullBuffer::new_null(1)));
let right =
build_table_struct("n2", ("a", &vec![None]), Some(NullBuffer::new_null(1)));
let on = vec![(
Arc::new(Column::new_with_schema("n1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("n2", &right.schema())?) as _,
)];
let (_, batches_null_eq, metrics) = join_collect(
Arc::clone(&left),
Arc::clone(&right),
on.clone(),
&JoinType::Inner,
NullEquality::NullEqualsNull,
Arc::clone(&task_ctx),
)
.await?;
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches_null_eq), @r"
+----+----+
| n1 | n2 |
+----+----+
| | |
+----+----+
");
}
assert_join_metrics!(metrics, 1);
let (_, batches_null_neq, metrics) = join_collect(
left,
right,
on,
&JoinType::Inner,
NullEquality::NullEqualsNothing,
task_ctx,
)
.await?;
assert_join_metrics!(metrics, 0);
if batches_null_neq.is_empty() {
} else {
let expected_null_neq =
["+----+----+", "| n1 | n2 |", "+----+----+", "+----+----+"];
assert_batches_eq!(expected_null_neq, &batches_null_neq);
}
Ok(())
}
fn columns(schema: &Schema) -> Vec<String> {
schema.fields().iter().map(|f| f.name().clone()).collect()
}
#[tokio::test]
async fn test_hash_join_marks_filter_complete() -> Result<()> {
let task_ctx = Arc::new(TaskContext::default());
let left = build_table(
("a1", &vec![1, 2, 3]),
("b1", &vec![4, 5, 6]),
("c1", &vec![7, 8, 9]),
);
let right = build_table(
("a2", &vec![10, 20, 30]),
("b1", &vec![4, 5, 6]),
("c2", &vec![70, 80, 90]),
);
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
)];
let (join, dynamic_filter) =
hash_join_with_dynamic_filter(left, right, on, JoinType::Inner)?;
let stream = join.execute(0, task_ctx)?;
let _batches = common::collect(stream).await?;
dynamic_filter.wait_complete().await;
Ok(())
}
#[tokio::test]
async fn test_hash_join_marks_filter_complete_empty_build_side() -> Result<()> {
let task_ctx = Arc::new(TaskContext::default());
let left = build_table(("a1", &vec![]), ("b1", &vec![]), ("c1", &vec![]));
let right = build_table(
("a2", &vec![10, 20, 30]),
("b1", &vec![4, 5, 6]),
("c2", &vec![70, 80, 90]),
);
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
)];
let (join, dynamic_filter) =
hash_join_with_dynamic_filter(left, right, on, JoinType::Inner)?;
let stream = join.execute(0, task_ctx)?;
let _batches = common::collect(stream).await?;
dynamic_filter.wait_complete().await;
Ok(())
}
#[tokio::test]
async fn test_partitioned_dynamic_filter_reports_empty_canceled_partitions()
-> Result<()> {
let mut session_config = SessionConfig::default();
session_config
.options_mut()
.optimizer
.enable_dynamic_filter_pushdown = true;
let task_ctx =
Arc::new(TaskContext::default().with_session_config(session_config));
let child_left_schema = Arc::new(Schema::new(vec![
Field::new("child_left_payload", DataType::Int32, false),
Field::new("child_key", DataType::Int32, false),
Field::new("child_left_extra", DataType::Int32, false),
]));
let child_right_schema = Arc::new(Schema::new(vec![
Field::new("child_right_payload", DataType::Int32, false),
Field::new("child_right_key", DataType::Int32, false),
Field::new("child_right_extra", DataType::Int32, false),
]));
let parent_left_schema = Arc::new(Schema::new(vec![
Field::new("parent_payload", DataType::Int32, false),
Field::new("parent_key", DataType::Int32, false),
Field::new("parent_extra", DataType::Int32, false),
]));
let child_left: Arc<dyn ExecutionPlan> = TestMemoryExec::try_new_exec(
&[
vec![build_table_i32(
("child_left_payload", &vec![10]),
("child_key", &vec![0]),
("child_left_extra", &vec![100]),
)],
vec![build_table_i32(
("child_left_payload", &vec![11]),
("child_key", &vec![1]),
("child_left_extra", &vec![101]),
)],
vec![build_table_i32(
("child_left_payload", &vec![12]),
("child_key", &vec![2]),
("child_left_extra", &vec![102]),
)],
vec![build_table_i32(
("child_left_payload", &vec![13]),
("child_key", &vec![3]),
("child_left_extra", &vec![103]),
)],
],
Arc::clone(&child_left_schema),
None,
)?;
let child_right: Arc<dyn ExecutionPlan> = TestMemoryExec::try_new_exec(
&[
vec![build_table_i32(
("child_right_payload", &vec![20]),
("child_right_key", &vec![0]),
("child_right_extra", &vec![200]),
)],
vec![build_table_i32(
("child_right_payload", &vec![21]),
("child_right_key", &vec![1]),
("child_right_extra", &vec![201]),
)],
vec![build_table_i32(
("child_right_payload", &vec![22]),
("child_right_key", &vec![2]),
("child_right_extra", &vec![202]),
)],
vec![build_table_i32(
("child_right_payload", &vec![23]),
("child_right_key", &vec![3]),
("child_right_extra", &vec![203]),
)],
],
Arc::clone(&child_right_schema),
None,
)?;
let parent_left: Arc<dyn ExecutionPlan> = TestMemoryExec::try_new_exec(
&[
vec![build_table_i32(
("parent_payload", &vec![30]),
("parent_key", &vec![0]),
("parent_extra", &vec![300]),
)],
vec![RecordBatch::new_empty(Arc::clone(&parent_left_schema))],
vec![build_table_i32(
("parent_payload", &vec![32]),
("parent_key", &vec![2]),
("parent_extra", &vec![302]),
)],
vec![RecordBatch::new_empty(Arc::clone(&parent_left_schema))],
],
Arc::clone(&parent_left_schema),
None,
)?;
let child_on = vec![(
Arc::new(Column::new_with_schema("child_key", &child_left_schema)?) as _,
Arc::new(Column::new_with_schema(
"child_right_key",
&child_right_schema,
)?) as _,
)];
let (child_join, _child_dynamic_filter) = hash_join_with_dynamic_filter_and_mode(
child_left,
child_right,
child_on,
JoinType::Inner,
PartitionMode::Partitioned,
)?;
let child_join: Arc<dyn ExecutionPlan> = Arc::new(child_join);
let parent_on = vec![(
Arc::new(Column::new_with_schema("parent_key", &parent_left_schema)?) as _,
Arc::new(Column::new_with_schema("child_key", &child_join.schema())?) as _,
)];
let parent_join = HashJoinExec::try_new(
parent_left,
child_join,
parent_on,
None,
&JoinType::RightSemi,
None,
PartitionMode::Partitioned,
NullEquality::NullEqualsNothing,
false,
)?;
let batches = tokio::time::timeout(
std::time::Duration::from_secs(5),
crate::execution_plan::collect(Arc::new(parent_join), task_ctx),
)
.await
.expect("partitioned right-semi join should not hang")?;
assert_batches_sorted_eq!(
[
"+--------------------+-----------+------------------+---------------------+-----------------+-------------------+",
"| child_left_payload | child_key | child_left_extra | child_right_payload | child_right_key | child_right_extra |",
"+--------------------+-----------+------------------+---------------------+-----------------+-------------------+",
"| 10 | 0 | 100 | 20 | 0 | 200 |",
"| 12 | 2 | 102 | 22 | 2 | 202 |",
"+--------------------+-----------+------------------+---------------------+-----------------+-------------------+",
],
&batches
);
Ok(())
}
#[tokio::test]
async fn test_hash_join_skips_probe_on_empty_build_after_partition_bounds_report()
-> Result<()> {
let task_ctx = Arc::new(TaskContext::default());
let (left, right, on) = empty_build_with_probe_error_inputs();
let (join, dynamic_filter) =
hash_join_with_dynamic_filter(left, right, on, JoinType::Inner)?;
let stream = join.execute(0, task_ctx)?;
let batches = common::collect(stream).await?;
assert!(batches.is_empty());
dynamic_filter.wait_complete().await;
Ok(())
}
#[tokio::test]
async fn test_perfect_hash_join_with_negative_numbers() -> Result<()> {
let task_ctx = prepare_task_ctx(8192, true);
let (left_schema, right_schema, on) = build_schema_and_on()?;
let left_batch = RecordBatch::try_new(
Arc::clone(&left_schema),
vec![
Arc::new(Int32Array::from(vec![1, 2, 3])) as ArrayRef,
Arc::new(Int32Array::from(vec![-1, 0, 1])) as ArrayRef,
],
)?;
let left = TestMemoryExec::try_new_exec(&[vec![left_batch]], left_schema, None)?;
let right_batch = RecordBatch::try_new(
Arc::clone(&right_schema),
vec![
Arc::new(Int32Array::from(vec![10, 20, 30, 40])) as ArrayRef,
Arc::new(Int32Array::from(vec![1, -1, 0, 2])) as ArrayRef,
],
)?;
let right =
TestMemoryExec::try_new_exec(&[vec![right_batch]], right_schema, None)?;
let (columns, batches, metrics) = join_collect(
left,
right,
on,
&JoinType::Inner,
NullEquality::NullEqualsNothing,
task_ctx,
)
.await?;
assert_eq!(columns, vec!["a1", "b1", "a2", "b1"]);
assert_batches_sorted_eq!(
[
"+----+----+----+----+",
"| a1 | b1 | a2 | b1 |",
"+----+----+----+----+",
"| 1 | -1 | 20 | -1 |",
"| 2 | 0 | 30 | 0 |",
"| 3 | 1 | 10 | 1 |",
"+----+----+----+----+",
],
&batches
);
assert_phj_used(&metrics, true);
Ok(())
}
#[tokio::test]
async fn test_perfect_hash_join_overflow_full_int64_range() -> Result<()> {
let task_ctx = prepare_task_ctx(8192, true);
let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int64, true)]));
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![Arc::new(Int64Array::from(vec![i64::MIN, i64::MAX]))],
)?;
let left = TestMemoryExec::try_new_exec(
&[vec![batch.clone()]],
Arc::clone(&schema),
None,
)?;
let right = TestMemoryExec::try_new_exec(&[vec![batch]], schema, None)?;
let on: JoinOn = vec![(
Arc::new(Column::new_with_schema("a", &left.schema())?) as _,
Arc::new(Column::new_with_schema("a", &right.schema())?) as _,
)];
let (_columns, batches, _metrics) = join_collect(
left,
right,
on,
&JoinType::Inner,
NullEquality::NullEqualsNothing,
task_ctx,
)
.await?;
let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
assert_eq!(total_rows, 2);
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn test_phj_null_equals_null_build_no_nulls_probe_has_nulls(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let (left_schema, right_schema, on) = build_schema_and_on()?;
let left_batch = RecordBatch::try_new(
Arc::clone(&left_schema),
vec![
Arc::new(Int32Array::from(vec![1, 2])) as ArrayRef,
Arc::new(Int32Array::from(vec![10, 20])) as ArrayRef,
],
)?;
let left = TestMemoryExec::try_new_exec(&[vec![left_batch]], left_schema, None)?;
let right_batch = RecordBatch::try_new(
Arc::clone(&right_schema),
vec![
Arc::new(Int32Array::from(vec![3, 4])) as ArrayRef,
Arc::new(Int32Array::from(vec![Some(10), None])) as ArrayRef,
],
)?;
let right =
TestMemoryExec::try_new_exec(&[vec![right_batch]], right_schema, None)?;
let (columns, batches, metrics) = join_collect(
left,
right,
on,
&JoinType::Inner,
NullEquality::NullEqualsNull,
task_ctx,
)
.await?;
assert_eq!(columns, vec!["a1", "b1", "a2", "b1"]);
assert_batches_sorted_eq!(
[
"+----+----+----+----+",
"| a1 | b1 | a2 | b1 |",
"+----+----+----+----+",
"| 1 | 10 | 3 | 10 |",
"+----+----+----+----+",
],
&batches
);
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn test_phj_null_equals_nothing_build_probe_all_have_nulls(
batch_size: usize,
use_perfect_hash_join_as_possible: bool,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
let (left_schema, right_schema, on) = build_schema_and_on()?;
let left_batch = RecordBatch::try_new(
Arc::clone(&left_schema),
vec![
Arc::new(Int32Array::from(vec![Some(1), Some(2)])) as ArrayRef,
Arc::new(Int32Array::from(vec![Some(10), None])) as ArrayRef,
],
)?;
let left = TestMemoryExec::try_new_exec(&[vec![left_batch]], left_schema, None)?;
let right_batch = RecordBatch::try_new(
Arc::clone(&right_schema),
vec![
Arc::new(Int32Array::from(vec![Some(3), Some(4)])) as ArrayRef,
Arc::new(Int32Array::from(vec![Some(10), None])) as ArrayRef,
],
)?;
let right =
TestMemoryExec::try_new_exec(&[vec![right_batch]], right_schema, None)?;
let (columns, batches, metrics) = join_collect(
left,
right,
on,
&JoinType::Inner,
NullEquality::NullEqualsNothing,
task_ctx,
)
.await?;
assert_eq!(columns, vec!["a1", "b1", "a2", "b1"]);
assert_batches_sorted_eq!(
[
"+----+----+----+----+",
"| a1 | b1 | a2 | b1 |",
"+----+----+----+----+",
"| 1 | 10 | 3 | 10 |",
"+----+----+----+----+",
],
&batches
);
assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
Ok(())
}
#[tokio::test]
async fn test_phj_null_equals_null_build_have_nulls() -> Result<()> {
let task_ctx = prepare_task_ctx(8192, true);
let (left_schema, right_schema, on) = build_schema_and_on()?;
let left_batch = RecordBatch::try_new(
Arc::clone(&left_schema),
vec![
Arc::new(Int32Array::from(vec![Some(1), Some(2), Some(3)])) as ArrayRef,
Arc::new(Int32Array::from(vec![Some(10), Some(20), None])) as ArrayRef,
],
)?;
let left = TestMemoryExec::try_new_exec(&[vec![left_batch]], left_schema, None)?;
let right_batch = RecordBatch::try_new(
Arc::clone(&right_schema),
vec![
Arc::new(Int32Array::from(vec![Some(3), Some(4)])) as ArrayRef,
Arc::new(Int32Array::from(vec![Some(10), Some(30)])) as ArrayRef,
],
)?;
let right =
TestMemoryExec::try_new_exec(&[vec![right_batch]], right_schema, None)?;
let (columns, batches, metrics) = join_collect(
left,
right,
on,
&JoinType::Inner,
NullEquality::NullEqualsNull,
task_ctx,
)
.await?;
assert_eq!(columns, vec!["a1", "b1", "a2", "b1"]);
assert_batches_sorted_eq!(
[
"+----+----+----+----+",
"| a1 | b1 | a2 | b1 |",
"+----+----+----+----+",
"| 1 | 10 | 3 | 10 |",
"+----+----+----+----+",
],
&batches
);
assert_phj_used(&metrics, false);
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn test_null_aware_anti_join_probe_null(batch_size: usize) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, false);
let left = build_table_two_cols(
("c1", &vec![Some(1), Some(2), Some(3), Some(4)]),
("dummy", &vec![Some(10), Some(20), Some(30), Some(40)]),
);
let right = build_table_two_cols(
("c2", &vec![Some(1), Some(2), Some(3), None]),
("dummy", &vec![Some(100), Some(200), Some(300), Some(400)]),
);
let on = vec![(
Arc::new(Column::new_with_schema("c1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("c2", &right.schema())?) as _,
)];
let join = HashJoinExec::try_new(
left,
right,
on,
None,
&JoinType::LeftAnti,
None,
PartitionMode::CollectLeft,
NullEquality::NullEqualsNothing,
true, )?;
let stream = join.execute(0, task_ctx)?;
let batches = common::collect(stream).await?;
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
++
++
");
}
Ok(())
}
fn build_two_partition_probe_with_null_in_partition_0() -> Arc<dyn ExecutionPlan> {
let schema = Arc::new(Schema::new(vec![
Field::new("c2", DataType::Int32, true),
Field::new("dummy", DataType::Int32, true),
]));
let partition_0 = RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(Int32Array::from(vec![Some(1), None])),
Arc::new(Int32Array::from(vec![Some(100), Some(400)])),
],
)
.unwrap();
let partition_1 = RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(Int32Array::from(vec![Some(2)])),
Arc::new(Int32Array::from(vec![Some(200)])),
],
)
.unwrap();
TestMemoryExec::try_new_exec(
&[vec![partition_0], vec![partition_1]],
schema,
None,
)
.unwrap()
}
fn build_two_partition_dict_probe_with_logical_null_in_partition_0()
-> Arc<dyn ExecutionPlan> {
let dict_type =
DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Int32));
let schema = Arc::new(Schema::new(vec![
Field::new("c2", dict_type, true),
Field::new("dummy", DataType::Int32, true),
]));
let with_logical_null: ArrayRef = Arc::new(DictionaryArray::new(
Int32Array::from(vec![0, 1]),
Arc::new(Int32Array::from(vec![Some(1), None])),
));
assert_eq!(
with_logical_null.null_count(),
0,
"the probe NULL must be logical only, or this test stops covering \
the logical_null_count path"
);
assert!(
with_logical_null.logical_null_count() > 0,
"the probe key must carry a logical NULL"
);
let partition_0 = RecordBatch::try_new(
Arc::clone(&schema),
vec![
with_logical_null,
Arc::new(Int32Array::from(vec![Some(100), Some(400)])),
],
)
.unwrap();
let partition_1 = RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(DictionaryArray::new(
Int32Array::from(vec![0]),
Arc::new(Int32Array::from(vec![Some(2)])),
)),
Arc::new(Int32Array::from(vec![Some(200)])),
],
)
.unwrap();
TestMemoryExec::try_new_exec(
&[vec![partition_0], vec![partition_1]],
schema,
None,
)
.unwrap()
}
async fn collect_partitions_in_order(
join: &HashJoinExec,
order: &[usize],
task_ctx: &Arc<TaskContext>,
) -> Result<Vec<RecordBatch>> {
let mut batches = vec![];
for &partition in order {
let stream = join.execute(partition, Arc::clone(task_ctx))?;
batches.extend(common::collect(stream).await?);
}
Ok(batches)
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn test_null_aware_anti_join_probe_null_in_other_partition(
batch_size: usize,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, false);
for order in [[0, 1], [1, 0]] {
let left = build_table_two_cols(
("c1", &vec![Some(1), Some(2), Some(3), Some(4)]),
("dummy", &vec![Some(10), Some(20), Some(30), Some(40)]),
);
let right = build_two_partition_probe_with_null_in_partition_0();
let on = vec![(
Arc::new(Column::new_with_schema("c1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("c2", &right.schema())?) as _,
)];
let join = HashJoinExec::try_new(
left,
right,
on,
None,
&JoinType::LeftAnti,
None,
PartitionMode::CollectLeft,
NullEquality::NullEqualsNothing,
true, )?;
let batches = collect_partitions_in_order(&join, &order, &task_ctx).await?;
let rows: usize = batches.iter().map(|b| b.num_rows()).sum();
assert_eq!(
rows, 0,
"probe order {order:?} emitted rows although a probe partition saw NULL"
);
}
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn test_null_aware_anti_join_probe_logical_null_in_other_partition(
batch_size: usize,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, false);
for order in [[0, 1], [1, 0]] {
let left = build_table_dict_key(
"c1",
vec![Some(1), Some(2), Some(3), Some(4)],
vec![0, 1, 2, 3],
"dummy",
vec![Some(10), Some(20), Some(30), Some(40)],
);
let right = build_two_partition_dict_probe_with_logical_null_in_partition_0();
let on = vec![(
Arc::new(Column::new_with_schema("c1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("c2", &right.schema())?) as _,
)];
let join = HashJoinExec::try_new(
left,
right,
on,
None,
&JoinType::LeftAnti,
None,
PartitionMode::CollectLeft,
NullEquality::NullEqualsNothing,
true, )?;
let batches = collect_partitions_in_order(&join, &order, &task_ctx).await?;
let rows: usize = batches.iter().map(|b| b.num_rows()).sum();
assert_eq!(
rows, 0,
"probe order {order:?} emitted rows although a probe partition saw a logical NULL"
);
}
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn test_null_aware_left_mark_probe_null_in_other_partition(
batch_size: usize,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, false);
for order in [[0, 1], [1, 0]] {
let left = build_table_two_cols(
("c1", &vec![Some(1), Some(4)]),
("dummy", &vec![Some(10), Some(40)]),
);
let right = build_two_partition_probe_with_null_in_partition_0();
let on = vec![(
Arc::new(Column::new_with_schema("c1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("c2", &right.schema())?) as _,
)];
let join = HashJoinExec::try_new(
left,
right,
on,
None,
&JoinType::LeftMark,
None,
PartitionMode::CollectLeft,
NullEquality::NullEqualsNothing,
true, )?;
let batches = collect_partitions_in_order(&join, &order, &task_ctx).await?;
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+-------+------+
| c1 | dummy | mark |
+----+-------+------+
| 1 | 10 | true |
| 4 | 40 | |
+----+-------+------+
");
}
}
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn test_null_aware_left_mark_probe_logical_null_in_other_partition(
batch_size: usize,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, false);
for order in [[0, 1], [1, 0]] {
let left = build_table_dict_key(
"c1",
vec![Some(1), Some(4)],
vec![0, 1],
"dummy",
vec![Some(10), Some(40)],
);
let right = build_two_partition_dict_probe_with_logical_null_in_partition_0();
let on = vec![(
Arc::new(Column::new_with_schema("c1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("c2", &right.schema())?) as _,
)];
let join = HashJoinExec::try_new(
left,
right,
on,
None,
&JoinType::LeftMark,
None,
PartitionMode::CollectLeft,
NullEquality::NullEqualsNothing,
true,
)?;
let batches = collect_partitions_in_order(&join, &order, &task_ctx).await?;
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+-------+------+
| c1 | dummy | mark |
+----+-------+------+
| 1 | 10 | true |
| 4 | 40 | |
+----+-------+------+
");
}
}
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn test_null_aware_anti_join_build_null(batch_size: usize) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, false);
let left = build_table_two_cols(
("c1", &vec![Some(1), Some(4), None]),
("dummy", &vec![Some(10), Some(40), Some(0)]),
);
let right = build_table_two_cols(
("c2", &vec![Some(1), Some(2), Some(3)]),
("dummy", &vec![Some(100), Some(200), Some(300)]),
);
let on = vec![(
Arc::new(Column::new_with_schema("c1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("c2", &right.schema())?) as _,
)];
let join = HashJoinExec::try_new(
left,
right,
on,
None,
&JoinType::LeftAnti,
None,
PartitionMode::CollectLeft,
NullEquality::NullEqualsNothing,
true, )?;
let stream = join.execute(0, task_ctx)?;
let batches = common::collect(stream).await?;
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+-------+
| c1 | dummy |
+----+-------+
| 4 | 40 |
+----+-------+
");
}
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn test_null_aware_anti_join_no_nulls(batch_size: usize) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, false);
let left = build_table_two_cols(
("c1", &vec![Some(1), Some(2), Some(4), Some(5)]),
("dummy", &vec![Some(10), Some(20), Some(40), Some(50)]),
);
let right = build_table_two_cols(
("c2", &vec![Some(1), Some(2), Some(3)]),
("dummy", &vec![Some(100), Some(200), Some(300)]),
);
let on = vec![(
Arc::new(Column::new_with_schema("c1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("c2", &right.schema())?) as _,
)];
let join = HashJoinExec::try_new(
left,
right,
on,
None,
&JoinType::LeftAnti,
None,
PartitionMode::CollectLeft,
NullEquality::NullEqualsNothing,
true, )?;
let stream = join.execute(0, task_ctx)?;
let batches = common::collect(stream).await?;
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+-------+
| c1 | dummy |
+----+-------+
| 4 | 40 |
| 5 | 50 |
+----+-------+
");
}
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn test_null_aware_right_anti_build_null(batch_size: usize) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, false);
let left = build_table_two_cols(
("c1", &vec![Some(1), Some(2), Some(3), None]),
("dummy", &vec![Some(100), Some(200), Some(300), Some(400)]),
);
let right = build_table_two_cols(
("c2", &vec![Some(1), Some(2), Some(3), Some(4)]),
("dummy", &vec![Some(10), Some(20), Some(30), Some(40)]),
);
let on = vec![(
Arc::new(Column::new_with_schema("c1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("c2", &right.schema())?) as _,
)];
let join = HashJoinExec::try_new(
left,
right,
on,
None,
&JoinType::RightAnti,
None,
PartitionMode::CollectLeft,
NullEquality::NullEqualsNothing,
true,
)?;
let stream = join.execute(0, task_ctx)?;
let batches = common::collect(stream).await?;
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
++
++
");
}
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn test_null_aware_right_anti_probe_null(batch_size: usize) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, false);
let left = build_table_two_cols(
("c1", &vec![Some(1), Some(2), Some(3)]),
("dummy", &vec![Some(100), Some(200), Some(300)]),
);
let right = build_table_two_cols(
("c2", &vec![Some(1), Some(4), None]),
("dummy", &vec![Some(10), Some(40), Some(0)]),
);
let on = vec![(
Arc::new(Column::new_with_schema("c1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("c2", &right.schema())?) as _,
)];
let join = HashJoinExec::try_new(
left,
right,
on,
None,
&JoinType::RightAnti,
None,
PartitionMode::CollectLeft,
NullEquality::NullEqualsNothing,
true,
)?;
let stream = join.execute(0, task_ctx)?;
let batches = common::collect(stream).await?;
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+-------+
| c2 | dummy |
+----+-------+
| 4 | 40 |
+----+-------+
");
}
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn test_null_aware_right_anti_no_nulls(batch_size: usize) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, false);
let left = build_table_two_cols(
("c1", &vec![Some(1), Some(2), Some(3)]),
("dummy", &vec![Some(100), Some(200), Some(300)]),
);
let right = build_table_two_cols(
("c2", &vec![Some(1), Some(2), Some(4), Some(5)]),
("dummy", &vec![Some(10), Some(20), Some(40), Some(50)]),
);
let on = vec![(
Arc::new(Column::new_with_schema("c1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("c2", &right.schema())?) as _,
)];
let join = HashJoinExec::try_new(
left,
right,
on,
None,
&JoinType::RightAnti,
None,
PartitionMode::CollectLeft,
NullEquality::NullEqualsNothing,
true,
)?;
let stream = join.execute(0, task_ctx)?;
let batches = common::collect(stream).await?;
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+-------+
| c2 | dummy |
+----+-------+
| 4 | 40 |
| 5 | 50 |
+----+-------+
");
}
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn test_null_aware_right_anti_empty_build(batch_size: usize) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, false);
let left = build_table_two_cols(("c1", &vec![]), ("dummy", &vec![]));
let right = build_table_two_cols(
("c2", &vec![Some(1), None, Some(4)]),
("dummy", &vec![Some(10), Some(0), Some(40)]),
);
let on = vec![(
Arc::new(Column::new_with_schema("c1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("c2", &right.schema())?) as _,
)];
let join = HashJoinExec::try_new(
left,
right,
on,
None,
&JoinType::RightAnti,
None,
PartitionMode::CollectLeft,
NullEquality::NullEqualsNothing,
true,
)?;
let stream = join.execute(0, task_ctx)?;
let batches = common::collect(stream).await?;
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+-------+
| c2 | dummy |
+----+-------+
| | 0 |
| 1 | 10 |
| 4 | 40 |
+----+-------+
");
}
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn test_null_aware_right_anti_build_logical_null(
batch_size: usize,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, false);
let left = build_table_dict_key(
"c1",
vec![Some(1), None, Some(2)],
vec![0, 1, 2],
"dummy",
vec![Some(100), Some(200), Some(300)],
);
let left_key = left
.execute(0, Arc::clone(&task_ctx))?
.next()
.await
.unwrap()?;
assert_eq!(left_key.column(0).null_count(), 0);
assert_eq!(left_key.column(0).logical_null_count(), 1);
let right = build_table_dict_key(
"c2",
vec![Some(1), Some(2), Some(3), Some(4)],
vec![0, 1, 2, 3],
"dummy",
vec![Some(10), Some(20), Some(30), Some(40)],
);
let on = vec![(
Arc::new(Column::new_with_schema("c1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("c2", &right.schema())?) as _,
)];
let join = HashJoinExec::try_new(
left,
right,
on,
None,
&JoinType::RightAnti,
None,
PartitionMode::CollectLeft,
NullEquality::NullEqualsNothing,
true,
)?;
let stream = join.execute(0, task_ctx)?;
let batches = common::collect(stream).await?;
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
++
++
");
}
Ok(())
}
#[tokio::test]
async fn test_null_equal_dynamic_filter_keeps_probe_nulls_for_build_logical_null()
-> Result<()> {
let task_ctx = Arc::new(TaskContext::default());
let left = build_table_dict_key(
"c1",
vec![Some(1), None, Some(2)],
vec![0, 1, 2],
"d1",
vec![Some(100), Some(200), Some(300)],
);
let left_key = left
.execute(0, Arc::clone(&task_ctx))?
.next()
.await
.unwrap()?;
assert_eq!(left_key.column(0).null_count(), 0);
assert_eq!(left_key.column(0).logical_null_count(), 1);
let right = build_table_dict_key(
"c2",
vec![Some(1), None, Some(4)],
vec![0, 1, 2],
"d2",
vec![Some(10), Some(20), Some(40)],
);
let on = vec![(
Arc::new(Column::new_with_schema("c1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("c2", &right.schema())?) as _,
)];
let dynamic_filter = HashJoinExec::create_dynamic_filter(&on);
let consumer: Arc<dyn PhysicalExpr> = Arc::clone(&dynamic_filter) as _;
let right = Arc::new(FilterExecBuilder::new(consumer, right).build()?);
let mut join = HashJoinExec::try_new(
left,
right,
on,
None,
&JoinType::Inner,
None,
PartitionMode::CollectLeft,
NullEquality::NullEqualsNull,
false,
)?;
join.dynamic_filter = Some(HashJoinExecDynamicFilter {
filter: Arc::clone(&dynamic_filter),
build_accumulator: OnceLock::new(),
});
let stream = join.execute(0, task_ctx)?;
let batches = common::collect(stream).await?;
dynamic_filter.wait_complete().await;
let filter = dynamic_filter.current()?.to_string();
assert!(
filter.contains("c2@0 IS NULL OR"),
"expected an IS NULL disjunct in the pushed filter, got: {filter}"
);
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+-----+----+----+
| c1 | d1 | c2 | d2 |
+----+-----+----+----+
| | 200 | | 20 |
| 1 | 100 | 1 | 10 |
+----+-----+----+----+
");
}
Ok(())
}
#[tokio::test]
async fn test_partitioned_null_equal_dynamic_filter_keeps_probe_nulls_for_build_logical_null()
-> Result<()> {
let mut session_config = SessionConfig::default();
session_config
.options_mut()
.optimizer
.enable_dynamic_filter_pushdown = true;
let task_ctx =
Arc::new(TaskContext::default().with_session_config(session_config));
let partition_count = 4;
let left = build_table_dict_key(
"c1",
vec![Some(1), None, Some(2)],
vec![0, 1, 2],
"d1",
vec![Some(100), Some(200), Some(300)],
);
let right = build_table_dict_key(
"c2",
vec![Some(1), None, Some(4)],
vec![0, 1, 2],
"d2",
vec![Some(10), Some(20), Some(40)],
);
let left_key =
Arc::new(Column::new_with_schema("c1", &left.schema())?) as PhysicalExprRef;
let right_key =
Arc::new(Column::new_with_schema("c2", &right.schema())?) as PhysicalExprRef;
let on = vec![(Arc::clone(&left_key), Arc::clone(&right_key))];
let left_repartitioned: Arc<dyn ExecutionPlan> =
Arc::new(RepartitionExec::try_new(
left,
Partitioning::Hash(vec![left_key], partition_count),
)?);
let right_repartitioned: Arc<dyn ExecutionPlan> =
Arc::new(RepartitionExec::try_new(
right,
Partitioning::Hash(vec![Arc::clone(&right_key)], partition_count),
)?);
let dynamic_filter = HashJoinExec::create_dynamic_filter(&on);
let consumer: Arc<dyn PhysicalExpr> = Arc::clone(&dynamic_filter) as _;
let right_filtered: Arc<dyn ExecutionPlan> =
Arc::new(FilterExecBuilder::new(consumer, right_repartitioned).build()?);
let mut join = HashJoinExec::try_new(
left_repartitioned,
right_filtered,
on,
None,
&JoinType::Inner,
None,
PartitionMode::Partitioned,
NullEquality::NullEqualsNull,
false,
)?;
join.dynamic_filter = Some(HashJoinExecDynamicFilter {
filter: Arc::clone(&dynamic_filter),
build_accumulator: OnceLock::new(),
});
let batches = crate::execution_plan::collect(Arc::new(join), task_ctx).await?;
dynamic_filter.wait_complete().await;
let filter = dynamic_filter.current()?.to_string();
assert!(
filter.starts_with("c2@0 IS NULL OR"),
"expected the IS NULL disjunct to wrap the whole routed filter, got: {filter}"
);
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+-----+----+----+
| c1 | d1 | c2 | d2 |
+----+-----+----+----+
| | 200 | | 20 |
| 1 | 100 | 1 | 10 |
+----+-----+----+----+
");
}
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn test_null_aware_right_anti_probe_logical_null(
batch_size: usize,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, false);
let left = build_table_dict_key(
"c1",
vec![Some(1), Some(2), Some(3)],
vec![0, 1, 2],
"dummy",
vec![Some(100), Some(200), Some(300)],
);
let right = build_table_dict_key(
"c2",
vec![Some(1), None, Some(4)],
vec![0, 1, 2],
"dummy",
vec![Some(10), Some(0), Some(40)],
);
let right_key = right
.execute(0, Arc::clone(&task_ctx))?
.next()
.await
.unwrap()?;
assert_eq!(right_key.column(0).null_count(), 0);
assert_eq!(right_key.column(0).logical_null_count(), 1);
let on = vec![(
Arc::new(Column::new_with_schema("c1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("c2", &right.schema())?) as _,
)];
let join = HashJoinExec::try_new(
left,
right,
on,
None,
&JoinType::RightAnti,
None,
PartitionMode::CollectLeft,
NullEquality::NullEqualsNothing,
true,
)?;
let stream = join.execute(0, task_ctx)?;
let batches = common::collect(stream).await?;
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+-------+
| c2 | dummy |
+----+-------+
| 4 | 40 |
+----+-------+
");
}
Ok(())
}
#[tokio::test]
async fn test_null_aware_validation_wrong_join_type() {
let left =
build_table_two_cols(("c1", &vec![Some(1)]), ("dummy", &vec![Some(10)]));
let right =
build_table_two_cols(("c2", &vec![Some(1)]), ("dummy", &vec![Some(100)]));
let on = vec![(
Arc::new(Column::new_with_schema("c1", &left.schema()).unwrap()) as _,
Arc::new(Column::new_with_schema("c2", &right.schema()).unwrap()) as _,
)];
let result = HashJoinExec::try_new(
left,
right,
on,
None,
&JoinType::Inner,
None,
PartitionMode::CollectLeft,
NullEquality::NullEqualsNothing,
true, );
assert!(result.is_err());
assert!(result.unwrap_err().to_string().contains(
"null_aware can only be true for LeftAnti joins and RightAnti joins"
));
}
#[tokio::test]
async fn test_null_aware_validation_right_anti_partitioned() {
let left =
build_table_two_cols(("c1", &vec![Some(1)]), ("dummy", &vec![Some(10)]));
let right =
build_table_two_cols(("c2", &vec![Some(1)]), ("dummy", &vec![Some(100)]));
let on = vec![(
Arc::new(Column::new_with_schema("c1", &left.schema()).unwrap()) as _,
Arc::new(Column::new_with_schema("c2", &right.schema()).unwrap()) as _,
)];
let result = HashJoinExec::try_new(
left,
right,
on,
None,
&JoinType::RightAnti,
None,
PartitionMode::Partitioned,
NullEquality::NullEqualsNothing,
true,
);
assert!(result.is_err());
assert!(result.unwrap_err().to_string().contains(
"null_aware can only be true for LeftAnti joins and RightAnti joins"
));
}
#[tokio::test]
async fn test_null_aware_validation_left_anti_partitioned() {
let left =
build_table_two_cols(("c1", &vec![Some(1)]), ("dummy", &vec![Some(10)]));
let right =
build_table_two_cols(("c2", &vec![Some(1)]), ("dummy", &vec![Some(100)]));
let on = vec![(
Arc::new(Column::new_with_schema("c1", &left.schema()).unwrap()) as _,
Arc::new(Column::new_with_schema("c2", &right.schema()).unwrap()) as _,
)];
let err = HashJoinExec::try_new(
left,
right,
on,
None,
&JoinType::LeftAnti,
None,
PartitionMode::Partitioned,
NullEquality::NullEqualsNothing,
true,
)
.expect_err("null_aware LeftAnti must reject PartitionMode::Partitioned");
assert!(
err.to_string()
.contains("null_aware joins require PartitionMode::CollectLeft"),
"{err}"
);
}
fn try_new_scalar_not_in(
left: Arc<dyn ExecutionPlan>,
right: Arc<dyn ExecutionPlan>,
on: JoinOn,
filter: Option<JoinFilter>,
join_type: JoinType,
partition_mode: PartitionMode,
) -> Result<HashJoinExec> {
HashJoinExecBuilder::new(left, right, on, join_type)
.with_filter(filter)
.with_partition_mode(partition_mode)
.with_null_aware(true)
.with_null_aware_value_keys(1)
.build()
}
#[tokio::test]
async fn test_null_aware_validation_partitioned() {
let left = build_table(("a", &vec![1]), ("b", &vec![2]), ("c", &vec![3]));
let right = build_table(("x", &vec![1]), ("y", &vec![2]), ("z", &vec![3]));
let on = vec![
(
Arc::new(Column::new_with_schema("a", &left.schema()).unwrap()) as _,
Arc::new(Column::new_with_schema("x", &right.schema()).unwrap()) as _,
),
(
Arc::new(Column::new_with_schema("b", &left.schema()).unwrap()) as _,
Arc::new(Column::new_with_schema("y", &right.schema()).unwrap()) as _,
),
];
let result = try_new_scalar_not_in(
left,
right,
on,
None,
JoinType::LeftMark,
PartitionMode::Partitioned,
);
assert!(result.is_err());
assert!(
result
.unwrap_err()
.to_string()
.contains("null_aware joins require PartitionMode::CollectLeft")
);
}
#[rstest]
#[case::right_anti_multi_key(JoinType::RightAnti, true, false)]
#[case::right_anti_filter(JoinType::RightAnti, false, true)]
#[case::left_anti_filter(JoinType::LeftAnti, false, true)]
fn test_null_aware_correlated_anti_join_accepted(
#[case] join_type: JoinType,
#[case] multi_key: bool,
#[case] with_filter: bool,
) -> Result<()> {
let left =
build_table_two_cols(("c1", &vec![Some(1)]), ("dummy", &vec![Some(10)]));
let right =
build_table_two_cols(("c2", &vec![Some(1)]), ("dummy", &vec![Some(100)]));
let key = |l: &str, r: &str| -> Result<(PhysicalExprRef, PhysicalExprRef)> {
Ok((
Arc::new(Column::new_with_schema(l, &left.schema())?) as _,
Arc::new(Column::new_with_schema(r, &right.schema())?) as _,
))
};
let mut on = vec![key("c1", "c2")?];
if multi_key {
on.push(key("dummy", "dummy")?);
}
let join = try_new_scalar_not_in(
Arc::clone(&left),
Arc::clone(&right),
on,
with_filter.then(prepare_join_filter),
join_type,
PartitionMode::CollectLeft,
)?;
let scope = NotInScope::Correlated { value_keys: 1 };
let expected = match join_type {
JoinType::RightAnti => NotIn::ProbeRows { scope },
_ => NotIn::BuildRows {
scope,
output: NotInOutput::Rows,
},
};
assert_eq!(join.not_in()?, Some(expected));
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn test_null_aware_left_anti_probe_logical_null(
batch_size: usize,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, false);
let left = build_table_dict_key(
"c1",
vec![Some(1), Some(2), Some(3)],
vec![0, 1, 2],
"dummy",
vec![Some(100), Some(200), Some(300)],
);
let right = build_table_dict_key(
"c2",
vec![Some(1), None, Some(4)],
vec![0, 1, 2],
"dummy",
vec![Some(10), Some(0), Some(40)],
);
let right_key = right
.execute(0, Arc::clone(&task_ctx))?
.next()
.await
.unwrap()?;
assert_eq!(right_key.column(0).null_count(), 0);
assert_eq!(right_key.column(0).logical_null_count(), 1);
let on = vec![(
Arc::new(Column::new_with_schema("c1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("c2", &right.schema())?) as _,
)];
let join = HashJoinExec::try_new(
left,
right,
on,
None,
&JoinType::LeftAnti,
None,
PartitionMode::CollectLeft,
NullEquality::NullEqualsNothing,
true,
)?;
let stream = join.execute(0, task_ctx)?;
let batches = common::collect(stream).await?;
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
++
++
");
}
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn test_null_aware_left_anti_build_logical_null(
batch_size: usize,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, false);
let left = build_table_dict_key(
"c1",
vec![Some(1), None, Some(2)],
vec![0, 1, 2],
"dummy",
vec![Some(10), Some(0), Some(20)],
);
let left_key = left
.execute(0, Arc::clone(&task_ctx))?
.next()
.await
.unwrap()?;
assert_eq!(left_key.column(0).null_count(), 0);
assert_eq!(left_key.column(0).logical_null_count(), 1);
let right = build_table_dict_key(
"c2",
vec![Some(5), Some(6)],
vec![0, 1],
"dummy",
vec![Some(50), Some(60)],
);
let on = vec![(
Arc::new(Column::new_with_schema("c1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("c2", &right.schema())?) as _,
)];
let join = HashJoinExec::try_new(
left,
right,
on,
None,
&JoinType::LeftAnti,
None,
PartitionMode::CollectLeft,
NullEquality::NullEqualsNothing,
true,
)?;
let stream = join.execute(0, task_ctx)?;
let batches = common::collect(stream).await?;
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+-------+
| c1 | dummy |
+----+-------+
| 1 | 10 |
| 2 | 20 |
+----+-------+
");
}
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn test_null_aware_left_mark_build_logical_null(
batch_size: usize,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, false);
let left = build_table_dict_key(
"c1",
vec![Some(1), None, Some(4)],
vec![0, 1, 2],
"dummy",
vec![Some(10), Some(0), Some(40)],
);
let left_key = left
.execute(0, Arc::clone(&task_ctx))?
.next()
.await
.unwrap()?;
assert_eq!(left_key.column(0).null_count(), 0);
assert_eq!(left_key.column(0).logical_null_count(), 1);
let right = build_table_dict_key(
"c2",
vec![Some(1), Some(2), Some(3)],
vec![0, 1, 2],
"dummy",
vec![Some(100), Some(200), Some(300)],
);
let on = vec![(
Arc::new(Column::new_with_schema("c1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("c2", &right.schema())?) as _,
)];
let join = HashJoinExec::try_new(
left,
right,
on,
None,
&JoinType::LeftMark,
None,
PartitionMode::CollectLeft,
NullEquality::NullEqualsNothing,
true,
)?;
let stream = join.execute(0, task_ctx)?;
let batches = common::collect(stream).await?;
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+-------+-------+
| c1 | dummy | mark |
+----+-------+-------+
| | 0 | |
| 1 | 10 | true |
| 4 | 40 | false |
+----+-------+-------+
");
}
Ok(())
}
fn build_single_column_table(name: &str, array: ArrayRef) -> Arc<dyn ExecutionPlan> {
let schema = Arc::new(Schema::new(vec![Field::new(
name,
array.data_type().clone(),
true,
)]));
let batch = RecordBatch::try_new(Arc::clone(&schema), vec![array]).unwrap();
TestMemoryExec::try_new_exec(&[vec![batch]], schema, None).unwrap()
}
fn nested_dictionary_array(
leaf_values: Vec<Option<i32>>,
inner_keys: Vec<i32>,
outer_keys: Vec<i32>,
) -> ArrayRef {
let leaf_values: ArrayRef = Arc::new(Int32Array::from(leaf_values));
let inner_keys = Int32Array::from(inner_keys);
let inner_values: ArrayRef =
Arc::new(DictionaryArray::<Int32Type>::new(inner_keys, leaf_values));
Arc::new(DictionaryArray::<Int32Type>::new(
Int32Array::from(outer_keys),
inner_values,
))
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn test_null_aware_left_mark_nested_dictionary_logical_null(
batch_size: usize,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, false);
let left_key = nested_dictionary_array(
vec![Some(1), None, Some(4)],
vec![0, 1, 2],
vec![0, 1, 2],
);
assert_eq!(left_key.logical_null_count(), 1);
let left = build_single_column_table("c1", left_key);
let right = build_single_column_table(
"c2",
nested_dictionary_array(
vec![Some(1), Some(2), Some(3)],
vec![0, 1, 2],
vec![0, 1, 2],
),
);
let on = vec![(
Arc::new(Column::new_with_schema("c1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("c2", &right.schema())?) as _,
)];
let join = HashJoinExec::try_new(
left,
right,
on,
None,
&JoinType::LeftMark,
None,
PartitionMode::CollectLeft,
NullEquality::NullEqualsNothing,
true,
)?;
let batches = common::collect(join.execute(0, task_ctx)?).await?;
let marks = batches
.iter()
.flat_map(|batch| batch.column(batch.num_columns() - 1).as_boolean().iter())
.collect::<Vec<_>>();
assert_eq!(marks, vec![Some(true), None, Some(false)]);
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn test_null_aware_left_mark_correlated_build_null_only(
batch_size: usize,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, false);
let left = build_table_two_cols(
("id", &vec![Some(1), None, None, Some(3)]),
("grp", &vec![Some(1), Some(1), Some(2), Some(3)]),
);
let right = build_table_two_cols(
("id", &vec![Some(2), Some(1)]),
("grp", &vec![Some(1), Some(2)]),
);
let on = vec![
(
Arc::new(Column::new_with_schema("id", &left.schema())?) as _,
Arc::new(Column::new_with_schema("id", &right.schema())?) as _,
),
(
Arc::new(Column::new_with_schema("grp", &left.schema())?) as _,
Arc::new(Column::new_with_schema("grp", &right.schema())?) as _,
),
];
let join = try_new_scalar_not_in(
left,
right,
on,
None,
JoinType::LeftMark,
PartitionMode::CollectLeft,
)?;
let stream = join.execute(0, task_ctx)?;
let batches = common::collect(stream).await?;
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+-----+-------+
| id | grp | mark |
+----+-----+-------+
| | 1 | |
| | 2 | |
| 1 | 1 | false |
| 3 | 3 | false |
+----+-----+-------+
");
}
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn test_null_aware_left_mark_correlated_probe_null_only(
batch_size: usize,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, false);
let left = build_table_two_cols(
("id", &vec![Some(1), Some(2), Some(5), Some(7)]),
("grp", &vec![Some(1), Some(1), Some(2), Some(3)]),
);
let right = build_table_two_cols(
("id", &vec![Some(2), None, Some(4)]),
("grp", &vec![Some(1), Some(1), Some(2)]),
);
let on = vec![
(
Arc::new(Column::new_with_schema("id", &left.schema())?) as _,
Arc::new(Column::new_with_schema("id", &right.schema())?) as _,
),
(
Arc::new(Column::new_with_schema("grp", &left.schema())?) as _,
Arc::new(Column::new_with_schema("grp", &right.schema())?) as _,
),
];
let join = try_new_scalar_not_in(
left,
right,
on,
None,
JoinType::LeftMark,
PartitionMode::CollectLeft,
)?;
let stream = join.execute(0, task_ctx)?;
let batches = common::collect(stream).await?;
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+-----+-------+
| id | grp | mark |
+----+-----+-------+
| 1 | 1 | |
| 2 | 1 | true |
| 5 | 2 | false |
| 7 | 3 | false |
+----+-----+-------+
");
}
Ok(())
}
fn prepare_second_column_gt_filter() -> JoinFilter {
let column_indices = vec![
ColumnIndex {
index: 1,
side: JoinSide::Left,
},
ColumnIndex {
index: 1,
side: JoinSide::Right,
},
];
let intermediate_schema = Schema::new(vec![
Field::new("z", DataType::Int32, true),
Field::new("z", DataType::Int32, true),
]);
let filter_expression = Arc::new(BinaryExpr::new(
Arc::new(Column::new("z", 0)),
Operator::Gt,
Arc::new(Column::new("z", 1)),
)) as Arc<dyn PhysicalExpr>;
JoinFilter::new(
filter_expression,
column_indices,
Arc::new(intermediate_schema),
)
}
fn build_null_aware_filter_only_inputs()
-> (Arc<dyn ExecutionPlan>, Arc<dyn ExecutionPlan>, JoinOn) {
let left = build_table_two_cols(
("id", &vec![Some(1), Some(2), None, Some(4), None, Some(5)]),
(
"z",
&vec![Some(10), Some(20), Some(30), Some(40), Some(1), Some(1)],
),
);
let right = build_table_two_cols(
("id", &vec![Some(1), None, Some(4), None]),
("z", &vec![Some(5), Some(50), Some(35), Some(2)]),
);
let on = vec![(
Arc::new(Column::new_with_schema("id", &left.schema()).unwrap()) as _,
Arc::new(Column::new_with_schema("id", &right.schema()).unwrap()) as _,
)];
(left, right, on)
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn test_null_aware_left_anti_filter_only(batch_size: usize) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, false);
let (left, right, on) = build_null_aware_filter_only_inputs();
let join = HashJoinExec::try_new(
left,
right,
on,
Some(prepare_second_column_gt_filter()),
&JoinType::LeftAnti,
None,
PartitionMode::CollectLeft,
NullEquality::NullEqualsNothing,
true,
)?;
let stream = join.execute(0, task_ctx)?;
let batches = common::collect(stream).await?;
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+---+
| id | z |
+----+---+
| | 1 |
| 5 | 1 |
+----+---+
");
}
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn test_null_aware_left_mark_filter_only(batch_size: usize) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, false);
let (left, right, on) = build_null_aware_filter_only_inputs();
let join = HashJoinExec::try_new(
left,
right,
on,
Some(prepare_second_column_gt_filter()),
&JoinType::LeftMark,
None,
PartitionMode::CollectLeft,
NullEquality::NullEqualsNothing,
true,
)?;
let stream = join.execute(0, task_ctx)?;
let batches = common::collect(stream).await?;
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+-------+
| id | z | mark |
+----+----+-------+
| | 1 | false |
| | 30 | |
| 1 | 10 | true |
| 2 | 20 | |
| 4 | 40 | true |
| 5 | 1 | false |
+----+----+-------+
");
}
Ok(())
}
#[test]
fn test_null_aware_validation_value_keys() -> Result<()> {
let left = build_table_two_cols(("a", &vec![Some(1)]), ("b", &vec![None]));
let right = build_table_two_cols(("x", &vec![Some(1)]), ("y", &vec![Some(5)]));
let key = |l: &str, r: &str| -> Result<(PhysicalExprRef, PhysicalExprRef)> {
Ok((
Arc::new(Column::new_with_schema(l, &left.schema())?) as _,
Arc::new(Column::new_with_schema(r, &right.schema())?) as _,
))
};
let two_keys = vec![key("a", "x")?, key("b", "y")?];
let build = |on: JoinOn, join_type, partition_mode, value_keys| {
HashJoinExecBuilder::new(Arc::clone(&left), Arc::clone(&right), on, join_type)
.with_partition_mode(partition_mode)
.with_null_aware(true)
.with_null_aware_value_keys(value_keys)
.build()
};
for (value_keys, expected) in [
(
0,
"join with 2 keys needs the number of its `NOT IN` value keys, set it with `with_null_aware_value_keys`",
),
(3, "needs between 1 and 2 `NOT IN` value keys"),
] {
let err = build(
two_keys.clone(),
JoinType::LeftAnti,
PartitionMode::CollectLeft,
value_keys,
)
.unwrap_err();
assert!(err.to_string().contains(expected), "{err}");
}
let err = HashJoinExec::try_new(
Arc::clone(&left),
Arc::clone(&right),
two_keys.clone(),
None,
&JoinType::LeftAnti,
None,
PartitionMode::CollectLeft,
NullEquality::NullEqualsNothing,
true,
)
.unwrap_err();
assert!(
err.to_string().contains("with_null_aware_value_keys"),
"{err}"
);
let join = build(
vec![key("a", "x")?],
JoinType::LeftAnti,
PartitionMode::CollectLeft,
0,
)?;
assert_eq!(join.not_in()?.map(NotIn::value_keys), Some(1));
for (on, join_type, partition_mode, expected) in [
(
two_keys.clone(),
JoinType::Inner,
PartitionMode::CollectLeft,
"null_aware can only be true for LeftAnti joins",
),
(
two_keys.clone(),
JoinType::RightAnti,
PartitionMode::Partitioned,
"null_aware can only be true for LeftAnti joins",
),
(
two_keys,
JoinType::LeftAnti,
PartitionMode::Partitioned,
"null_aware joins require PartitionMode::CollectLeft",
),
(
vec![],
JoinType::LeftAnti,
PartitionMode::CollectLeft,
"On constraints in HashJoinExec should be non-empty",
),
] {
let err = build(on, join_type, partition_mode, 0).unwrap_err();
assert!(err.to_string().contains(expected), "{join_type}: {err}");
}
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn test_null_aware_left_anti_multi_column_scope(
batch_size: usize,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, false);
fn table(
id: Vec<Option<i32>>,
g1: Vec<Option<i32>>,
g2: Vec<Option<i32>>,
) -> Arc<dyn ExecutionPlan> {
let schema = Arc::new(Schema::new(vec![
Field::new("id", DataType::Int32, true),
Field::new("g1", DataType::Int32, true),
Field::new("g2", DataType::Int32, true),
]));
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(Int32Array::from(id)),
Arc::new(Int32Array::from(g1)),
Arc::new(Int32Array::from(g2)),
],
)
.unwrap();
TestMemoryExec::try_new_exec(&[vec![batch]], schema, None).unwrap()
}
let left = table(
vec![
Some(1),
Some(2),
None,
None,
Some(6),
Some(8),
Some(9),
Some(10),
None,
],
vec![
Some(1),
Some(1),
Some(1),
Some(1),
Some(1),
Some(1),
Some(1),
Some(2),
Some(3),
],
vec![
Some(1),
Some(1),
Some(1),
Some(1),
Some(2),
Some(2),
Some(2),
Some(1),
Some(3),
],
);
let right = table(
vec![
Some(2),
Some(3),
Some(4),
Some(5),
None,
None,
Some(7),
Some(11),
],
vec![
Some(1),
Some(1),
Some(1),
Some(1),
Some(1),
Some(1),
Some(1),
Some(2),
],
vec![
Some(1),
Some(1),
Some(1),
Some(1),
Some(2),
Some(2),
Some(2),
Some(1),
],
);
let on = ["id", "g1", "g2"]
.into_iter()
.map(|name| {
Ok((
Arc::new(Column::new_with_schema(name, &left.schema())?) as _,
Arc::new(Column::new_with_schema(name, &right.schema())?) as _,
))
})
.collect::<Result<JoinOn>>()?;
let left_anti = try_new_scalar_not_in(
Arc::clone(&left),
Arc::clone(&right),
on.clone(),
None,
JoinType::LeftAnti,
PartitionMode::CollectLeft,
)?;
let right_anti = swap_for_separate_execution(&left_anti)?;
let batches =
common::collect(left_anti.execute(0, Arc::clone(&task_ctx))?).await?;
let swapped = common::collect(right_anti.execute(0, task_ctx)?).await?;
assert_eq!(
batches_to_sort_string(&batches),
batches_to_sort_string(&swapped)
);
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+----+
| id | g1 | g2 |
+----+----+----+
| | 3 | 3 |
| 1 | 1 | 1 |
| 10 | 2 | 1 |
+----+----+----+
");
}
Ok(())
}
fn swap_for_separate_execution(
left_anti: &HashJoinExec,
) -> Result<Arc<dyn ExecutionPlan>> {
let swapped = left_anti.swap_inputs(PartitionMode::CollectLeft)?;
let swapped = swapped.downcast_ref::<HashJoinExec>().unwrap();
Ok(Arc::new(swapped.builder().reset_state().build()?))
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn test_null_aware_correlated_all_null_build_values(
batch_size: usize,
) -> Result<()> {
fn table(id: Vec<Option<i32>>, g: Vec<Option<i32>>) -> RecordBatch {
let schema = Arc::new(Schema::new(vec![
Field::new("id", DataType::Int32, true),
Field::new("g", DataType::Int32, true),
]));
RecordBatch::try_new(
schema,
vec![
Arc::new(Int32Array::from(id)),
Arc::new(Int32Array::from(g)),
],
)
.unwrap()
}
let build = table(vec![None, None, None], vec![Some(1), Some(2), Some(3)]);
let probe = [
table(vec![Some(5)], vec![Some(1)]),
table(vec![Some(7), Some(9)], vec![Some(2), Some(4)]),
];
let mut results = vec![];
for join_type in [JoinType::LeftAnti, JoinType::LeftMark, JoinType::RightAnti] {
let task_ctx = prepare_task_ctx(batch_size, false);
let left = TestMemoryExec::try_new_exec(
&[vec![build.clone()]],
build.schema(),
None,
)?;
let right =
TestMemoryExec::try_new_exec(&[probe.to_vec()], probe[0].schema(), None)?;
let on = ["id", "g"]
.into_iter()
.map(|name| {
Ok((
Arc::new(Column::new_with_schema(name, &left.schema())?) as _,
Arc::new(Column::new_with_schema(name, &right.schema())?) as _,
))
})
.collect::<Result<JoinOn>>()?;
let join = try_new_scalar_not_in(
left,
right,
on,
None,
join_type,
PartitionMode::CollectLeft,
)?;
let batches = common::collect(join.execute(0, task_ctx)?).await?;
results.push(batches_to_sort_string(&batches));
}
allow_duplicates! {
assert_snapshot!(results.join("\n"), @r"
+----+---+
| id | g |
+----+---+
| | 3 |
+----+---+
+----+---+-------+
| id | g | mark |
+----+---+-------+
| | 1 | |
| | 2 | |
| | 3 | false |
+----+---+-------+
+----+---+
| id | g |
+----+---+
| 9 | 4 |
+----+---+
");
}
Ok(())
}
#[apply(hash_join_exec_configs)]
#[tokio::test]
async fn test_null_aware_left_anti_float_scope_negative_zero(
batch_size: usize,
) -> Result<()> {
let task_ctx = prepare_task_ctx(batch_size, false);
fn table(
id: Vec<Option<i32>>,
g1: Vec<f64>,
g2: Vec<f64>,
) -> Arc<dyn ExecutionPlan> {
let schema = Arc::new(Schema::new(vec![
Field::new("id", DataType::Int32, true),
Field::new("g1", DataType::Float64, true),
Field::new("g2", DataType::Float64, true),
]));
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(Int32Array::from(id)),
Arc::new(Float64Array::from(g1)),
Arc::new(Float64Array::from(g2)),
],
)
.unwrap();
TestMemoryExec::try_new_exec(&[vec![batch]], schema, None).unwrap()
}
let left = table(
vec![Some(1), Some(3), None, Some(4), Some(5), None, Some(6)],
vec![-0.0, -0.0, -0.0, 2.0, -0.0, 3.0, 2.0],
vec![1.0, 1.0, 1.0, -0.0, -0.0, -0.0, 1.0],
);
let right = table(
vec![Some(1), Some(2), None, Some(7)],
vec![0.0, 0.0, 2.0, 2.0],
vec![1.0, 1.0, 0.0, 1.0],
);
let on = ["id", "g1", "g2"]
.into_iter()
.map(|name| {
Ok((
Arc::new(Column::new_with_schema(name, &left.schema())?) as _,
Arc::new(Column::new_with_schema(name, &right.schema())?) as _,
))
})
.collect::<Result<JoinOn>>()?;
let join = try_new_scalar_not_in(
left,
right,
on,
None,
JoinType::LeftAnti,
PartitionMode::CollectLeft,
)?;
let stream = join.execute(0, task_ctx)?;
let batches = common::collect(stream).await?;
allow_duplicates! {
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+------+------+
| id | g1 | g2 |
+----+------+------+
| | 3.0 | -0.0 |
| 3 | -0.0 | 1.0 |
| 5 | -0.0 | -0.0 |
| 6 | 2.0 | 1.0 |
+----+------+------+
");
}
Ok(())
}
#[test]
fn test_lr_is_preserved() {
assert_eq!(lr_is_preserved(JoinType::Inner), (true, true));
assert_eq!(lr_is_preserved(JoinType::Left), (true, false));
assert_eq!(lr_is_preserved(JoinType::Right), (false, true));
assert_eq!(lr_is_preserved(JoinType::Full), (false, false));
assert_eq!(lr_is_preserved(JoinType::LeftSemi), (true, true));
assert_eq!(lr_is_preserved(JoinType::LeftAnti), (true, false));
assert_eq!(lr_is_preserved(JoinType::LeftMark), (true, false));
assert_eq!(lr_is_preserved(JoinType::RightSemi), (true, true));
assert_eq!(lr_is_preserved(JoinType::RightAnti), (false, true));
assert_eq!(lr_is_preserved(JoinType::RightMark), (false, true));
}
#[test]
fn test_with_dynamic_filter() -> Result<()> {
let (_, _, on) = build_schema_and_on()?;
let left = build_table(("a1", &vec![1]), ("b1", &vec![1]), ("c1", &vec![1]));
let right = build_table(("a2", &vec![1]), ("b1", &vec![1]), ("c2", &vec![1]));
let join = HashJoinExec::try_new(
left,
right,
on,
None,
&JoinType::Inner,
None,
PartitionMode::CollectLeft,
NullEquality::NullEqualsNothing,
false,
)?;
assert!(join.dynamic_expressions_produced().is_empty());
let df = Arc::new(DynamicFilterPhysicalExpr::new(
vec![Arc::new(Column::new("b1", 1)) as _],
lit(true),
));
let join = join.set_dynamic_filter(Arc::clone(&df))?;
let produced = join.dynamic_expressions_produced();
assert_eq!(produced.len(), 1);
assert_eq!(
produced[0]
.expression_id()
.expect("DynamicFilterPhysicalExpr always has an expression_id"),
df.expression_id()
.expect("DynamicFilterPhysicalExpr always has an expression_id"),
);
Ok(())
}
#[test]
fn test_swap_inputs_rejects_dynamic_filter() -> Result<()> {
let left = build_table(
("l_key", &vec![1]),
("l_payload", &vec![10]),
("l_other", &vec![100]),
);
let right = build_table(
("r_payload", &vec![20]),
("r_key", &vec![1]),
("r_other", &vec![200]),
);
let on = vec![(
Arc::new(Column::new_with_schema("l_key", &left.schema())?) as _,
Arc::new(Column::new_with_schema("r_key", &right.schema())?) as _,
)];
let dynamic_filter = HashJoinExec::create_dynamic_filter(&on);
let join = HashJoinExec::try_new(
left,
right,
on,
None,
&JoinType::LeftSemi,
None,
PartitionMode::CollectLeft,
NullEquality::NullEqualsNothing,
false,
)?
.set_dynamic_filter(dynamic_filter)?;
let err = join.swap_inputs(PartitionMode::CollectLeft).unwrap_err();
assert_contains!(
err.to_string(),
"Cannot swap HashJoinExec inputs after dynamic filters have been constructed"
);
Ok(())
}
#[test]
fn test_dynamic_filter_pushdown_allowed_for_null_equal_join() -> Result<()> {
let (_, _, on) = build_schema_and_on()?;
let left = build_table(("a1", &vec![1]), ("b1", &vec![1]), ("c1", &vec![1]));
let right = build_table(("a2", &vec![1]), ("b1", &vec![1]), ("c2", &vec![1]));
let mut session_config = SessionConfig::default();
session_config
.options_mut()
.optimizer
.enable_join_dynamic_filter_pushdown = true;
let join = HashJoinExec::try_new(
left,
right,
on,
None,
&JoinType::RightSemi,
None,
PartitionMode::CollectLeft,
NullEquality::NullEqualsNull,
false,
)?;
assert!(join.allow_join_dynamic_filter_pushdown(session_config.options()));
Ok(())
}
#[test]
fn test_dynamic_filter_pushdown_rejects_null_aware_nullable_build_key() -> Result<()>
{
let left = build_table_two_cols(
("a1", &vec![Some(1), None]),
("b1", &vec![Some(1), Some(2)]),
);
let right = build_table_two_cols(
("a2", &vec![Some(2), Some(3)]),
("b2", &vec![Some(1), Some(2)]),
);
let on = vec![(
Arc::new(Column::new_with_schema("a1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("a2", &right.schema())?) as _,
)];
let mut session_config = SessionConfig::default();
session_config
.options_mut()
.optimizer
.enable_join_dynamic_filter_pushdown = true;
let join = HashJoinExec::try_new(
left,
right,
on,
None,
&JoinType::LeftAnti,
None,
PartitionMode::CollectLeft,
NullEquality::NullEqualsNothing,
true,
)?;
assert!(!join.allow_join_dynamic_filter_pushdown(session_config.options()));
Ok(())
}
#[test]
fn test_dynamic_filter_pushdown_allows_null_aware_non_null_build_key() -> Result<()> {
let left = build_table(("a1", &vec![1]), ("b1", &vec![1]), ("c1", &vec![1]));
let right = build_table(("a2", &vec![2]), ("b2", &vec![2]), ("c2", &vec![2]));
let on = vec![(
Arc::new(Column::new_with_schema("a1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("a2", &right.schema())?) as _,
)];
let mut session_config = SessionConfig::default();
session_config
.options_mut()
.optimizer
.enable_join_dynamic_filter_pushdown = true;
let join = HashJoinExec::try_new(
left,
right,
on,
None,
&JoinType::LeftAnti,
None,
PartitionMode::CollectLeft,
NullEquality::NullEqualsNothing,
true,
)?;
assert!(join.allow_join_dynamic_filter_pushdown(session_config.options()));
Ok(())
}
fn range_partitioned_dynamic_filter_test_join(
left_split: i32,
right_split: i32,
) -> Result<(HashJoinExec, JoinOn)> {
let (left_schema, right_schema, on) = build_schema_and_on()?;
let left_partitioning = Partitioning::Range(RangePartitioning::try_new(
[PhysicalSortExpr {
expr: Arc::clone(&on[0].0),
options: Default::default(),
}]
.into(),
vec![SplitPoint::new(vec![ScalarValue::Int32(Some(left_split))])],
)?);
let right_partitioning = Partitioning::Range(RangePartitioning::try_new(
[PhysicalSortExpr {
expr: Arc::clone(&on[0].1),
options: Default::default(),
}]
.into(),
vec![SplitPoint::new(vec![ScalarValue::Int32(Some(right_split))])],
)?);
let left = Arc::new(PartitionedTestExec::try_new(
left_schema,
left_partitioning,
)?);
let right = Arc::new(PartitionedTestExec::try_new(
right_schema,
right_partitioning,
)?);
let join = HashJoinExec::try_new(
left,
right,
on.clone(),
None,
&JoinType::Inner,
None,
PartitionMode::Partitioned,
NullEquality::NullEqualsNothing,
false,
)?;
Ok((join, on))
}
fn with_hash_partitioned_children(
join: &HashJoinExec,
on: &JoinOn,
) -> Result<HashJoinExec> {
join.builder()
.with_new_children(vec![
Arc::new(PartitionedTestExec::try_new(
join.left().schema(),
Partitioning::Hash(vec![Arc::clone(&on[0].0)], 2),
)?),
Arc::new(PartitionedTestExec::try_new(
join.right().schema(),
Partitioning::Hash(vec![Arc::clone(&on[0].1)], 2),
)?),
])?
.build()
}
#[test]
fn test_partitioned_dynamic_filter_pushdown_allows_supported_partitioning()
-> Result<()> {
let (range_join, on) = range_partitioned_dynamic_filter_test_join(10, 10)?;
let hash_join = with_hash_partitioned_children(&range_join, &on)?;
let mut session_config = SessionConfig::default();
session_config
.options_mut()
.optimizer
.enable_join_dynamic_filter_pushdown = true;
assert!(range_join.allow_join_dynamic_filter_pushdown(session_config.options()));
assert!(hash_join.allow_join_dynamic_filter_pushdown(session_config.options()));
session_config
.options_mut()
.optimizer
.preserve_file_partitions = 1;
assert!(range_join.allow_join_dynamic_filter_pushdown(session_config.options()));
Ok(())
}
#[test]
fn test_partitioned_dynamic_filter_pushdown_rejects_unsupported_partitioning()
-> Result<()> {
let (range_join, on) = range_partitioned_dynamic_filter_test_join(10, 10)?;
let hash_join = with_hash_partitioned_children(&range_join, &on)?;
let (mismatched_range_join, _) =
range_partitioned_dynamic_filter_test_join(10, 11)?;
let mut session_config = SessionConfig::default();
session_config
.options_mut()
.optimizer
.enable_join_dynamic_filter_pushdown = true;
assert!(
!mismatched_range_join
.allow_join_dynamic_filter_pushdown(session_config.options())
);
session_config
.options_mut()
.optimizer
.preserve_file_partitions = 1;
assert!(!hash_join.allow_join_dynamic_filter_pushdown(session_config.options()));
Ok(())
}
#[test]
fn test_with_dynamic_filter_rejects_invalid_columns() -> Result<()> {
let (_, _, on) = build_schema_and_on()?;
let left = build_table(("a1", &vec![1]), ("b1", &vec![1]), ("c1", &vec![1]));
let right = build_table(("a2", &vec![1]), ("b1", &vec![1]), ("c2", &vec![1]));
let join = HashJoinExec::try_new(
left,
right,
on,
None,
&JoinType::Inner,
None,
PartitionMode::CollectLeft,
NullEquality::NullEqualsNothing,
false,
)?;
let df = Arc::new(DynamicFilterPhysicalExpr::new(
vec![Arc::new(Column::new("bad", 99)) as _],
lit(true),
));
assert!(join.set_dynamic_filter(df).is_err());
Ok(())
}
fn fallback_inputs() -> Result<(Arc<dyn ExecutionPlan>, Arc<dyn ExecutionPlan>)> {
let side = |offset: i32| {
let batches = (0..32)
.map(|i| {
let ids: Vec<i32> = (i * 16..(i + 1) * 16).collect();
let keys: Vec<i32> = ids.iter().map(|id| id % 47 + offset).collect();
build_table_i32(("id", &ids), ("key", &keys), ("value", &ids))
})
.collect::<Vec<_>>();
TestMemoryExec::try_new_exec(
std::slice::from_ref(&batches),
batches[0].schema(),
None,
)
.map(|exec| exec as Arc<dyn ExecutionPlan>)
};
Ok((side(0)?, side(5)?))
}
fn fallback_context(limit: Option<usize>) -> Arc<TaskContext> {
let mut runtime = RuntimeEnvBuilder::new();
if let Some(limit) = limit {
runtime = runtime.with_memory_limit(limit, 1.0);
}
Arc::new(
TaskContext::default()
.with_session_config(
SessionConfig::default()
.with_batch_size(16)
.with_sort_spill_reservation_bytes(0),
)
.with_runtime(runtime.build_arc().unwrap()),
)
}
fn fallback_join(
left: Arc<dyn ExecutionPlan>,
right: Arc<dyn ExecutionPlan>,
join_type: JoinType,
) -> Result<HashJoinExec> {
HashJoinExecBuilder::new(
left,
right,
vec![(
Arc::new(Column::new("key", 1)),
Arc::new(Column::new("key", 1)),
)],
join_type,
)
.with_partition_mode(PartitionMode::Partitioned)
.build()
}
#[tokio::test]
async fn partitioned_join_memory_limit() -> Result<()> {
let (left, right) = fallback_inputs()?;
let reference =
fallback_join(Arc::clone(&left), Arc::clone(&right), JoinType::Inner)?;
let expected =
common::collect(reference.execute(0, fallback_context(None))?).await?;
assert!(!expected.is_empty());
let join = fallback_join(left, right, JoinType::Inner)?;
let error = common::collect(join.execute(0, fallback_context(Some(4 * 1024)))?)
.await
.unwrap_err();
assert_contains!(error.to_string(), "Resources exhausted");
Ok(())
}
#[tokio::test]
async fn sort_merge_fallback_preserves_promised_ordering() -> Result<()> {
let (left, right) = fallback_inputs()?;
let right = Arc::new(crate::sorts::sort::SortExec::new(
[PhysicalSortExpr::new_default(Arc::new(Column::new(
"id", 0,
)))]
.into(),
right,
));
let join = fallback_join(left, right, JoinType::Inner)?;
assert!(join.properties().output_ordering().is_some());
let error = common::collect(join.execute(0, fallback_context(Some(4096)))?)
.await
.unwrap_err();
assert_contains!(error.to_string(), "Resources exhausted");
Ok(())
}
#[tokio::test]
async fn memory_limited_join_keeps_streaming_inputs() -> Result<()> {
let (left, right) = fallback_inputs()?;
let batches = common::collect(right.execute(0, fallback_context(None))?).await?;
let right: Arc<dyn ExecutionPlan> =
Arc::new(crate::streaming::StreamingTableExec::try_new(
right.schema(),
vec![Arc::new(
crate::test::TestPartitionStream::new_with_batches(batches),
)],
None,
[],
true,
None,
)?);
assert!(right.boundedness().is_unbounded());
let join = fallback_join(left, right, JoinType::Inner)?;
let error = common::collect(join.execute(0, fallback_context(Some(4096)))?)
.await
.unwrap_err();
assert_contains!(error.to_string(), "Resources exhausted");
Ok(())
}
}