use std::fmt::Formatter;
use std::ops::{BitOr, ControlFlow};
use std::sync::Arc;
use std::task::Poll;
use super::utils::{
asymmetric_join_output_partitioning, need_produce_result_in_final,
reorder_output_after_swap, swap_join_projection,
};
use crate::common::can_project;
use crate::execution_plan::{EmissionType, boundedness_from_children};
use crate::filter_pushdown::{
ChildFilterDescription, FilterDescription, FilterPushdownPhase, PushedDownPredicate,
};
use crate::joins::SharedBitmapBuilder;
use crate::joins::logical_batch::{BatchRow, LogicalBatch, RowIndices};
use crate::joins::probe_completion::{Completion, ProbeCompletion};
use crate::joins::utils::{
BuildProbeJoinMetrics, ColumnIndex, JoinFilter, OnceAsync, OnceFut,
boolean_mask_from_filter, build_join_schema, check_join_is_valid,
estimate_join_statistics, need_produce_right_in_final,
};
use crate::metrics::{
Count, ExecutionPlanMetricsSet, MetricBuilder, MetricType, MetricsSet, RatioMetrics,
Time,
};
use crate::projection::{
EmbeddedProjection, JoinData, ProjectionExec, try_embed_projection,
try_pushdown_through_join_with_column_indices,
};
use crate::statistics::{ChildStats, StatisticsArgs};
use crate::{
ChildrenPropertiesMode, DisplayAs, DisplayFormatType, Distribution, ExecutionPlan,
ExecutionPlanProperties, PlanProperties, RecordBatchStream, ReplaceChildrenOptions,
SendableRecordBatchStream, validate_child_count,
};
use arrow::array::{
Array, BooleanArray, BooleanBufferBuilder, RecordBatchOptions, UInt32Array,
UInt64Array, new_null_array,
};
use arrow::buffer::BooleanBuffer;
use arrow::compute::{
BatchCoalescer, filter, filter_record_batch, not, take, take_record_batch,
};
use arrow::datatypes::{Schema, SchemaRef};
use arrow::record_batch::RecordBatch;
use arrow::util::bit_iterator::BitIndexIterator;
use arrow_schema::DataType;
use datafusion_common::cast::as_boolean_array;
use datafusion_common::config::ConfigOptions;
use datafusion_common::tree_node::TreeNodeRecursion;
use datafusion_common::{
DataFusionError, JoinSide, NullEquality, Result, ScalarValue, SharedResult,
Statistics, arrow_err, assert_eq_or_internal_err, internal_datafusion_err,
internal_err, project_schema, unwrap_or_internal_err,
};
use datafusion_execution::memory_pool::{MemoryConsumer, MemoryPool, MemoryReservation};
use datafusion_execution::{SpillFile, TaskContext};
use datafusion_expr::JoinType;
use datafusion_physical_expr::PhysicalExpr;
use datafusion_physical_expr::equivalence::{
ProjectionMapping, join_equivalence_properties,
};
use datafusion_physical_expr::expressions::DynamicFilterPhysicalExpr;
use datafusion_physical_expr::projection::{ProjectionRef, combine_projections};
use futures::future::{BoxFuture, Shared};
use futures::{FutureExt, Stream, StreamExt};
use log::debug;
use parking_lot::Mutex;
use crate::metrics::SpillMetrics;
use crate::spill::replayable_spill_input::ReplayableStreamSource;
use crate::spill::spill_manager::SpillManager;
#[expect(rustdoc::private_intra_doc_links)]
#[derive(Debug)]
pub struct NestedLoopJoinExec {
pub(crate) left: Arc<dyn ExecutionPlan>,
pub(crate) right: Arc<dyn ExecutionPlan>,
pub(crate) filter: Option<JoinFilter>,
pub(crate) join_type: JoinType,
join_schema: SchemaRef,
build_side_data: OnceAsync<LeftLoad>,
left_chunk_barrier: Arc<LeftChunkBarrier>,
column_indices: Vec<ColumnIndex>,
projection: Option<ProjectionRef>,
metrics: ExecutionPlanMetricsSet,
cache: Arc<PlanProperties>,
}
pub struct NestedLoopJoinExecBuilder {
left: Arc<dyn ExecutionPlan>,
right: Arc<dyn ExecutionPlan>,
join_type: JoinType,
filter: Option<JoinFilter>,
projection: Option<ProjectionRef>,
}
impl NestedLoopJoinExecBuilder {
pub fn new(
left: Arc<dyn ExecutionPlan>,
right: Arc<dyn ExecutionPlan>,
join_type: JoinType,
) -> Self {
Self {
left,
right,
join_type,
filter: None,
projection: None,
}
}
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.projection = projection;
self
}
pub fn with_filter(mut self, filter: Option<JoinFilter>) -> Self {
self.filter = filter;
self
}
pub fn build(self) -> Result<NestedLoopJoinExec> {
let Self {
left,
right,
join_type,
filter,
projection,
} = self;
let left_schema = left.schema();
let right_schema = right.schema();
check_join_is_valid(&left_schema, &right_schema, &[])?;
let (join_schema, column_indices) =
build_join_schema(&left_schema, &right_schema, &join_type);
let join_schema = Arc::new(join_schema);
let cache = NestedLoopJoinExec::compute_properties(
&left,
&right,
&join_schema,
join_type,
projection.as_deref(),
)?;
let left_chunk_barrier = Arc::new(LeftChunkBarrier::new(
right.output_partitioning().partition_count(),
));
Ok(NestedLoopJoinExec {
left,
right,
filter,
join_type,
join_schema,
build_side_data: Default::default(),
left_chunk_barrier,
column_indices,
projection,
metrics: Default::default(),
cache: Arc::new(cache),
})
}
}
impl From<&NestedLoopJoinExec> for NestedLoopJoinExecBuilder {
fn from(exec: &NestedLoopJoinExec) -> Self {
Self {
left: Arc::clone(exec.left()),
right: Arc::clone(exec.right()),
join_type: exec.join_type,
filter: exec.filter.clone(),
projection: exec.projection.clone(),
}
}
}
impl NestedLoopJoinExec {
pub fn try_new(
left: Arc<dyn ExecutionPlan>,
right: Arc<dyn ExecutionPlan>,
filter: Option<JoinFilter>,
join_type: &JoinType,
projection: Option<Vec<usize>>,
) -> Result<Self> {
NestedLoopJoinExecBuilder::new(left, right, *join_type)
.with_projection(projection)
.with_filter(filter)
.build()
}
pub fn left(&self) -> &Arc<dyn ExecutionPlan> {
&self.left
}
pub fn right(&self) -> &Arc<dyn ExecutionPlan> {
&self.right
}
pub fn filter(&self) -> Option<&JoinFilter> {
self.filter.as_ref()
}
pub fn join_type(&self) -> &JoinType {
&self.join_type
}
pub fn projection(&self) -> &Option<ProjectionRef> {
&self.projection
}
fn compute_properties(
left: &Arc<dyn ExecutionPlan>,
right: &Arc<dyn ExecutionPlan>,
schema: &SchemaRef,
join_type: JoinType,
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),
None,
&[],
)?;
let mut output_partitioning =
asymmetric_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 {
match join_type {
JoinType::Inner
| JoinType::LeftSemi
| JoinType::RightSemi
| JoinType::Right
| JoinType::RightAnti
| JoinType::RightMark => EmissionType::Incremental,
JoinType::Left
| JoinType::LeftAnti
| JoinType::LeftMark
| JoinType::Full => EmissionType::Both,
}
} 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]),
))
}
fn maintains_input_order(_join_type: JoinType) -> Vec<bool> {
vec![false, false]
}
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())?;
NestedLoopJoinExecBuilder::from(self)
.with_projection_ref(projection)
.build()
}
#[doc(hidden)]
pub fn swap_inputs(&self) -> Result<Arc<dyn ExecutionPlan>> {
let left = self.left();
let right = self.right();
let new_join = NestedLoopJoinExecBuilder::new(
Arc::clone(right),
Arc::clone(left),
self.join_type().swap(),
)
.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(),
))
.build()?;
let plan: Arc<dyn ExecutionPlan> = if matches!(
self.join_type(),
JoinType::LeftSemi
| JoinType::RightSemi
| JoinType::LeftAnti
| JoinType::RightAnti
| JoinType::LeftMark
| JoinType::RightMark
) || self.projection.is_some()
{
Arc::new(new_join)
} else {
reorder_output_after_swap(
Arc::new(new_join),
&self.left().schema(),
&self.right().schema(),
)?
};
Ok(plan)
}
}
impl DisplayAs for NestedLoopJoinExec {
fn fmt_as(&self, t: DisplayFormatType, f: &mut Formatter) -> std::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()
};
write!(
f,
"NestedLoopJoinExec: join_type={:?}{}{}",
self.join_type, display_filter, display_projections
)
}
DisplayFormatType::TreeRender => {
if *self.join_type() != JoinType::Inner {
writeln!(f, "join_type={:?}", self.join_type)
} else {
Ok(())
}
}
}
}
}
impl ExecutionPlan for NestedLoopJoinExec {
fn name(&self) -> &'static str {
"NestedLoopJoinExec"
}
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) -> crate::InputDistributionRequirements {
crate::InputDistributionRequirements::new(vec![
Distribution::SinglePartition,
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> {
crate::apply_expression_roots(
self.filter.iter().map(|filter| filter.expression()),
f,
)
}
fn replace_children(
self: Arc<Self>,
mut children: Vec<Arc<dyn ExecutionPlan>>,
options: ReplaceChildrenOptions,
) -> Result<Arc<dyn ExecutionPlan>> {
validate_child_count!(self, children);
match options.children_properties {
ChildrenPropertiesMode::Keep => {
let left = children.swap_remove(0);
let right = children.swap_remove(0);
let left_chunk_barrier = Arc::new(LeftChunkBarrier::new(
right.output_partitioning().partition_count(),
));
Ok(Arc::new(Self {
left,
right,
metrics: ExecutionPlanMetricsSet::new(),
build_side_data: Default::default(),
left_chunk_barrier,
cache: Arc::clone(&self.cache),
filter: self.filter.clone(),
join_type: self.join_type,
join_schema: Arc::clone(&self.join_schema),
column_indices: self.column_indices.clone(),
projection: self.projection.clone(),
}))
}
ChildrenPropertiesMode::Recompute => Ok(Arc::new(
NestedLoopJoinExecBuilder::new(
Arc::clone(&children[0]),
Arc::clone(&children[1]),
self.join_type,
)
.with_filter(self.filter.clone())
.with_projection_ref(self.projection.clone())
.build()?,
)),
}
}
fn with_new_children(
self: Arc<Self>,
children: Vec<Arc<dyn ExecutionPlan>>,
) -> Result<Arc<dyn ExecutionPlan>> {
self.replace_children(
children,
ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
)
}
fn with_new_children_and_same_properties(
self: Arc<Self>,
children: Vec<Arc<dyn ExecutionPlan>>,
) -> Result<Arc<dyn ExecutionPlan>> {
self.replace_children(
children,
ReplaceChildrenOptions::new(ChildrenPropertiesMode::Keep),
)
}
fn execute(
&self,
partition: usize,
context: Arc<TaskContext>,
) -> Result<SendableRecordBatchStream> {
assert_eq_or_internal_err!(
self.left.output_partitioning().partition_count(),
1,
"Invalid NestedLoopJoinExec, the output partition count of the left child must be 1,\
consider using CoalescePartitionsExec or the EnforceDistribution rule"
);
let metrics = NestedLoopJoinMetrics::new(&self.metrics, partition);
let batch_size = context.session_config().batch_size();
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 right_partition_count = self.right().output_partitioning().partition_count();
let load_reservation =
MemoryConsumer::new(format!("NestedLoopJoinLoad[{partition}]"))
.register(context.memory_pool());
let coordinated_fallback_disabled = !context
.session_config()
.options()
.execution
.enable_nlj_coordinated_fallback
&& need_produce_result_in_final(self.join_type)
&& right_partition_count > 1;
let can_spill = context.runtime_env().disk_manager.tmp_files_enabled()
&& !coordinated_fallback_disabled;
let build_side_data = self.build_side_data.try_once(|| {
let stream = self.left.execute(0, Arc::clone(&context))?;
let left_spill_manager = can_spill.then(|| {
SpillManager::new(
context.runtime_env(),
metrics.spill_metrics.clone(),
stream.schema(),
)
.with_compression_type(context.session_config().spill_compression())
});
Ok(collect_left_input(
stream,
metrics.join_metrics.clone(),
load_reservation,
need_produce_result_in_final(self.join_type),
right_partition_count,
left_spill_manager,
Arc::clone(&self.left_chunk_barrier),
))
})?;
let probe_side_data = self.right.execute(partition, Arc::clone(&context))?;
let spill_state = if can_spill {
SpillState::Pending {
task_context: Arc::clone(&context),
partition,
left_chunk_barrier: Arc::clone(&self.left_chunk_barrier),
}
} else {
SpillState::Disabled
};
Ok(Box::pin(NestedLoopJoinStream::new(
self.schema(),
self.filter.clone(),
self.join_type,
probe_side_data,
build_side_data,
column_indices_after_projection,
metrics,
batch_size,
spill_state,
)))
}
fn metrics(&self) -> Option<MetricsSet> {
Some(self.metrics.clone_inner())
}
fn child_stats_requests(&self, partition: Option<usize>) -> Vec<ChildStats> {
vec![ChildStats::At(None), ChildStats::At(partition)]
}
fn statistics_from_inputs(
&self,
input_stats: &[Arc<Statistics>],
_args: &StatisticsArgs,
) -> Result<Arc<Statistics>> {
let join_columns = Vec::new();
let left_stats = input_stats[0].as_ref().clone();
let right_stats = input_stats[1].as_ref().clone();
let stats = estimate_join_statistics(
left_stats,
right_stats,
&join_columns,
NullEquality::NullEqualsNothing,
&self.join_type,
&self.join_schema,
)?;
Ok(Arc::new(stats.project(self.projection.as_ref())))
}
fn gather_filters_for_pushdown(
&self,
phase: FilterPushdownPhase,
parent_filters: Vec<Arc<dyn PhysicalExpr>>,
config: &ConfigOptions,
) -> Result<FilterDescription> {
if phase != FilterPushdownPhase::Post
|| !config.optimizer.enable_join_dynamic_filter_pushdown
{
return Ok(FilterDescription::new()
.with_child(ChildFilterDescription::all_unsupported(&parent_filters))
.with_child(ChildFilterDescription::all_unsupported(&parent_filters)));
}
let (left_preserved, right_preserved) = match self.join_type {
JoinType::Inner => (true, true),
JoinType::Left
| JoinType::LeftSemi
| JoinType::LeftAnti
| JoinType::LeftMark => (true, false),
JoinType::Right
| JoinType::RightSemi
| JoinType::RightAnti
| JoinType::RightMark => (false, true),
JoinType::Full => (false, false),
};
let output_indices: Vec<_> = match &self.projection {
Some(projection) => projection.to_vec(),
None => (0..self.column_indices.len()).collect(),
};
let mut description = FilterDescription::new();
for (side, preserved, child) in [
(JoinSide::Left, left_preserved, self.left()),
(JoinSide::Right, right_preserved, self.right()),
] {
let column_mapping = output_indices
.iter()
.enumerate()
.filter_map(|(output, input)| {
let column = &self.column_indices[*input];
(column.side == side).then_some((output, column.index))
})
.collect();
let mut child_description = if preserved {
ChildFilterDescription::from_child_with_column_mapping(
&parent_filters,
column_mapping,
child,
)?
} else {
ChildFilterDescription::all_unsupported(&parent_filters)
};
for (filter, pushed) in parent_filters
.iter()
.zip(&mut child_description.parent_filters)
{
if !filter.is::<DynamicFilterPhysicalExpr>() {
*pushed = PushedDownPredicate::unsupported(Arc::clone(filter));
}
}
description = description.with_child(child_description);
}
Ok(description)
}
fn try_swapping_with_projection(
&self,
projection: &ProjectionExec,
) -> Result<Option<Arc<dyn ExecutionPlan>>> {
if self.contains_projection() {
return Ok(None);
}
let schema = self.schema();
if let Some(JoinData {
projected_left_child,
projected_right_child,
join_filter,
..
}) = try_pushdown_through_join_with_column_indices(
projection,
self.left(),
self.right(),
&[],
&schema,
self.filter(),
self.column_indices.as_slice(),
)? {
Ok(Some(Arc::new(
NestedLoopJoinExecBuilder::new(
Arc::new(projected_left_child),
Arc::new(projected_right_child),
*self.join_type(),
)
.with_filter(join_filter)
.build()?,
)))
} else {
try_embed_projection(projection, self)
}
}
#[cfg(feature = "proto")]
fn try_to_proto(
&self,
ctx: &crate::proto::ExecutionPlanEncodeCtx<'_>,
) -> Result<Option<datafusion_proto_models::protobuf::PhysicalPlanNode>> {
use datafusion_proto_models::protobuf;
let Self {
left,
right,
filter,
join_type,
projection,
join_schema: _,
build_side_data: _,
left_chunk_barrier: _,
column_indices: _,
metrics: _,
cache: _,
} = self;
let left = ctx.encode_child(left)?;
let right = ctx.encode_child(right)?;
let join_type = crate::joins::proto::join_type_to_proto(*join_type);
let filter = filter
.as_ref()
.map(|f| crate::joins::proto::join_filter_to_proto(f, ctx))
.transpose()?;
Ok(Some(protobuf::PhysicalPlanNode {
physical_plan_type: Some(
protobuf::physical_plan_node::PhysicalPlanType::NestedLoopJoin(Box::new(
protobuf::NestedLoopJoinExecNode {
left: Some(Box::new(left)),
right: Some(Box::new(right)),
join_type: join_type.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(),
},
},
)),
),
}))
}
}
#[cfg(feature = "proto")]
impl NestedLoopJoinExec {
pub fn try_from_proto(
node: &datafusion_proto_models::protobuf::PhysicalPlanNode,
ctx: &crate::proto::ExecutionPlanDecodeCtx<'_>,
) -> Result<Arc<dyn ExecutionPlan>> {
use datafusion_proto_models::protobuf;
let join = crate::expect_plan_variant!(
node,
protobuf::physical_plan_node::PhysicalPlanType::NestedLoopJoin,
"NestedLoopJoinExec",
);
let protobuf::NestedLoopJoinExecNode {
left,
right,
join_type,
filter,
projection,
} = &**join;
let left =
ctx.decode_required_child(left.as_deref(), "NestedLoopJoinExec", "left")?;
let right =
ctx.decode_required_child(right.as_deref(), "NestedLoopJoinExec", "right")?;
let join_type =
crate::joins::proto::join_type_from_proto(*join_type, "NestedLoopJoinExec")?;
let filter = filter
.as_ref()
.map(|f| {
crate::joins::proto::join_filter_from_proto(f, ctx, "NestedLoopJoinExec")
})
.transpose()?;
let projection = match projection.as_slice() {
[] => None,
[u32::MAX] => Some(Vec::new()),
indices => Some(indices.iter().map(|i| *i as usize).collect()),
};
Ok(Arc::new(NestedLoopJoinExec::try_new(
left, right, filter, &join_type, projection,
)?))
}
}
#[cfg(all(test, feature = "proto"))]
mod proto_tests {
use super::*;
use crate::proto::{ExecutionPlanDecodeCtx, ExecutionPlanEncodeCtx};
use crate::proto_test_util::{
StubPlanDecoder, StubPlanEncoder, UnreachablePlanDecoder, encoded_child_node,
stub_child,
};
use datafusion_proto_models::protobuf;
fn encode_projection(projection: Option<Vec<usize>>) -> Vec<u32> {
let plan = NestedLoopJoinExec::try_new(
stub_child(),
stub_child(),
None,
&JoinType::Inner,
projection,
)
.unwrap();
let encoder = StubPlanEncoder::ok();
let ctx = ExecutionPlanEncodeCtx::new(&encoder);
let node = plan
.try_to_proto(&ctx)
.unwrap()
.expect("NestedLoopJoinExec should encode to Some(node)");
match node.physical_plan_type {
Some(protobuf::physical_plan_node::PhysicalPlanType::NestedLoopJoin(
join,
)) => join.projection,
other => panic!("expected a NestedLoopJoin node, got {other:?}"),
}
}
fn join_node(projection: Vec<u32>) -> protobuf::PhysicalPlanNode {
protobuf::PhysicalPlanNode {
physical_plan_type: Some(
protobuf::physical_plan_node::PhysicalPlanType::NestedLoopJoin(Box::new(
protobuf::NestedLoopJoinExecNode {
left: Some(Box::new(encoded_child_node())),
right: Some(Box::new(encoded_child_node())),
join_type: protobuf::JoinType::Inner.into(),
filter: None,
projection,
},
)),
),
}
}
fn decode_projection(projection: Vec<u32>) -> Option<Vec<usize>> {
let decoder = StubPlanDecoder::ok();
let ctx = ExecutionPlanDecodeCtx::new(&decoder);
let plan =
NestedLoopJoinExec::try_from_proto(&join_node(projection), &ctx).unwrap();
plan.downcast_ref::<NestedLoopJoinExec>()
.expect("decoded plan should be a NestedLoopJoinExec")
.projection
.as_ref()
.map(|p| p.to_vec())
}
#[test]
fn projection_states_survive_the_encode_side() {
assert_eq!(encode_projection(None), Vec::<u32>::new());
assert_eq!(encode_projection(Some(vec![])), vec![u32::MAX]);
assert_eq!(encode_projection(Some(vec![0, 1])), vec![0, 1]);
}
#[test]
fn projection_states_survive_the_decode_side() {
assert_eq!(decode_projection(vec![]), None);
assert_eq!(decode_projection(vec![u32::MAX]), Some(vec![]));
assert_eq!(decode_projection(vec![0, 1]), Some(vec![0, 1]));
}
#[test]
fn try_from_proto_rejects_a_different_plan_variant() {
let decoder = UnreachablePlanDecoder::new();
let ctx = ExecutionPlanDecodeCtx::new(&decoder);
let err =
NestedLoopJoinExec::try_from_proto(&encoded_child_node(), &ctx).unwrap_err();
assert!(err.to_string().contains("not a NestedLoopJoinExec"));
}
}
impl EmbeddedProjection for NestedLoopJoinExec {
fn with_projection(&self, projection: Option<Vec<usize>>) -> Result<Self> {
self.with_projection(projection)
}
}
pub(crate) struct JoinLeftData {
batch: LogicalBatch,
bitmap: SharedBitmapBuilder,
#[expect(dead_code)]
reservation: MemoryReservation,
}
impl JoinLeftData {
pub(crate) fn new(
batch: LogicalBatch,
bitmap: SharedBitmapBuilder,
reservation: MemoryReservation,
) -> Self {
Self {
batch,
bitmap,
reservation,
}
}
pub(crate) fn batch(&self) -> &LogicalBatch {
&self.batch
}
pub(crate) fn bitmap(&self) -> &SharedBitmapBuilder {
&self.bitmap
}
}
async fn collect_left_input(
mut stream: SendableRecordBatchStream,
join_metrics: BuildProbeJoinMetrics,
reservation: MemoryReservation,
with_visited_left_side: bool,
probe_threads_count: usize,
spill_manager: Option<SpillManager>,
left_chunk_barrier: Arc<LeftChunkBarrier>,
) -> Result<LeftLoad> {
let schema = stream.schema();
let metrics = join_metrics;
let mut batches: Vec<RecordBatch> = Vec::new();
while let Some(batch) = stream.next().await {
let batch = batch?;
let build_timer = metrics.build_time.timer();
let batch_size = batch.get_array_memory_size();
match reservation.try_grow(batch_size) {
Ok(()) => {
metrics.build_mem_used.add(batch_size);
metrics.build_input_batches.add(1);
metrics.build_input_rows.add(batch.num_rows());
batches.push(batch);
}
Err(e) if is_spillable_oom(&e, spill_manager.as_ref()) => {
build_timer.done();
let spill_manager = spill_manager.expect("checked by is_spillable_oom");
let spilled = spill_left_input(
spill_manager,
batches,
Some(batch),
stream,
metrics,
&reservation,
)
.await?;
return Ok(left_load_from_spill(
spilled,
schema,
with_visited_left_side,
probe_threads_count,
reservation,
&left_chunk_barrier,
));
}
Err(e) => return Err(e),
}
}
let build_timer = metrics.build_time.timer();
let buffered_build_batch = LogicalBatch::new(Arc::clone(&schema), batches)?;
let visited_left_side = if with_visited_left_side {
let n_rows = buffered_build_batch.num_rows();
let buffer_size = n_rows.div_ceil(8);
match reservation.try_grow(buffer_size) {
Ok(()) => {}
Err(e) if is_spillable_oom(&e, spill_manager.as_ref()) => {
build_timer.done();
let spill_manager = spill_manager.expect("checked by is_spillable_oom");
let spilled = spill_left_input(
spill_manager,
buffered_build_batch.into_batches(),
None,
stream,
metrics,
&reservation,
)
.await?;
return Ok(left_load_from_spill(
spilled,
schema,
with_visited_left_side,
probe_threads_count,
reservation,
&left_chunk_barrier,
));
}
Err(e) => return Err(e),
}
metrics.build_mem_used.add(buffer_size);
let mut buffer = BooleanBufferBuilder::new(n_rows);
buffer.append_n(n_rows, false);
buffer
} else {
BooleanBufferBuilder::new(0)
};
Ok(LeftLoad::InMemory {
left_data: Arc::new(JoinLeftData::new(
buffered_build_batch,
Mutex::new(visited_left_side),
reservation,
)),
probe_completion: Arc::new(ProbeCompletion::new(probe_threads_count)),
})
}
fn left_load_from_spill(
spilled: Option<SpilledLeftFile>,
schema: SchemaRef,
with_visited_left_side: bool,
probe_threads_count: usize,
reservation: MemoryReservation,
left_chunk_barrier: &LeftChunkBarrier,
) -> LeftLoad {
match spilled {
Some(spilled) => {
let left_spill = Arc::new(LeftSpillData::new(
spilled,
schema,
with_visited_left_side,
probe_threads_count,
reservation,
));
left_chunk_barrier.register_left_spill(&left_spill);
LeftLoad::Spilled(left_spill)
}
None => LeftLoad::InMemory {
left_data: Arc::new(JoinLeftData::new(
LogicalBatch::new_empty(schema),
Mutex::new(BooleanBufferBuilder::new(0)),
reservation,
)),
probe_completion: Arc::new(ProbeCompletion::new(probe_threads_count)),
},
}
}
fn is_spillable_oom(
error: &DataFusionError,
spill_manager: Option<&SpillManager>,
) -> bool {
spill_manager.is_some()
&& matches!(error.find_root(), DataFusionError::ResourcesExhausted(_))
}
async fn spill_left_input(
spill_manager: SpillManager,
buffered: Vec<RecordBatch>,
pending: Option<RecordBatch>,
mut stream: SendableRecordBatchStream,
metrics: BuildProbeJoinMetrics,
reservation: &MemoryReservation,
) -> Result<Option<SpilledLeftFile>> {
let build_timer = metrics.build_time.timer();
let mut spill_file =
spill_manager.create_in_progress_file("NestedLoopJoin left spill")?;
let mut num_rows = 0;
for batch in buffered {
if batch.num_rows() > 0 {
num_rows += batch.num_rows();
spill_file.append_batch(&batch)?;
}
}
reservation.free();
for batch in pending.into_iter() {
if batch.num_rows() > 0 {
metrics.build_input_batches.add(1);
metrics.build_input_rows.add(batch.num_rows());
num_rows += batch.num_rows();
spill_file.append_batch(&batch)?;
}
}
build_timer.done();
while let Some(batch) = stream.next().await {
let batch = batch?;
let _build_timer = metrics.build_time.timer();
if batch.num_rows() > 0 {
metrics.build_input_batches.add(1);
metrics.build_input_rows.add(batch.num_rows());
num_rows += batch.num_rows();
spill_file.append_batch(&batch)?;
}
}
let _build_timer = metrics.build_time.timer();
Ok(spill_file.finish()?.map(|spill_file| SpilledLeftFile {
spill_manager,
spill_file,
num_rows,
}))
}
#[derive(Debug, Clone, Copy)]
enum NLJState {
BufferingLeft,
FetchingRight,
ProbeRight,
EmitRightUnmatched,
ProbeEnd,
EmitLeftUnmatched,
EmitGlobalRightUnmatched,
Done,
}
pub(crate) enum LeftLoad {
InMemory {
left_data: Arc<JoinLeftData>,
probe_completion: Arc<ProbeCompletion>,
},
Spilled(Arc<LeftSpillData>),
}
struct SpilledLeftFile {
spill_manager: SpillManager,
spill_file: Arc<dyn SpillFile>,
num_rows: usize,
}
pub(crate) struct LeftSpillData {
spill_manager: SpillManager,
spill_file: Arc<dyn SpillFile>,
schema: SchemaRef,
num_rows: usize,
reader: Arc<Mutex<Option<LeftChunkReader>>>,
visited: SharedBitmapBuilder,
probe_completion: ProbeCompletion,
reservation: MemoryReservation,
}
impl LeftSpillData {
fn new(
spilled: SpilledLeftFile,
schema: SchemaRef,
with_visited_left_side: bool,
probe_threads_count: usize,
reservation: MemoryReservation,
) -> Self {
let SpilledLeftFile {
spill_manager,
spill_file,
num_rows,
} = spilled;
let visited = if with_visited_left_side {
reservation.grow(num_rows.div_ceil(8));
let mut buffer = BooleanBufferBuilder::new(num_rows);
buffer.append_n(num_rows, false);
buffer
} else {
BooleanBufferBuilder::new(0)
};
Self {
spill_manager,
spill_file,
schema,
num_rows,
reader: Arc::new(Mutex::new(None)),
visited: Mutex::new(visited),
probe_completion: ProbeCompletion::new(probe_threads_count),
reservation,
}
}
fn open_pass(&self) -> Result<SendableRecordBatchStream> {
self.spill_manager
.read_spill_as_stream(Arc::clone(&self.spill_file), None)
}
fn load_chunk(
&self,
reservation: MemoryReservation,
build_time: &Time,
) -> LeftChunkFut {
load_left_chunk(
Arc::clone(&self.reader),
self.spill_manager.clone(),
Arc::clone(&self.spill_file),
Arc::clone(&self.schema),
reservation,
build_time.clone(),
)
.map(|chunk| chunk.map(Arc::new).map_err(Arc::new))
.boxed()
.shared()
}
fn merge_visited(&self, row_offset: usize, chunk_visited: &BooleanBufferBuilder) {
let mut visited = self.visited.lock();
for idx in BitIndexIterator::new(chunk_visited.as_slice(), 0, chunk_visited.len())
{
visited.set_bit(row_offset + idx, true);
}
}
fn report_probe_completed(&self) -> Option<BooleanBuffer> {
match self.probe_completion.report_completed() {
Completion::NotLast => None,
Completion::Emit(_) => Some(self.take_visited()),
Completion::Abandoned => {
drop(self.take_visited());
None
}
}
}
fn depart_unfinished(&self, count: usize) {
if self.probe_completion.abandon(count) {
drop(self.take_visited());
}
}
fn take_visited(&self) -> BooleanBuffer {
self.reservation.free();
self.visited.lock().finish()
}
}
struct LeftChunk {
batch: LogicalBatch,
#[expect(dead_code)]
reservation: MemoryReservation,
}
type LeftChunkFut = Shared<BoxFuture<'static, SharedResult<Arc<LeftChunk>>>>;
struct LeftChunkReader {
stream: SendableRecordBatchStream,
carryover: Option<RecordBatch>,
}
async fn load_left_chunk(
reader_slot: Arc<Mutex<Option<LeftChunkReader>>>,
spill_manager: SpillManager,
spill_file: Arc<dyn SpillFile>,
schema: SchemaRef,
reservation: MemoryReservation,
build_time: Time,
) -> Result<LeftChunk> {
let reader = reader_slot.lock().take();
let mut reader = match reader {
Some(reader) => reader,
None => LeftChunkReader {
stream: spill_manager.read_spill_as_stream(spill_file, None)?,
carryover: None,
},
};
let mut batches = vec![];
if let Some(batch) = reader.carryover.take() {
reservation.grow(batch.get_array_memory_size());
batches.push(batch);
}
while let Some(batch) = reader.stream.next().await {
let batch = batch?;
let _build_timer = build_time.timer();
if batch.num_rows() == 0 {
continue;
}
let batch_size = batch.get_array_memory_size();
if reservation.try_grow(batch_size).is_err() {
if !batches.is_empty() {
reader.carryover = Some(batch);
break;
}
reservation.grow(batch_size);
}
batches.push(batch);
}
let _build_timer = build_time.timer();
let batch = LogicalBatch::new(schema, batches)?;
*reader_slot.lock() = Some(reader);
Ok(LeftChunk { batch, reservation })
}
#[derive(Debug)]
pub(crate) struct LeftChunkBarrier {
inner: Mutex<LeftChunkBarrierInner>,
notify: tokio::sync::Notify,
}
struct LeftChunkBarrierInner {
chunk_index: usize,
chunk: Option<LeftChunkFut>,
live: usize,
finished: usize,
reservation: Option<MemoryReservation>,
left_spill: Option<Arc<LeftSpillData>>,
departed_before_spill: usize,
}
impl std::fmt::Debug for LeftChunkBarrierInner {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("LeftChunkBarrierInner")
.field("chunk_index", &self.chunk_index)
.field("live", &self.live)
.field("finished", &self.finished)
.finish()
}
}
impl LeftChunkBarrierInner {
fn advance_if_all_finished(&mut self) -> bool {
if self.live > 0 && self.finished < self.live {
return false;
}
self.chunk = None;
self.chunk_index += 1;
self.finished = 0;
true
}
}
impl LeftChunkBarrier {
fn new(right_partition_count: usize) -> Self {
Self {
inner: Mutex::new(LeftChunkBarrierInner {
chunk_index: 0,
chunk: None,
live: right_partition_count,
finished: 0,
reservation: None,
left_spill: None,
departed_before_spill: 0,
}),
notify: tokio::sync::Notify::new(),
}
}
async fn chunk(
self: Arc<Self>,
chunk_index: usize,
left_spill: Arc<LeftSpillData>,
memory_pool: Arc<dyn MemoryPool>,
build_time: Time,
) -> Result<Arc<LeftChunk>> {
loop {
let advanced = {
let mut inner = self.inner.lock();
if chunk_index == inner.chunk_index {
let inner = &mut *inner;
let reservation = inner.reservation.get_or_insert_with(|| {
MemoryConsumer::new("NestedLoopJoinFallbackChunk")
.with_can_spill(true)
.register(&memory_pool)
});
let chunk = inner.chunk.get_or_insert_with(|| {
left_spill.load_chunk(reservation.new_empty(), &build_time)
});
Err(chunk.clone())
} else {
Ok(self.notify.notified())
}
};
match advanced {
Ok(advanced) => advanced.await,
Err(chunk) => return chunk.await.map_err(DataFusionError::Shared),
}
}
}
fn finish_chunk(&self) {
let mut inner = self.inner.lock();
inner.finished += 1;
if inner.advance_if_all_finished() {
drop(inner);
self.notify.notify_waiters();
}
}
fn register_left_spill(&self, left_spill: &Arc<LeftSpillData>) {
let mut inner = self.inner.lock();
left_spill.depart_unfinished(inner.departed_before_spill);
inner.left_spill = Some(Arc::clone(left_spill));
}
fn depart(&self, chunk_index: usize, probe_reported: bool) {
let mut inner = self.inner.lock();
inner.live = inner.live.saturating_sub(1);
if chunk_index > inner.chunk_index {
inner.finished = inner.finished.saturating_sub(1);
}
if !probe_reported {
match &inner.left_spill {
Some(left_spill) => left_spill.depart_unfinished(1),
None => inner.departed_before_spill += 1,
}
}
if inner.advance_if_all_finished() {
drop(inner);
self.notify.notify_waiters();
}
}
}
pub(crate) enum SpillState {
Disabled,
Pending {
task_context: Arc<TaskContext>,
partition: usize,
left_chunk_barrier: Arc<LeftChunkBarrier>,
},
Active(Box<SpillStateActive>),
}
pub(crate) struct SpillStateActive {
left_spill: Arc<LeftSpillData>,
left_chunk_barrier: Arc<LeftChunkBarrier>,
chunk_index: usize,
chunk_fetch: Option<BoxFuture<'static, Result<Arc<LeftChunk>>>>,
current_chunk: Option<Arc<LeftChunk>>,
memory_pool: Arc<dyn MemoryPool>,
chunk_reservation: MemoryReservation,
chunk_row_offset: usize,
left_unmatched_pass: Option<LeftUnmatchedPass>,
right_schema: SchemaRef,
right_input: ReplayableStreamSource,
global_right_bitmaps: Vec<BooleanBuffer>,
global_right_bitmaps_reservation: MemoryReservation,
right_batch_index: usize,
}
struct LeftUnmatchedPass {
stream: Option<SendableRecordBatchStream>,
visited: BooleanBuffer,
row_offset: usize,
}
impl SpillStateActive {
fn merge_current_right_bitmap(&mut self, idx: usize, values: BooleanBuffer) {
if idx >= self.global_right_bitmaps.len() {
let bytes = values.len().div_ceil(8);
self.global_right_bitmaps_reservation.grow(bytes);
self.global_right_bitmaps.push(values);
} else {
self.global_right_bitmaps[idx] =
self.global_right_bitmaps[idx].bitor(&values);
}
}
}
struct RightExistenceProbe {
candidates: RecordBatch,
filter: Option<JoinFilter>,
original_indices: Option<Vec<usize>>,
matched: BooleanBufferBuilder,
candidate_matched: Vec<u64>,
remaining: usize,
}
impl RightExistenceProbe {
fn new(right: &RecordBatch, filter: Option<&JoinFilter>) -> Result<Self> {
let mut projection = Vec::new();
let mut filter = filter.cloned();
if let Some(filter) = &mut filter {
for column in &mut filter.column_indices {
if column.side == JoinSide::Right {
let index = projection.iter().position(|&i| i == column.index);
column.index = index.unwrap_or_else(|| {
projection.push(column.index);
projection.len() - 1
});
}
}
}
let rows = right.num_rows();
let mut matched = BooleanBufferBuilder::new(rows);
matched.append_n(rows, false);
Ok(Self {
candidates: right.project(&projection)?,
filter,
original_indices: None,
matched,
candidate_matched: vec![0; rows.div_ceil(64)],
remaining: rows,
})
}
fn probe(
&mut self,
left: &LogicalBatch,
start: usize,
batch_size: usize,
) -> Result<usize> {
let candidate_rows = self.candidates.num_rows();
let rows_per_range = batch_size / candidate_rows;
let count = if rows_per_range > 10 {
rows_per_range
} else {
1
};
let count = count.min(left.num_rows() - start);
let remaining_before = self.remaining;
let matches = match &self.filter {
Some(filter) if count == 1 => apply_filter_to_row_join_batch(
left.row(start)?,
&self.candidates,
filter,
)?,
Some(filter) => {
let left_indices = left.row_indices(
(start..start + count)
.flat_map(|i| std::iter::repeat_n(i, candidate_rows)),
)?;
let right_indices = UInt32Array::from_iter_values(
(0..count).flat_map(|_| 0..candidate_rows as u32),
);
apply_filter_to_indices(
left,
&self.candidates,
&left_indices,
&right_indices,
filter,
)?
}
None => {
BooleanArray::new(BooleanBuffer::new_set(count * candidate_rows), None)
}
};
if !matches.has_true() {
return Ok(count);
}
self.update_matches(matches.values());
if start + count < left.num_rows()
&& self.remaining > 0
&& self.remaining < remaining_before
&& self.remaining <= candidate_rows / 2
{
self.compact()?;
}
Ok(count)
}
fn update_matches(&mut self, matches: &BooleanBuffer) {
let candidate_rows = self.candidates.num_rows();
for offset in (0..matches.len()).step_by(candidate_rows) {
let segment = matches.slice(offset, candidate_rows);
let chunks = segment.bit_chunks();
for (word_index, (previous, current)) in self
.candidate_matched
.iter_mut()
.zip(chunks.iter_padded())
.enumerate()
{
let mut new_matches = current & !*previous;
*previous |= current;
self.remaining -= new_matches.count_ones() as usize;
while new_matches != 0 {
let candidate =
word_index * 64 + new_matches.trailing_zeros() as usize;
let original = self
.original_indices
.as_ref()
.map_or(candidate, |indices| indices[candidate]);
self.matched.set_bit(original, true);
new_matches &= new_matches - 1;
}
}
if self.remaining == 0 {
break;
}
}
}
fn compact(&mut self) -> Result<()> {
let indices = UInt32Array::from_iter_values(
(0..self.candidates.num_rows())
.filter(|&i| self.candidate_matched[i / 64] & (1 << (i % 64)) == 0)
.map(|i| i as u32),
);
let original_indices = indices
.values()
.iter()
.map(|&i| {
self.original_indices
.as_ref()
.map_or(i as usize, |original| original[i as usize])
})
.collect();
self.candidates = if self.candidates.num_columns() == 0 {
create_record_batch_with_empty_schema(
self.candidates.schema(),
indices.len(),
)?
} else {
take_record_batch(&self.candidates, &indices)?
};
self.original_indices = Some(original_indices);
self.candidate_matched.clear();
self.candidate_matched
.resize(self.remaining.div_ceil(64), 0);
Ok(())
}
}
pub(crate) struct NestedLoopJoinStream {
pub(crate) output_schema: Arc<Schema>,
pub(crate) join_filter: Option<JoinFilter>,
pub(crate) join_type: JoinType,
pub(crate) right_data: Option<SendableRecordBatchStream>,
pub(crate) left_data: OnceFut<LeftLoad>,
pub(crate) column_indices: Vec<ColumnIndex>,
pub(crate) metrics: NestedLoopJoinMetrics,
batch_size: usize,
should_track_unmatched_right: bool,
state: NLJState,
output_buffer: Box<BatchCoalescer>,
handled_empty_output: bool,
buffered_left_data: Option<Arc<JoinLeftData>>,
in_memory_probe_completion: Option<Arc<ProbeCompletion>>,
left_probe_idx: usize,
left_emit_idx: usize,
left_exhausted: bool,
current_right_batch: Option<RecordBatch>,
current_right_batch_matched: Option<BooleanArray>,
right_existence_probe: Option<RightExistenceProbe>,
spill_state: SpillState,
is_unmatched_left_emitter: bool,
}
pub(crate) struct NestedLoopJoinMetrics {
pub(crate) join_metrics: BuildProbeJoinMetrics,
pub(crate) selectivity: RatioMetrics,
pub(crate) spill_metrics: SpillMetrics,
}
impl NestedLoopJoinMetrics {
pub fn new(metrics: &ExecutionPlanMetricsSet, partition: usize) -> Self {
Self {
join_metrics: BuildProbeJoinMetrics::new(partition, metrics),
selectivity: MetricBuilder::new(metrics)
.with_type(MetricType::Summary)
.ratio_metrics("selectivity", partition),
spill_metrics: SpillMetrics::new(metrics, partition),
}
}
}
impl Stream for NestedLoopJoinStream {
type Item = Result<RecordBatch>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> Poll<Option<Self::Item>> {
loop {
match self.state {
NLJState::BufferingLeft => {
debug!("[NLJState] Entering: {:?}", self.state);
match self.handle_buffering_left(cx) {
ControlFlow::Continue(()) => {}
ControlFlow::Break(poll) => return poll,
}
}
NLJState::FetchingRight => {
debug!("[NLJState] Entering: {:?}", self.state);
match self.handle_fetching_right(cx) {
ControlFlow::Continue(()) => {}
ControlFlow::Break(poll) => return poll,
}
}
NLJState::ProbeRight => {
debug!("[NLJState] Entering: {:?}", self.state);
let join_metric = self.metrics.join_metrics.join_time.clone();
let _join_timer = join_metric.timer();
match self.handle_probe_right() {
ControlFlow::Continue(()) => {}
ControlFlow::Break(poll) => {
return self.metrics.join_metrics.baseline.record_poll(poll);
}
}
}
NLJState::EmitRightUnmatched => {
debug!("[NLJState] Entering: {:?}", self.state);
let join_metric = self.metrics.join_metrics.join_time.clone();
let _join_timer = join_metric.timer();
match self.handle_emit_right_unmatched() {
ControlFlow::Continue(()) => {}
ControlFlow::Break(poll) => {
return self.metrics.join_metrics.baseline.record_poll(poll);
}
}
}
NLJState::ProbeEnd => {
debug!("[NLJState] Entering: {:?}", self.state);
let join_metric = self.metrics.join_metrics.join_time.clone();
let _join_timer = join_metric.timer();
match self.handle_probe_end() {
ControlFlow::Continue(()) => {}
ControlFlow::Break(poll) => {
return self.metrics.join_metrics.baseline.record_poll(poll);
}
}
}
NLJState::EmitLeftUnmatched if self.is_memory_limited() => {
debug!("[NLJState] Entering: {:?}", self.state);
match self.handle_emit_left_unmatched_memory_limited(cx) {
ControlFlow::Continue(()) => {}
ControlFlow::Break(poll) => {
return self.metrics.join_metrics.baseline.record_poll(poll);
}
}
}
NLJState::EmitLeftUnmatched => {
debug!("[NLJState] Entering: {:?}", self.state);
let join_metric = self.metrics.join_metrics.join_time.clone();
let _join_timer = join_metric.timer();
match self.handle_emit_left_unmatched() {
ControlFlow::Continue(()) => {}
ControlFlow::Break(poll) => {
return self.metrics.join_metrics.baseline.record_poll(poll);
}
}
}
NLJState::EmitGlobalRightUnmatched => {
debug!("[NLJState] Entering: {:?}", self.state);
match self.handle_emit_global_right_unmatched(cx) {
ControlFlow::Continue(()) => {}
ControlFlow::Break(poll) => {
return self.metrics.join_metrics.baseline.record_poll(poll);
}
}
}
NLJState::Done => {
debug!("[NLJState] Entering: {:?}", self.state);
let join_metric = self.metrics.join_metrics.join_time.clone();
let _join_timer = join_metric.timer();
let poll = self.handle_done();
return self.metrics.join_metrics.baseline.record_poll(poll);
}
}
}
}
}
impl RecordBatchStream for NestedLoopJoinStream {
fn schema(&self) -> SchemaRef {
Arc::clone(&self.output_schema)
}
}
impl Drop for NestedLoopJoinStream {
fn drop(&mut self) {
if matches!(self.state, NLJState::Done) {
return;
}
let probe_reported = matches!(self.state, NLJState::EmitLeftUnmatched);
match &self.spill_state {
SpillState::Active(active) => active
.left_chunk_barrier
.depart(active.chunk_index, probe_reported),
SpillState::Pending {
left_chunk_barrier, ..
} => left_chunk_barrier.depart(0, probe_reported),
SpillState::Disabled => {}
}
}
}
impl NestedLoopJoinStream {
#[expect(clippy::too_many_arguments)]
pub(crate) fn new(
schema: Arc<Schema>,
filter: Option<JoinFilter>,
join_type: JoinType,
right_data: SendableRecordBatchStream,
left_data: OnceFut<LeftLoad>,
column_indices: Vec<ColumnIndex>,
metrics: NestedLoopJoinMetrics,
batch_size: usize,
spill_state: SpillState,
) -> Self {
Self {
output_schema: Arc::clone(&schema),
join_filter: filter,
join_type,
right_data: Some(right_data),
column_indices,
left_data,
metrics,
in_memory_probe_completion: None,
buffered_left_data: None,
output_buffer: Box::new(BatchCoalescer::new(schema, batch_size)),
batch_size,
current_right_batch: None,
current_right_batch_matched: None,
right_existence_probe: None,
state: NLJState::BufferingLeft,
left_probe_idx: 0,
left_emit_idx: 0,
left_exhausted: false,
handled_empty_output: false,
should_track_unmatched_right: need_produce_right_in_final(join_type),
spill_state,
is_unmatched_left_emitter: false,
}
}
fn is_memory_limited(&self) -> bool {
matches!(self.spill_state, SpillState::Active(_))
}
fn enter_memory_limited_mode(
&mut self,
left_spill: Arc<LeftSpillData>,
) -> Result<()> {
let SpillState::Pending {
task_context: context,
partition,
left_chunk_barrier,
} = std::mem::replace(&mut self.spill_state, SpillState::Disabled)
else {
return internal_err!(
"enter_memory_limited_mode called in non-Pending spill state"
);
};
let chunk_reservation =
MemoryConsumer::new(format!("NestedLoopJoinLeftVisited[{partition}]"))
.register(context.memory_pool());
let global_right_bitmaps_reservation =
MemoryConsumer::new("NestedLoopJoinGlobalRightBitmaps".to_string())
.register(context.memory_pool());
let right_schema = self
.right_data
.as_ref()
.expect("right_data must be present before entering memory-limited mode")
.schema();
let right_data = self
.right_data
.take()
.expect("right_data must be present before entering memory-limited mode");
let right_spill_manager = SpillManager::new(
context.runtime_env(),
self.metrics.spill_metrics.clone(),
Arc::clone(&right_schema),
)
.with_compression_type(context.session_config().spill_compression());
self.spill_state = SpillState::Active(Box::new(SpillStateActive {
left_spill,
left_chunk_barrier,
chunk_index: 0,
chunk_fetch: None,
current_chunk: None,
memory_pool: Arc::clone(context.memory_pool()),
chunk_reservation,
chunk_row_offset: 0,
left_unmatched_pass: None,
right_schema,
right_input: ReplayableStreamSource::new(
right_data,
right_spill_manager,
"NestedLoopJoin right spill",
),
global_right_bitmaps: Vec::new(),
global_right_bitmaps_reservation,
right_batch_index: 0,
}));
self.state = NLJState::BufferingLeft;
Ok(())
}
fn handle_buffering_left(
&mut self,
cx: &mut std::task::Context<'_>,
) -> ControlFlow<Poll<Option<Result<RecordBatch>>>> {
if self.is_memory_limited() {
self.handle_buffering_left_memory_limited(cx)
} else {
match self.left_data.get_shared(cx) {
Poll::Ready(Ok(load)) => match load.as_ref() {
LeftLoad::InMemory {
left_data,
probe_completion,
} => {
self.in_memory_probe_completion =
Some(Arc::clone(probe_completion));
self.buffered_left_data = Some(Arc::clone(left_data));
self.left_exhausted = true;
self.state = NLJState::FetchingRight;
ControlFlow::Continue(())
}
LeftLoad::Spilled(left_spill) => {
debug!(
"NestedLoopJoin: left side exceeded the budget and was spilled, \
entering memory-limited mode"
);
match self.enter_memory_limited_mode(Arc::clone(left_spill)) {
Ok(()) => ControlFlow::Continue(()),
Err(e) => ControlFlow::Break(Poll::Ready(Some(Err(e)))),
}
}
},
Poll::Ready(Err(e)) => ControlFlow::Break(Poll::Ready(Some(Err(e)))),
Poll::Pending => ControlFlow::Break(Poll::Pending),
}
}
}
fn handle_buffering_left_memory_limited(
&mut self,
cx: &mut std::task::Context<'_>,
) -> ControlFlow<Poll<Option<Result<RecordBatch>>>> {
let build_time = self.metrics.join_metrics.build_time.clone();
let SpillState::Active(active) = &mut self.spill_state else {
unreachable!(
"handle_buffering_left_memory_limited called without Active spill state"
);
};
let row_offset = active.chunk_row_offset;
if row_offset >= active.left_spill.num_rows {
self.left_exhausted = true;
self.enter_state_after_last_left_chunk();
return ControlFlow::Continue(());
}
if active.chunk_fetch.is_none() {
active.chunk_fetch = Some(
Arc::clone(&active.left_chunk_barrier)
.chunk(
active.chunk_index,
Arc::clone(&active.left_spill),
Arc::clone(&active.memory_pool),
build_time.clone(),
)
.boxed(),
);
}
let chunk_fetch = active
.chunk_fetch
.as_mut()
.expect("chunk_fetch installed above");
let chunk = match chunk_fetch.poll_unpin(cx) {
Poll::Ready(Ok(chunk)) => chunk,
Poll::Ready(Err(e)) => return ControlFlow::Break(Poll::Ready(Some(Err(e)))),
Poll::Pending => return ControlFlow::Break(Poll::Pending),
};
active.chunk_fetch = None;
let _build_timer = build_time.timer();
let batch = chunk.batch.clone();
let n_rows = batch.num_rows();
self.left_exhausted = row_offset + n_rows >= active.left_spill.num_rows;
let visited_left_side = if need_produce_result_in_final(self.join_type) {
active.chunk_reservation.grow(n_rows.div_ceil(8));
let mut buffer = BooleanBufferBuilder::new(n_rows);
buffer.append_n(n_rows, false);
buffer
} else {
BooleanBufferBuilder::new(0)
};
self.buffered_left_data = Some(Arc::new(JoinLeftData::new(
batch,
Mutex::new(visited_left_side),
active.chunk_reservation.take(),
)));
active.current_chunk = Some(chunk);
active.right_batch_index = 0;
match active.right_input.open_pass() {
Ok(stream) => {
self.right_data = Some(stream);
}
Err(e) => {
return ControlFlow::Break(Poll::Ready(Some(Err(e))));
}
}
self.state = NLJState::FetchingRight;
ControlFlow::Continue(())
}
fn finish_left_chunk(&mut self) -> Result<()> {
let Some(left_data) = self.buffered_left_data.take() else {
return internal_err!("LeftData should be available");
};
let SpillState::Active(active) = &mut self.spill_state else {
return internal_err!("finish_left_chunk called without Active spill state");
};
if need_produce_result_in_final(self.join_type) {
active
.left_spill
.merge_visited(active.chunk_row_offset, &left_data.bitmap().lock());
}
active.chunk_row_offset += left_data.batch().num_rows();
drop(left_data);
active.current_chunk = None;
active.chunk_index += 1;
active.left_chunk_barrier.finish_chunk();
self.left_probe_idx = 0;
if self.left_exhausted {
self.enter_state_after_last_left_chunk();
} else {
self.state = NLJState::BufferingLeft;
}
Ok(())
}
fn enter_state_after_last_left_chunk(&mut self) {
if self.should_track_unmatched_right {
self.right_data = None;
self.state = NLJState::EmitGlobalRightUnmatched;
} else {
self.state = NLJState::ProbeEnd;
}
}
fn handle_fetching_right(
&mut self,
cx: &mut std::task::Context<'_>,
) -> ControlFlow<Poll<Option<Result<RecordBatch>>>> {
let result = match self
.right_data
.as_mut()
.expect("right_data must be present while fetching right")
.poll_next_unpin(cx)
{
Poll::Ready(result) => result,
Poll::Pending => return ControlFlow::Break(Poll::Pending),
};
let join_metric = self.metrics.join_metrics.join_time.clone();
let _join_timer = join_metric.timer();
match result {
Some(Ok(right_batch)) => {
let right_batch_rows = right_batch.num_rows();
self.metrics.join_metrics.input_rows.add(right_batch_rows);
self.metrics.join_metrics.input_batches.add(1);
if right_batch_rows == 0 {
return ControlFlow::Continue(());
}
self.current_right_batch = Some(right_batch);
if self.should_track_unmatched_right
&& !matches!(
self.join_type,
JoinType::RightSemi | JoinType::RightAnti
)
{
let zeroed_buf = BooleanBuffer::new_unset(right_batch_rows);
self.current_right_batch_matched =
Some(BooleanArray::new(zeroed_buf, None));
}
self.left_probe_idx = 0;
self.state = NLJState::ProbeRight;
ControlFlow::Continue(())
}
Some(Err(e)) => ControlFlow::Break(Poll::Ready(Some(Err(e)))),
None if self.is_memory_limited() => {
match self.finish_left_chunk() {
Ok(()) => ControlFlow::Continue(()),
Err(e) => ControlFlow::Break(Poll::Ready(Some(Err(e)))),
}
}
None => {
self.state = NLJState::ProbeEnd;
ControlFlow::Continue(())
}
}
}
fn handle_probe_right(&mut self) -> ControlFlow<Poll<Option<Result<RecordBatch>>>> {
if let Some(poll) = self.maybe_flush_ready_batch() {
return ControlFlow::Break(poll);
}
match self.process_probe_batch() {
Ok(true) => ControlFlow::Continue(()),
Ok(false) => {
self.left_probe_idx = 0;
if let (Ok(left_data), Some(right_batch)) =
(self.get_left_data(), self.current_right_batch.as_ref())
{
let left_rows = left_data.batch().num_rows();
let right_rows = right_batch.num_rows();
self.metrics.selectivity.add_total(left_rows * right_rows);
}
if self.should_track_unmatched_right {
debug_assert!(
self.current_right_batch_matched.is_some(),
"If it's required to track matched rows in the right input, the right bitmap must be present"
);
self.state = NLJState::EmitRightUnmatched;
} else {
self.current_right_batch = None;
self.state = NLJState::FetchingRight;
}
ControlFlow::Continue(())
}
Err(e) => ControlFlow::Break(Poll::Ready(Some(Err(e)))),
}
}
fn handle_emit_right_unmatched(
&mut self,
) -> ControlFlow<Poll<Option<Result<RecordBatch>>>> {
if self.is_memory_limited() {
debug_assert!(
self.current_right_batch_matched.is_some(),
"right bitmap must be present"
);
let bitmap = std::mem::take(&mut self.current_right_batch_matched)
.expect("right bitmap should be available");
let (values, _nulls) = bitmap.into_parts();
if let SpillState::Active(ref mut active) = self.spill_state {
let idx = active.right_batch_index;
active.merge_current_right_bitmap(idx, values);
active.right_batch_index += 1;
}
self.current_right_batch = None;
self.state = NLJState::FetchingRight;
return ControlFlow::Continue(());
}
if let Some(poll) = self.maybe_flush_ready_batch() {
return ControlFlow::Break(poll);
}
debug_assert!(
self.current_right_batch_matched.is_some()
&& self.current_right_batch.is_some(),
"This state is yielding output for unmatched rows in the current right batch, so both the right batch and the bitmap must be present"
);
match self.process_right_unmatched() {
Ok(Some(batch)) => match self.output_buffer.push_batch(batch) {
Ok(()) => {
debug_assert!(self.current_right_batch.is_none());
self.state = NLJState::FetchingRight;
ControlFlow::Continue(())
}
Err(e) => ControlFlow::Break(Poll::Ready(Some(arrow_err!(e)))),
},
Ok(None) => {
debug_assert!(self.current_right_batch.is_none());
self.state = NLJState::FetchingRight;
ControlFlow::Continue(())
}
Err(e) => ControlFlow::Break(Poll::Ready(Some(Err(e)))),
}
}
fn handle_probe_end(&mut self) -> ControlFlow<Poll<Option<Result<RecordBatch>>>> {
let is_emitter = if let SpillState::Active(active) = &mut self.spill_state {
match active.left_spill.report_probe_completed() {
Some(visited) => {
if need_produce_result_in_final(self.join_type) {
active.chunk_reservation.grow(visited.len().div_ceil(8));
active.left_unmatched_pass = Some(LeftUnmatchedPass {
stream: None,
visited,
row_offset: 0,
});
}
true
}
None => false,
}
} else {
match self.get_in_memory_probe_completion() {
Ok(probe_completion) => match probe_completion.report_completed() {
Completion::NotLast => false,
Completion::Abandoned => false,
Completion::Emit(_) => true,
},
Err(e) => return ControlFlow::Break(Poll::Ready(Some(Err(e)))),
}
};
self.is_unmatched_left_emitter = is_emitter;
self.state = NLJState::EmitLeftUnmatched;
ControlFlow::Continue(())
}
fn handle_emit_left_unmatched(
&mut self,
) -> ControlFlow<Poll<Option<Result<RecordBatch>>>> {
if let Some(poll) = self.maybe_flush_ready_batch() {
return ControlFlow::Break(poll);
}
match self.process_left_unmatched() {
Ok(true) => ControlFlow::Continue(()),
Ok(false) => match self.output_buffer.finish_buffered_batch() {
Ok(()) => {
self.buffered_left_data = None;
self.in_memory_probe_completion = None;
self.state = NLJState::Done;
ControlFlow::Continue(())
}
Err(e) => ControlFlow::Break(Poll::Ready(Some(arrow_err!(e)))),
},
Err(e) => ControlFlow::Break(Poll::Ready(Some(Err(e)))),
}
}
fn handle_emit_left_unmatched_memory_limited(
&mut self,
cx: &mut std::task::Context<'_>,
) -> ControlFlow<Poll<Option<Result<RecordBatch>>>> {
if let Some(poll) = self.maybe_flush_ready_batch() {
return ControlFlow::Break(poll);
}
let SpillState::Active(active) = &mut self.spill_state else {
unreachable!("memory-limited EmitLeftUnmatched without Active spill state");
};
if let Some(pass) = active.left_unmatched_pass.as_mut()
&& pass.stream.is_none()
{
let join_metric = self.metrics.join_metrics.join_time.clone();
let _join_timer = join_metric.timer();
match active.left_spill.open_pass() {
Ok(stream) => pass.stream = Some(stream),
Err(e) => return ControlFlow::Break(Poll::Ready(Some(Err(e)))),
}
}
let result = match active.left_unmatched_pass.as_mut() {
Some(pass) => match pass
.stream
.as_mut()
.expect("the pass was opened above")
.poll_next_unpin(cx)
{
Poll::Ready(result) => result,
Poll::Pending => return ControlFlow::Break(Poll::Pending),
},
None => None,
};
let join_metric = self.metrics.join_metrics.join_time.clone();
let _join_timer = join_metric.timer();
match result {
Some(Ok(left_batch)) => {
let pass = active
.left_unmatched_pass
.as_mut()
.expect("a left batch was read from the pass");
let n_rows = left_batch.num_rows();
let bitmap =
BooleanArray::new(pass.visited.slice(pass.row_offset, n_rows), None);
pass.row_offset += n_rows;
match build_unmatched_batch(
&self.output_schema,
&left_batch,
bitmap,
&active.right_schema,
&self.column_indices,
self.join_type,
JoinSide::Left,
) {
Ok(Some(batch)) => match self.output_buffer.push_batch(batch) {
Ok(()) => ControlFlow::Continue(()),
Err(e) => ControlFlow::Break(Poll::Ready(Some(arrow_err!(e)))),
},
Ok(None) => ControlFlow::Continue(()),
Err(e) => ControlFlow::Break(Poll::Ready(Some(Err(e)))),
}
}
Some(Err(e)) => ControlFlow::Break(Poll::Ready(Some(Err(e)))),
None => {
active.left_unmatched_pass = None;
active.chunk_reservation.free();
match self.output_buffer.finish_buffered_batch() {
Ok(()) => {
self.state = NLJState::Done;
ControlFlow::Continue(())
}
Err(e) => ControlFlow::Break(Poll::Ready(Some(arrow_err!(e)))),
}
}
}
}
fn handle_emit_global_right_unmatched(
&mut self,
cx: &mut std::task::Context<'_>,
) -> ControlFlow<Poll<Option<Result<RecordBatch>>>> {
if let Some(poll) = self.maybe_flush_ready_batch() {
return ControlFlow::Break(poll);
}
if self.right_data.is_none() {
let join_metric = self.metrics.join_metrics.join_time.clone();
let _join_timer = join_metric.timer();
let SpillState::Active(ref mut active) = self.spill_state else {
unreachable!("EmitGlobalRightUnmatched without Active spill state");
};
active.right_batch_index = 0;
match active.right_input.open_pass() {
Ok(stream) => {
self.right_data = Some(stream);
}
Err(e) => {
return ControlFlow::Break(Poll::Ready(Some(Err(e))));
}
}
}
let result = match self
.right_data
.as_mut()
.expect("right_data must be present")
.poll_next_unpin(cx)
{
Poll::Ready(result) => result,
Poll::Pending => return ControlFlow::Break(Poll::Pending),
};
let join_metric = self.metrics.join_metrics.join_time.clone();
let _join_timer = join_metric.timer();
match result {
Some(Ok(right_batch)) => {
if right_batch.num_rows() == 0 {
return ControlFlow::Continue(());
}
let SpillState::Active(ref mut active) = self.spill_state else {
unreachable!();
};
let idx = active.right_batch_index;
active.right_batch_index += 1;
let bitmap = if idx < active.global_right_bitmaps.len() {
BooleanArray::new(active.global_right_bitmaps[idx].clone(), None)
} else {
BooleanArray::new(
BooleanBuffer::new_unset(right_batch.num_rows()),
None,
)
};
match build_unmatched_batch(
&self.output_schema,
&right_batch,
bitmap,
&active.left_spill.schema,
&self.column_indices,
self.join_type,
JoinSide::Right,
) {
Ok(Some(batch)) => match self.output_buffer.push_batch(batch) {
Ok(()) => ControlFlow::Continue(()),
Err(e) => ControlFlow::Break(Poll::Ready(Some(arrow_err!(e)))),
},
Ok(None) => ControlFlow::Continue(()),
Err(e) => ControlFlow::Break(Poll::Ready(Some(Err(e)))),
}
}
Some(Err(e)) => ControlFlow::Break(Poll::Ready(Some(Err(e)))),
None => {
self.right_data = None;
self.state = NLJState::ProbeEnd;
ControlFlow::Continue(())
}
}
}
fn handle_done(&mut self) -> Poll<Option<Result<RecordBatch>>> {
if let Some(poll) = self.maybe_flush_ready_batch() {
return poll;
}
if !self.handled_empty_output {
let zero_count = Count::new();
if *self.metrics.join_metrics.baseline.output_rows() == zero_count {
let empty_batch = RecordBatch::new_empty(Arc::clone(&self.output_schema));
self.handled_empty_output = true;
return Poll::Ready(Some(Ok(empty_batch)));
}
}
Poll::Ready(None)
}
fn process_probe_batch(&mut self) -> Result<bool> {
let left_data = Arc::clone(self.get_left_data()?);
if matches!(self.join_type, JoinType::RightSemi | JoinType::RightAnti) {
if self.right_existence_probe.is_none() {
let right = self.current_right_batch.as_ref().ok_or_else(|| {
internal_datafusion_err!("Right batch should be available")
})?;
self.right_existence_probe =
Some(RightExistenceProbe::new(right, self.join_filter.as_ref())?);
}
let probe = self.right_existence_probe.as_mut().unwrap();
if probe.remaining == 0 || self.left_probe_idx >= left_data.batch().num_rows()
{
let mut probe = self.right_existence_probe.take().unwrap();
self.current_right_batch_matched =
Some(BooleanArray::new(probe.matched.finish(), None));
return Ok(false);
}
self.left_probe_idx +=
probe.probe(left_data.batch(), self.left_probe_idx, self.batch_size)?;
return Ok(true);
}
let right_batch = self
.current_right_batch
.as_ref()
.ok_or_else(|| internal_datafusion_err!("Right batch should be available"))?
.clone();
if self.left_probe_idx >= left_data.batch().num_rows() {
return Ok(false);
}
debug_assert_ne!(
right_batch.num_rows(),
0,
"When fetching the right batch, empty batches will be skipped"
);
let l_row_cnt_ratio = self.batch_size / right_batch.num_rows();
if l_row_cnt_ratio > 10 {
let l_row_count = std::cmp::min(
l_row_cnt_ratio,
left_data.batch().num_rows() - self.left_probe_idx,
);
debug_assert!(
l_row_count != 0,
"This function should only be entered when there are remaining left rows to process"
);
let joined_batch = self.process_left_range_join(
&left_data,
&right_batch,
self.left_probe_idx,
l_row_count,
)?;
if let Some(batch) = joined_batch {
self.output_buffer.push_batch(batch)?;
}
self.left_probe_idx += l_row_count;
return Ok(true);
}
let l_idx = self.left_probe_idx;
let joined_batch =
self.process_single_left_row_join(&left_data, &right_batch, l_idx)?;
if let Some(batch) = joined_batch {
self.output_buffer.push_batch(batch)?;
}
self.left_probe_idx += 1;
Ok(true)
}
fn process_left_range_join(
&mut self,
left_data: &JoinLeftData,
right_batch: &RecordBatch,
l_start_index: usize,
l_row_count: usize,
) -> Result<Option<RecordBatch>> {
let left_batch = left_data.batch();
let right_rows = right_batch.num_rows();
let total_rows = l_row_count * right_rows;
let left_indices = left_batch.row_indices(
(0..l_row_count)
.flat_map(|i| std::iter::repeat_n(l_start_index + i, right_rows)),
)?;
let right_indices: UInt32Array = UInt32Array::from_iter_values(
(0..l_row_count).flat_map(|_| 0..right_rows as u32),
);
debug_assert!(
left_indices.len() == right_indices.len()
&& right_indices.len() == total_rows,
"The length or cartesian product should be (left_size * right_size)",
);
let bitmap_combined = if let Some(filter) = &self.join_filter {
apply_filter_to_indices(
left_data.batch(),
right_batch,
&left_indices,
&right_indices,
filter,
)?
} else {
BooleanArray::new(BooleanBuffer::new_set(total_rows), None)
};
let mut left_bitmap = if need_produce_result_in_final(self.join_type) {
Some(left_data.bitmap().lock())
} else {
None
};
let mut local_right_bitmap = if self.should_track_unmatched_right {
let mut current_right_batch_bitmap = BooleanBufferBuilder::new(right_rows);
current_right_batch_bitmap.append_n(right_rows, false);
Some(current_right_batch_bitmap)
} else {
None
};
for (i, is_matched) in bitmap_combined.iter().enumerate() {
let is_matched = is_matched.ok_or_else(|| {
internal_datafusion_err!("Must be Some after the previous combining step")
})?;
let l_index = l_start_index + i / right_rows;
let r_index = i % right_rows;
if let Some(bitmap) = left_bitmap.as_mut()
&& is_matched
{
bitmap.set_bit(l_index, true);
}
if let Some(bitmap) = local_right_bitmap.as_mut()
&& is_matched
{
bitmap.set_bit(r_index, true);
}
}
if self.should_track_unmatched_right {
let global_right_bitmap =
std::mem::take(&mut self.current_right_batch_matched).ok_or_else(
|| internal_datafusion_err!("right batch's bitmap should be present"),
)?;
let (buf, nulls) = global_right_bitmap.into_parts();
debug_assert!(nulls.is_none());
let current_right_bitmap = local_right_bitmap
.ok_or_else(|| {
internal_datafusion_err!(
"Should be Some if the current join type requires right bitmap"
)
})?
.finish();
let updated_global_right_bitmap = buf.bitor(¤t_right_bitmap);
self.current_right_batch_matched =
Some(BooleanArray::new(updated_global_right_bitmap, None));
}
if matches!(
self.join_type,
JoinType::LeftAnti
| JoinType::LeftSemi
| JoinType::LeftMark
| JoinType::RightAnti
| JoinType::RightMark
| JoinType::RightSemi
) {
return Ok(None);
}
if self.output_schema.fields().is_empty() {
let row_count = bitmap_combined.true_count();
return Ok(Some(create_record_batch_with_empty_schema(
Arc::clone(&self.output_schema),
row_count,
)?));
}
let mut out_columns: Vec<Arc<dyn Array>> =
Vec::with_capacity(self.output_schema.fields().len());
for column_index in &self.column_indices {
let array = if column_index.side == JoinSide::Left {
left_batch.take_column(column_index.index, &left_indices)?
} else {
let col = right_batch.column(column_index.index);
take(col.as_ref(), &right_indices, None)?
};
out_columns.push(array);
}
let pre_filtered =
RecordBatch::try_new(Arc::clone(&self.output_schema), out_columns)?;
let filtered = filter_record_batch(&pre_filtered, &bitmap_combined)?;
Ok(Some(filtered))
}
fn process_single_left_row_join(
&mut self,
left_data: &JoinLeftData,
right_batch: &RecordBatch,
l_index: usize,
) -> Result<Option<RecordBatch>> {
let right_row_count = right_batch.num_rows();
if right_row_count == 0 {
return Ok(None);
}
let left_row = left_data.batch().row(l_index)?;
let cur_right_bitmap = if let Some(filter) = &self.join_filter {
apply_filter_to_row_join_batch(left_row, right_batch, filter)?
} else {
BooleanArray::new(BooleanBuffer::new_set(right_row_count), None)
};
self.update_matched_bitmap(l_index, &cur_right_bitmap)?;
if matches!(
self.join_type,
JoinType::LeftAnti
| JoinType::LeftSemi
| JoinType::LeftMark
| JoinType::RightAnti
| JoinType::RightMark
| JoinType::RightSemi
) {
return Ok(None);
}
if !cur_right_bitmap.has_true() {
Ok(None)
} else {
let join_batch = build_row_join_batch(
&self.output_schema,
left_row,
right_batch,
Some(cur_right_bitmap),
&self.column_indices,
JoinSide::Left,
)?;
Ok(join_batch)
}
}
fn process_left_unmatched(&mut self) -> Result<bool> {
let left_data = self.get_left_data()?;
let left_batch = left_data.batch();
let join_type_no_produce_left = !need_produce_result_in_final(self.join_type);
let finished = self.left_emit_idx >= left_batch.num_rows();
if join_type_no_produce_left || !self.is_unmatched_left_emitter || finished {
return Ok(false);
}
let start_idx = self.left_emit_idx;
let end_idx = std::cmp::min(start_idx + self.batch_size, left_batch.num_rows());
if let Some(batch) =
self.process_left_unmatched_range(left_data, start_idx, end_idx)?
{
self.output_buffer.push_batch(batch)?;
}
self.left_emit_idx = end_idx;
Ok(true)
}
fn process_left_unmatched_range(
&self,
left_data: &JoinLeftData,
start_idx: usize,
end_idx: usize,
) -> Result<Option<RecordBatch>> {
if start_idx == end_idx {
return Ok(None);
}
let left_batch_sliced =
left_data.batch().slice(start_idx, end_idx - start_idx)?;
let bitmap_sliced = {
let bitmap = left_data.bitmap().lock();
BooleanBuffer::collect_bool(end_idx - start_idx, |i| {
bitmap.get_bit(start_idx + i)
})
};
let bitmap_sliced = BooleanArray::new(bitmap_sliced, None);
let right_schema = self
.right_data
.as_ref()
.expect("right_data must be present when building unmatched batch")
.schema();
build_unmatched_batch(
&self.output_schema,
&left_batch_sliced,
bitmap_sliced,
&right_schema,
&self.column_indices,
self.join_type,
JoinSide::Left,
)
}
fn process_right_unmatched(&mut self) -> Result<Option<RecordBatch>> {
let right_batch_bitmap: BooleanArray =
std::mem::take(&mut self.current_right_batch_matched).ok_or_else(|| {
internal_datafusion_err!("right bitmap should be available")
})?;
let right_batch = self.current_right_batch.take();
let cur_right_batch = unwrap_or_internal_err!(right_batch);
let left_data = self.get_left_data()?;
let left_schema = left_data.batch().schema();
let res = build_unmatched_batch(
&self.output_schema,
&cur_right_batch,
right_batch_bitmap,
&left_schema,
&self.column_indices,
self.join_type,
JoinSide::Right,
);
self.current_right_batch_matched = None;
res
}
fn get_left_data(&self) -> Result<&Arc<JoinLeftData>> {
self.buffered_left_data
.as_ref()
.ok_or_else(|| internal_datafusion_err!("LeftData should be available"))
}
fn get_in_memory_probe_completion(&self) -> Result<&Arc<ProbeCompletion>> {
self.in_memory_probe_completion.as_ref().ok_or_else(|| {
internal_datafusion_err!("In-memory probe completion should be available")
})
}
fn maybe_flush_ready_batch(&mut self) -> Option<Poll<Option<Result<RecordBatch>>>> {
if self.output_buffer.has_completed_batch()
&& let Some(batch) = self.output_buffer.next_completed_batch()
{
let output_rows = batch.num_rows();
self.metrics.selectivity.add_part(output_rows);
return Some(Poll::Ready(Some(Ok(batch))));
}
None
}
fn update_matched_bitmap(
&mut self,
l_index: usize,
r_matched_bitmap: &BooleanArray,
) -> Result<()> {
let left_data = self.get_left_data()?;
if need_produce_result_in_final(self.join_type) && r_matched_bitmap.has_true() {
let mut bitmap = left_data.bitmap().lock();
bitmap.set_bit(l_index, true);
}
if self.should_track_unmatched_right {
debug_assert!(self.current_right_batch_matched.is_some());
let right_bitmap = std::mem::take(&mut self.current_right_batch_matched)
.ok_or_else(|| {
internal_datafusion_err!("right batch's bitmap should be present")
})?;
let (buf, nulls) = right_bitmap.into_parts();
debug_assert!(nulls.is_none());
let updated_right_bitmap = buf.bitor(r_matched_bitmap.values());
self.current_right_batch_matched =
Some(BooleanArray::new(updated_right_bitmap, None));
}
Ok(())
}
}
fn apply_filter_to_indices(
left: &LogicalBatch,
right: &RecordBatch,
left_indices: &RowIndices,
right_indices: &UInt32Array,
filter: &JoinFilter,
) -> Result<BooleanArray> {
let columns = filter
.column_indices()
.iter()
.map(|column| {
if column.side == JoinSide::Left {
left.take_column(column.index, left_indices)
} else {
Ok(take(
right.column(column.index).as_ref(),
right_indices,
None,
)?)
}
})
.collect::<Result<Vec<_>>>()?;
let options = RecordBatchOptions::new().with_row_count(Some(left_indices.len()));
let intermediate = RecordBatch::try_new_with_options(
Arc::clone(filter.schema()),
columns,
&options,
)?;
let result = filter
.expression()
.evaluate(&intermediate)?
.into_array(intermediate.num_rows())?;
Ok(boolean_mask_from_filter(as_boolean_array(&result)?))
}
fn apply_filter_to_row_join_batch(
left_row: BatchRow<'_>,
right_batch: &RecordBatch,
filter: &JoinFilter,
) -> Result<BooleanArray> {
debug_assert!(right_batch.num_rows() != 0);
let intermediate_batch = if filter.schema.fields().is_empty() {
create_record_batch_with_empty_schema(
Arc::new((*filter.schema).clone()),
right_batch.num_rows(),
)?
} else {
build_row_join_batch(
&filter.schema,
left_row,
right_batch,
None,
&filter.column_indices,
JoinSide::Left,
)?
.ok_or_else(|| internal_datafusion_err!("This function assume input batch is not empty, so the intermediate batch can't be empty too"))?
};
let filter_result = filter
.expression()
.evaluate(&intermediate_batch)?
.into_array(intermediate_batch.num_rows())?;
let filter_arr = as_boolean_array(&filter_result)?;
let bitmap_combined = boolean_mask_from_filter(filter_arr);
Ok(bitmap_combined)
}
fn build_row_join_batch(
output_schema: &Schema,
build_row: BatchRow<'_>,
probe_side_batch: &RecordBatch,
probe_side_filter: Option<BooleanArray>,
col_indices: &[ColumnIndex],
build_side: JoinSide,
) -> Result<Option<RecordBatch>> {
debug_assert_ne!(build_side, JoinSide::None);
let filtered_probe_batch = if let Some(filter) = probe_side_filter {
&filter_record_batch(probe_side_batch, &filter)?
} else {
probe_side_batch
};
if filtered_probe_batch.num_rows() == 0 {
return Ok(None);
}
if output_schema.fields.is_empty() {
return Ok(Some(create_record_batch_with_empty_schema(
Arc::new(output_schema.clone()),
filtered_probe_batch.num_rows(),
)?));
}
let mut columns: Vec<Arc<dyn Array>> =
Vec::with_capacity(output_schema.fields().len());
for column_index in col_indices {
let array = if column_index.side == build_side {
let original_left_array = build_row.column(column_index.index)?;
match original_left_array.data_type() {
DataType::List(field) | DataType::LargeList(field)
if field.data_type() == &DataType::Utf8View =>
{
let indices_iter = std::iter::repeat_n(
build_row.index() as u64,
filtered_probe_batch.num_rows(),
);
let indices_array = UInt64Array::from_iter_values(indices_iter);
take(original_left_array.as_ref(), &indices_array, None)?
}
_ => {
let scalar_value = ScalarValue::try_from_array(
original_left_array.as_ref(),
build_row.index(),
)?;
scalar_value.to_array_of_size(filtered_probe_batch.num_rows())?
}
}
} else {
Arc::clone(filtered_probe_batch.column(column_index.index))
};
columns.push(array);
}
Ok(Some(RecordBatch::try_new(
Arc::new(output_schema.clone()),
columns,
)?))
}
fn build_unmatched_batch_empty_schema(
output_schema: &SchemaRef,
batch_bitmap: &BooleanArray,
join_type: JoinType,
) -> Result<Option<RecordBatch>> {
let result_size = match join_type {
JoinType::Left
| JoinType::Right
| JoinType::Full
| JoinType::LeftAnti
| JoinType::RightAnti => batch_bitmap.false_count(),
JoinType::LeftSemi | JoinType::RightSemi => batch_bitmap.true_count(),
JoinType::LeftMark | JoinType::RightMark => batch_bitmap.len(),
_ => unreachable!(),
};
if output_schema.fields().is_empty() {
Ok(Some(create_record_batch_with_empty_schema(
Arc::clone(output_schema),
result_size,
)?))
} else {
Ok(None)
}
}
fn create_record_batch_with_empty_schema(
schema: SchemaRef,
row_count: usize,
) -> Result<RecordBatch> {
let options = RecordBatchOptions::new()
.with_match_field_names(true)
.with_row_count(Some(row_count));
RecordBatch::try_new_with_options(schema, vec![], &options).map_err(|e| {
internal_datafusion_err!("Failed to create empty record batch: {}", e)
})
}
fn build_unmatched_batch(
output_schema: &SchemaRef,
batch: &RecordBatch,
batch_bitmap: BooleanArray,
another_side_schema: &SchemaRef,
col_indices: &[ColumnIndex],
join_type: JoinType,
batch_side: JoinSide,
) -> Result<Option<RecordBatch>> {
debug_assert_ne!(join_type, JoinType::Inner);
debug_assert_ne!(batch_side, JoinSide::None);
if let Some(batch) =
build_unmatched_batch_empty_schema(output_schema, &batch_bitmap, join_type)?
{
return Ok(Some(batch));
}
match join_type {
JoinType::Full | JoinType::Right | JoinType::Left => {
if join_type == JoinType::Right {
debug_assert_eq!(batch_side, JoinSide::Right);
}
if join_type == JoinType::Left {
debug_assert_eq!(batch_side, JoinSide::Left);
}
let flipped_bitmap = not(&batch_bitmap)?;
let left_null_columns: Vec<Arc<dyn Array>> = another_side_schema
.fields()
.iter()
.map(|field| new_null_array(field.data_type(), 1))
.collect();
let nullable_left_schema = Arc::new(Schema::new(
another_side_schema
.fields()
.iter()
.map(|field| (**field).clone().with_nullable(true))
.collect::<Vec<_>>(),
));
let left_null_batch = if nullable_left_schema.fields.is_empty() {
create_record_batch_with_empty_schema(nullable_left_schema, 1)?
} else {
RecordBatch::try_new(nullable_left_schema, left_null_columns)?
};
debug_assert_ne!(batch_side, JoinSide::None);
let opposite_side = batch_side.negate();
build_row_join_batch(
output_schema,
BatchRow::new(&left_null_batch, 0)?,
batch,
Some(flipped_bitmap),
col_indices,
opposite_side,
)
}
JoinType::RightSemi
| JoinType::RightAnti
| JoinType::LeftSemi
| JoinType::LeftAnti => {
if matches!(join_type, JoinType::RightSemi | JoinType::RightAnti) {
debug_assert_eq!(batch_side, JoinSide::Right);
}
if matches!(join_type, JoinType::LeftSemi | JoinType::LeftAnti) {
debug_assert_eq!(batch_side, JoinSide::Left);
}
let bitmap = if matches!(join_type, JoinType::LeftSemi | JoinType::RightSemi)
{
batch_bitmap.clone()
} else {
not(&batch_bitmap)?
};
if !bitmap.has_true() {
return Ok(None);
}
let mut columns: Vec<Arc<dyn Array>> =
Vec::with_capacity(output_schema.fields().len());
for column_index in col_indices {
debug_assert_eq!(column_index.side, batch_side);
let col = batch.column(column_index.index);
let filtered_col = filter(col, &bitmap)?;
columns.push(filtered_col);
}
Ok(Some(RecordBatch::try_new(
Arc::clone(output_schema),
columns,
)?))
}
JoinType::RightMark | JoinType::LeftMark => {
if join_type == JoinType::RightMark {
debug_assert_eq!(batch_side, JoinSide::Right);
}
if join_type == JoinType::LeftMark {
debug_assert_eq!(batch_side, JoinSide::Left);
}
let mut columns: Vec<Arc<dyn Array>> =
Vec::with_capacity(output_schema.fields().len());
let mut right_batch_bitmap_opt = Some(batch_bitmap);
for column_index in col_indices {
if column_index.side == batch_side {
let col = batch.column(column_index.index);
columns.push(Arc::clone(col));
} else if column_index.side == JoinSide::None {
let right_batch_bitmap = std::mem::take(&mut right_batch_bitmap_opt);
match right_batch_bitmap {
Some(right_batch_bitmap) => {
columns.push(Arc::new(right_batch_bitmap))
}
None => unreachable!("Should only be one mark column"),
}
} else {
return internal_err!(
"Not possible to have this join side for RightMark join"
);
}
}
Ok(Some(RecordBatch::try_new(
Arc::clone(output_schema),
columns,
)?))
}
_ => internal_err!(
"If batch is at right side, this function must be handling Full/Right/RightSemi/RightAnti/RightMark joins"
),
}
}
#[cfg(test)]
pub(crate) mod tests {
use std::pin::Pin;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use super::*;
use crate::statistics::{StatisticsArgs, StatisticsContext};
use crate::test::{TestMemoryExec, assert_join_metrics};
use crate::{
common, expressions::Column, repartition::RepartitionExec, test::build_table_i32,
};
use arrow::compute::SortOptions;
use arrow::datatypes::{DataType, Field};
use bytes::Bytes;
use datafusion_common::assert_contains;
use datafusion_common::instant::Instant;
use datafusion_common::test_util::batches_to_sort_string;
use datafusion_common_runtime::SpawnedTask;
use datafusion_execution::disk_manager::{
DiskManager, DiskManagerBuilder, DiskManagerMode,
};
use datafusion_execution::runtime_env::RuntimeEnvBuilder;
use datafusion_execution::spill_file::{SpillFile, SpillWriter, TempFileFactory};
use datafusion_expr::Operator;
use datafusion_physical_expr::expressions::{BinaryExpr, Literal};
use datafusion_physical_expr::{Partitioning, PhysicalExpr};
use datafusion_physical_expr_common::sort_expr::{LexOrdering, PhysicalSortExpr};
use insta::allow_duplicates;
use insta::assert_snapshot;
use rstest::rstest;
#[test]
fn test_nlj_dynamic_filter_pushdown() -> Result<()> {
use crate::filter_pushdown::PushedDown;
use arrow::array::record_batch;
use datafusion_physical_expr::expressions::lit;
let batch = record_batch!(("key", Int32, [1, 2]), ("key", Int32, [2, 1]))?;
let input: Arc<dyn ExecutionPlan> =
TestMemoryExec::try_new_exec(&[vec![batch.clone()]], batch.schema(), None)?;
for join_type in [
JoinType::Inner,
JoinType::Left,
JoinType::Right,
JoinType::Full,
JoinType::LeftSemi,
JoinType::RightSemi,
JoinType::LeftAnti,
JoinType::RightAnti,
JoinType::LeftMark,
JoinType::RightMark,
] {
let join = NestedLoopJoinExec::try_new(
Arc::clone(&input),
Arc::clone(&input),
None,
&join_type,
None,
)?;
for reorder in [false, true] {
let projection =
reorder.then(|| (0..join.schema().fields().len()).rev().collect());
let join = join.with_projection(projection)?;
for output in 0..join.schema().fields().len() {
let column: Arc<dyn PhysicalExpr> =
Arc::new(Column::new(join.schema().field(output).name(), output));
let source = Arc::new(DynamicFilterPhysicalExpr::new(
vec![Arc::clone(&column)],
lit(true),
));
let filters = join
.gather_filters_for_pushdown(
FilterPushdownPhase::Post,
vec![Arc::clone(&source) as _],
&ConfigOptions::default(),
)?
.parent_filters();
let unprojected =
join.projection.as_ref().map_or(output, |p| p[output]);
let side = join.column_indices[unprojected].side;
let expected = match join_type {
JoinType::Inner => {
[side == JoinSide::Left, side == JoinSide::Right]
}
JoinType::Left
| JoinType::LeftSemi
| JoinType::LeftAnti
| JoinType::LeftMark => [side == JoinSide::Left, false],
JoinType::Right
| JoinType::RightSemi
| JoinType::RightAnti
| JoinType::RightMark => [false, side == JoinSide::Right],
JoinType::Full => [false, false],
};
source.update(Arc::new(BinaryExpr::new(
column,
Operator::Eq,
lit(2i32),
)))?;
for (child, accepted) in filters.iter().zip(expected) {
assert_eq!(
matches!(child[0].discriminant, PushedDown::Yes),
accepted,
"{join_type:?}, reorder={reorder}, output={output}"
);
if accepted {
assert_eq!(
child[0].predicate.expression_id(),
source.expression_id()
);
let values = child[0]
.predicate
.evaluate(&batch)?
.into_array(batch.num_rows())?;
assert_eq!(
as_boolean_array(&values)?.iter().collect::<Vec<_>>(),
if join.column_indices[unprojected].index == 0 {
vec![Some(false), Some(true)]
} else {
vec![Some(true), Some(false)]
}
);
}
}
}
}
}
let join = NestedLoopJoinExec::try_new(
Arc::clone(&input),
input,
None,
&JoinType::Inner,
None,
)?;
let left: Arc<dyn PhysicalExpr> = Arc::new(Column::new("key", 0));
let right: Arc<dyn PhysicalExpr> = Arc::new(Column::new("key", 2));
let whole: Arc<dyn PhysicalExpr> = Arc::new(DynamicFilterPhysicalExpr::new(
vec![Arc::clone(&left)],
lit(true),
));
let mixed: Arc<dyn PhysicalExpr> = Arc::new(DynamicFilterPhysicalExpr::new(
vec![Arc::clone(&left), right],
lit(true),
));
let static_filter: Arc<dyn PhysicalExpr> =
Arc::new(BinaryExpr::new(left, Operator::Eq, lit(2i32)));
for (phase, enabled, filters) in [
(FilterPushdownPhase::Pre, true, vec![Arc::clone(&whole)]),
(FilterPushdownPhase::Post, false, vec![whole]),
(FilterPushdownPhase::Post, true, vec![mixed, static_filter]),
] {
let mut config = ConfigOptions::default();
config.optimizer.enable_join_dynamic_filter_pushdown = enabled;
let description =
join.gather_filters_for_pushdown(phase, filters, &config)?;
assert!(
description
.parent_filters()
.iter()
.flatten()
.all(|f| matches!(f.discriminant, PushedDown::No))
);
}
Ok(())
}
fn delayed_stream(batch: RecordBatch, delay: Duration) -> SendableRecordBatchStream {
let schema = batch.schema();
Box::pin(crate::stream::RecordBatchStreamAdapter::new(
schema,
futures::stream::once(async move {
std::thread::sleep(delay);
Ok(batch)
}),
))
}
struct DelayedReadSpillFile {
inner: Arc<dyn SpillFile>,
delay: Duration,
read_count: Arc<AtomicUsize>,
}
impl SpillFile for DelayedReadSpillFile {
fn path(&self) -> Option<&std::path::Path> {
self.inner.path()
}
fn size(&self) -> Option<u64> {
self.inner.size()
}
fn read_stream(
&self,
) -> Result<Pin<Box<dyn Stream<Item = Result<Bytes>> + Send>>> {
let delay = self.delay;
let read_count = Arc::clone(&self.read_count);
let mut delay_first_item = true;
let stream = self.inner.read_stream()?.map(move |item| {
if delay_first_item {
delay_first_item = false;
read_count.fetch_add(1, Ordering::Relaxed);
std::thread::sleep(delay);
}
item
});
Ok(Box::pin(stream))
}
fn open_writer(&self) -> Result<Box<dyn SpillWriter>> {
self.inner.open_writer()
}
}
struct DelayedReadTempFileFactory {
inner: Arc<DiskManager>,
delay: Duration,
read_count: Arc<AtomicUsize>,
}
impl TempFileFactory for DelayedReadTempFileFactory {
fn create_temp_file(&self, description: &str) -> Result<Arc<dyn SpillFile>> {
Ok(Arc::new(DelayedReadSpillFile {
inner: self.inner.create_tmp_file(description)?,
delay: self.delay,
read_count: Arc::clone(&self.read_count),
}))
}
}
fn build_table(
a: (&str, &Vec<i32>),
b: (&str, &Vec<i32>),
c: (&str, &Vec<i32>),
batch_size: Option<usize>,
sorted_column_names: Vec<&str>,
) -> Arc<dyn ExecutionPlan> {
let batch = build_table_i32(a, b, c);
let schema = batch.schema();
let batches = if let Some(batch_size) = batch_size {
let num_batches = batch.num_rows().div_ceil(batch_size);
(0..num_batches)
.map(|i| {
let start = i * batch_size;
let remaining_rows = batch.num_rows() - start;
batch.slice(start, batch_size.min(remaining_rows))
})
.collect::<Vec<_>>()
} else {
vec![batch]
};
let mut sort_info = vec![];
for name in sorted_column_names {
let index = schema.index_of(name).unwrap();
let sort_expr = PhysicalSortExpr::new(
Arc::new(Column::new(name, index)),
SortOptions::new(false, false),
);
sort_info.push(sort_expr);
}
let mut source = TestMemoryExec::try_new(&[batches], schema, None).unwrap();
if let Some(ordering) = LexOrdering::new(sort_info) {
source = source.try_with_sort_information(vec![ordering]).unwrap();
}
let source = Arc::new(source);
Arc::new(TestMemoryExec::update_cache(&source))
}
#[derive(Debug)]
struct OneShotExec {
inner: Arc<dyn ExecutionPlan>,
executions: Arc<AtomicUsize>,
}
impl DisplayAs for OneShotExec {
fn fmt_as(&self, _t: DisplayFormatType, f: &mut Formatter) -> std::fmt::Result {
write!(f, "OneShotExec")
}
}
impl ExecutionPlan for OneShotExec {
fn name(&self) -> &str {
"OneShotExec"
}
fn apply_expressions(
&self,
_f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
) -> Result<TreeNodeRecursion> {
Ok(TreeNodeRecursion::Continue)
}
fn properties(&self) -> &Arc<PlanProperties> {
self.inner.properties()
}
fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
vec![&self.inner]
}
fn with_new_children(
self: Arc<Self>,
_children: Vec<Arc<dyn ExecutionPlan>>,
) -> Result<Arc<dyn ExecutionPlan>> {
Ok(self)
}
fn execute(
&self,
partition: usize,
context: Arc<TaskContext>,
) -> Result<SendableRecordBatchStream> {
if self.executions.fetch_add(1, Ordering::Relaxed) == 0 {
self.inner.execute(partition, context)
} else {
Ok(Box::pin(crate::stream::RecordBatchStreamAdapter::new(
self.inner.schema(),
futures::stream::empty(),
)))
}
}
}
#[tokio::test]
async fn memory_limited_left_side_reads_the_child_once() -> Result<()> {
let executions = Arc::new(AtomicUsize::new(0));
let left = Arc::new(OneShotExec {
inner: build_left_table(),
executions: Arc::clone(&executions),
});
let right = build_right_table();
let filter = prepare_join_filter();
let task_ctx = task_ctx_with_memory_limit(50, 16)?;
let (_, batches, metrics) =
join_collect(left, right, &JoinType::Inner, Some(filter), task_ctx).await?;
assert!(
metrics.spill_count().unwrap_or(0) > 0,
"expected the tight memory limit to spill the left side"
);
assert_eq!(
executions.load(Ordering::Relaxed),
1,
"the left child must be executed exactly once"
);
allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+----+----+----+----+
| a1 | b1 | c1 | a2 | b2 | c2 |
+----+----+----+----+----+----+
| 5 | 5 | 50 | 2 | 2 | 80 |
+----+----+----+----+----+----+
"));
Ok(())
}
fn build_left_table() -> Arc<dyn ExecutionPlan> {
build_table(
("a1", &vec![5, 9, 11]),
("b1", &vec![5, 8, 8]),
("c1", &vec![50, 90, 110]),
None,
Vec::new(),
)
}
fn build_right_table() -> Arc<dyn ExecutionPlan> {
build_table(
("a2", &vec![12, 2, 10]),
("b2", &vec![10, 2, 10]),
("c2", &vec![40, 80, 100]),
None,
Vec::new(),
)
}
async fn run_join_with_child_poll_delays(
left_delay: Duration,
right_delay: Duration,
memory_limited: bool,
) -> Result<(Duration, Duration, Duration)> {
run_join_with_poll_delays(
left_delay,
right_delay,
memory_limited,
JoinType::Inner,
None,
)
.await
}
async fn run_join_with_poll_delays(
left_delay: Duration,
right_delay: Duration,
memory_limited: bool,
join_type: JoinType,
spill_read_delay: Option<(Duration, Arc<AtomicUsize>)>,
) -> Result<(Duration, Duration, Duration)> {
let left_batch =
build_table_i32(("a1", &vec![1]), ("b1", &vec![2]), ("c1", &vec![3]));
let right_batch =
build_table_i32(("a2", &vec![4]), ("b2", &vec![5]), ("c2", &vec![6]));
let left_schema = left_batch.schema();
let right_schema = right_batch.schema();
let left_stream = delayed_stream(left_batch.clone(), left_delay);
let right_stream = delayed_stream(right_batch, right_delay);
let task_ctx = if let Some((delay, read_count)) = spill_read_delay {
let inner = Arc::new(
DiskManagerBuilder::default()
.with_mode(DiskManagerMode::OsTmpDirectory)
.build()?,
);
let runtime = RuntimeEnvBuilder::new()
.with_disk_manager_builder(DiskManagerBuilder::default().with_mode(
DiskManagerMode::Custom(Arc::new(DelayedReadTempFileFactory {
inner,
delay,
read_count,
})),
))
.build_arc()?;
Arc::new(TaskContext::default().with_runtime(runtime))
} else {
Arc::new(TaskContext::default())
};
let metrics_set = ExecutionPlanMetricsSet::new();
let metrics = NestedLoopJoinMetrics::new(&metrics_set, 0);
let build_time = metrics.join_metrics.build_time.clone();
let join_time = metrics.join_metrics.join_time.clone();
let (left_data, right_stream, spill_state) = if memory_limited {
let global_right_bitmaps_reservation =
MemoryConsumer::new("NestedLoopJoinGlobalRightBitmaps[test]".to_string())
.register(task_ctx.memory_pool());
let spill_manager = SpillManager::new(
task_ctx.runtime_env(),
metrics.spill_metrics.clone(),
Arc::clone(&right_schema),
);
let left_spill_manager = SpillManager::new(
task_ctx.runtime_env(),
metrics.spill_metrics.clone(),
Arc::clone(&left_schema),
);
let mut left_spill_file =
left_spill_manager.create_in_progress_file("test left spill")?;
left_spill_file.append_batch(&left_batch)?;
let left_spill_file = left_spill_file
.finish()?
.expect("the test left spill contains one batch");
let left_spill = LeftSpillData::new(
SpilledLeftFile {
spill_manager: left_spill_manager,
spill_file: left_spill_file,
num_rows: left_batch.num_rows(),
},
Arc::clone(&left_schema),
need_produce_result_in_final(join_type),
1,
MemoryConsumer::new("NestedLoopJoinLoad[test]".to_string())
.register(task_ctx.memory_pool()),
);
*left_spill.reader.lock() = Some(LeftChunkReader {
stream: left_stream,
carryover: None,
});
let active = SpillStateActive {
left_spill: Arc::new(left_spill),
left_chunk_barrier: Arc::new(LeftChunkBarrier::new(1)),
chunk_index: 0,
chunk_fetch: None,
current_chunk: None,
memory_pool: Arc::clone(task_ctx.memory_pool()),
chunk_reservation: MemoryConsumer::new(
"NestedLoopJoinLeftVisited[test]".to_string(),
)
.register(task_ctx.memory_pool()),
chunk_row_offset: 0,
left_unmatched_pass: None,
right_schema: Arc::clone(&right_schema),
right_input: ReplayableStreamSource::new(
right_stream,
spill_manager,
"test right spill",
),
global_right_bitmaps: Vec::new(),
global_right_bitmaps_reservation,
right_batch_index: 0,
};
(
OnceFut::new(async { internal_err!("unused left data was polled") }),
Box::pin(crate::EmptyRecordBatchStream::new(Arc::clone(
&right_schema,
))) as SendableRecordBatchStream,
SpillState::Active(Box::new(active)),
)
} else {
let reservation = MemoryConsumer::new("NestedLoopJoinLoad[test]".to_string())
.register(task_ctx.memory_pool());
(
OnceFut::new(collect_left_input(
left_stream,
metrics.join_metrics.clone(),
reservation,
false,
1,
None,
Arc::new(LeftChunkBarrier::new(1)),
)),
right_stream,
SpillState::Disabled,
)
};
let (output_schema, column_indices) =
build_join_schema(&left_schema, &right_schema, &join_type);
let stream = NestedLoopJoinStream::new(
Arc::new(output_schema),
None,
join_type,
right_stream,
left_data,
column_indices,
metrics,
1024,
spill_state,
);
let start = Instant::now();
let batches = common::collect(Box::pin(stream)).await?;
let wall_time = start.elapsed();
assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::<usize>(), 1);
Ok((
Duration::from_nanos(build_time.value() as u64),
Duration::from_nanos(join_time.value() as u64),
wall_time,
))
}
async fn check_child_poll_time_excluded<F, Fut>(mut run: F) -> Result<()>
where
F: FnMut(Duration) -> Fut,
Fut: Future<Output = Result<(Duration, Duration)>>,
{
let mut delay = Duration::from_millis(50);
for attempt in 0..3 {
let (operator_time, wall_time) = run(delay).await?;
assert!(
!operator_time.is_zero(),
"operator work should still be timed"
);
assert!(
wall_time >= delay,
"child poll delay should dominate wall time: {wall_time:?} < {delay:?}"
);
if operator_time < delay {
return Ok(());
}
assert!(
attempt < 2,
"operator time ({operator_time:?}) included the child poll delay ({delay:?})"
);
delay *= 4;
}
unreachable!()
}
#[tokio::test]
async fn build_time_excludes_left_child_poll() -> Result<()> {
check_child_poll_time_excluded(|delay| async move {
let (build_time, _, wall_time) =
run_join_with_child_poll_delays(delay, Duration::ZERO, false).await?;
Ok((build_time, wall_time))
})
.await
}
#[tokio::test]
async fn join_time_excludes_right_child_poll() -> Result<()> {
check_child_poll_time_excluded(|delay| async move {
let (_, join_time, wall_time) =
run_join_with_child_poll_delays(Duration::ZERO, delay, false).await?;
Ok((join_time, wall_time))
})
.await
}
#[tokio::test]
async fn build_time_excludes_spill_stream_poll() -> Result<()> {
check_child_poll_time_excluded(|delay| async move {
let (build_time, _, wall_time) =
run_join_with_child_poll_delays(delay, Duration::ZERO, true).await?;
Ok((build_time, wall_time))
})
.await
}
#[tokio::test]
async fn join_time_excludes_replayable_input_poll() -> Result<()> {
check_child_poll_time_excluded(|delay| async move {
let (_, join_time, wall_time) =
run_join_with_child_poll_delays(Duration::ZERO, delay, true).await?;
Ok((join_time, wall_time))
})
.await
}
#[tokio::test(flavor = "current_thread")]
async fn join_time_excludes_global_right_unmatched_replay_poll() -> Result<()> {
check_child_poll_time_excluded(|delay| async move {
let read_count = Arc::new(AtomicUsize::new(0));
let (_, join_time, wall_time) = run_join_with_poll_delays(
Duration::ZERO,
Duration::ZERO,
true,
JoinType::Right,
Some((delay, Arc::clone(&read_count))),
)
.await?;
assert_eq!(
read_count.load(Ordering::Relaxed),
1,
"EmitGlobalRightUnmatched should replay the right spill exactly once"
);
Ok((join_time, wall_time))
})
.await
}
fn prepare_join_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("x", DataType::Int32, true),
Field::new("x", DataType::Int32, true),
]);
let left_filter = 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 right_filter = Arc::new(BinaryExpr::new(
Arc::new(Column::new("x", 1)),
Operator::NotEq,
Arc::new(Literal::new(ScalarValue::Int32(Some(10)))),
)) as Arc<dyn PhysicalExpr>;
let filter_expression =
Arc::new(BinaryExpr::new(left_filter, Operator::And, right_filter))
as Arc<dyn PhysicalExpr>;
JoinFilter::new(
filter_expression,
column_indices,
Arc::new(intermediate_schema),
)
}
pub(crate) async fn multi_partitioned_join_collect(
left: Arc<dyn ExecutionPlan>,
right: Arc<dyn ExecutionPlan>,
join_type: &JoinType,
join_filter: Option<JoinFilter>,
context: Arc<TaskContext>,
) -> Result<(Vec<String>, Vec<RecordBatch>, MetricsSet)> {
let partition_count = 4;
let right = Arc::new(RepartitionExec::try_new(
right,
Partitioning::RoundRobinBatch(partition_count),
)?) as Arc<dyn ExecutionPlan>;
let nested_loop_join =
NestedLoopJoinExec::try_new(left, right, join_filter, join_type, None)?;
let columns = columns(&nested_loop_join.schema());
let mut batches = vec![];
for i in 0..partition_count {
let stream = nested_loop_join.execute(i, Arc::clone(&context))?;
let more_batches = common::collect(stream).await?;
batches.extend(
more_batches
.into_iter()
.inspect(|b| {
assert!(b.num_rows() <= context.session_config().batch_size())
})
.filter(|b| b.num_rows() > 0)
.collect::<Vec<_>>(),
);
}
let metrics = nested_loop_join.metrics().unwrap();
Ok((columns, batches, metrics))
}
fn new_task_ctx(batch_size: usize) -> Arc<TaskContext> {
let base = TaskContext::default();
let cfg = base.session_config().clone().with_batch_size(batch_size);
Arc::new(base.with_session_config(cfg))
}
#[rstest]
#[tokio::test]
async fn join_inner_with_filter(#[values(1, 2, 16)] batch_size: usize) -> Result<()> {
let task_ctx = new_task_ctx(batch_size);
let left = build_left_table();
let right = build_right_table();
let filter = prepare_join_filter();
let (columns, batches, metrics) = multi_partitioned_join_collect(
left,
right,
&JoinType::Inner,
Some(filter),
task_ctx,
)
.await?;
assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b2", "c2"]);
allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+----+----+----+----+
| a1 | b1 | c1 | a2 | b2 | c2 |
+----+----+----+----+----+----+
| 5 | 5 | 50 | 2 | 2 | 80 |
+----+----+----+----+----+----+
"));
assert_join_metrics!(metrics, 1);
Ok(())
}
#[rstest]
#[tokio::test]
async fn join_left_with_filter(#[values(1, 2, 16)] batch_size: usize) -> Result<()> {
let task_ctx = new_task_ctx(batch_size);
let left = build_left_table();
let right = build_right_table();
let filter = prepare_join_filter();
let (columns, batches, metrics) = multi_partitioned_join_collect(
left,
right,
&JoinType::Left,
Some(filter),
task_ctx,
)
.await?;
assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b2", "c2"]);
allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+-----+----+----+----+
| a1 | b1 | c1 | a2 | b2 | c2 |
+----+----+-----+----+----+----+
| 11 | 8 | 110 | | | |
| 5 | 5 | 50 | 2 | 2 | 80 |
| 9 | 8 | 90 | | | |
+----+----+-----+----+----+----+
"));
assert_join_metrics!(metrics, 3);
Ok(())
}
#[rstest]
#[tokio::test]
async fn join_right_with_filter(#[values(1, 2, 16)] batch_size: usize) -> Result<()> {
let task_ctx = new_task_ctx(batch_size);
let left = build_left_table();
let right = build_right_table();
let filter = prepare_join_filter();
let (columns, batches, metrics) = multi_partitioned_join_collect(
left,
right,
&JoinType::Right,
Some(filter),
task_ctx,
)
.await?;
assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b2", "c2"]);
allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+----+----+----+-----+
| a1 | b1 | c1 | a2 | b2 | c2 |
+----+----+----+----+----+-----+
| | | | 10 | 10 | 100 |
| | | | 12 | 10 | 40 |
| 5 | 5 | 50 | 2 | 2 | 80 |
+----+----+----+----+----+-----+
"));
assert_join_metrics!(metrics, 3);
Ok(())
}
#[rstest]
#[tokio::test]
async fn join_full_with_filter(#[values(1, 2, 16)] batch_size: usize) -> Result<()> {
let task_ctx = new_task_ctx(batch_size);
let left = build_left_table();
let right = build_right_table();
let filter = prepare_join_filter();
let (columns, batches, metrics) = multi_partitioned_join_collect(
left,
right,
&JoinType::Full,
Some(filter),
task_ctx,
)
.await?;
assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b2", "c2"]);
allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+-----+----+----+-----+
| a1 | b1 | c1 | a2 | b2 | c2 |
+----+----+-----+----+----+-----+
| | | | 10 | 10 | 100 |
| | | | 12 | 10 | 40 |
| 11 | 8 | 110 | | | |
| 5 | 5 | 50 | 2 | 2 | 80 |
| 9 | 8 | 90 | | | |
+----+----+-----+----+----+-----+
"));
assert_join_metrics!(metrics, 5);
Ok(())
}
#[tokio::test]
async fn test_left_semi_join_reports_final_emission() -> Result<()> {
let left = build_left_table();
let right = build_right_table();
let join =
NestedLoopJoinExec::try_new(left, right, None, &JoinType::LeftSemi, None)?;
assert_eq!(join.properties().emission_type, EmissionType::Final);
Ok(())
}
#[rstest]
#[tokio::test]
async fn join_left_semi_with_filter(
#[values(1, 2, 16)] batch_size: usize,
) -> Result<()> {
let task_ctx = new_task_ctx(batch_size);
let left = build_left_table();
let right = build_right_table();
let filter = prepare_join_filter();
let (columns, batches, metrics) = multi_partitioned_join_collect(
left,
right,
&JoinType::LeftSemi,
Some(filter),
task_ctx,
)
.await?;
assert_eq!(columns, vec!["a1", "b1", "c1"]);
allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+----+
| a1 | b1 | c1 |
+----+----+----+
| 5 | 5 | 50 |
+----+----+----+
"));
assert_join_metrics!(metrics, 1);
Ok(())
}
#[rstest]
#[tokio::test]
async fn join_left_anti_with_filter(
#[values(1, 2, 16)] batch_size: usize,
) -> Result<()> {
let task_ctx = new_task_ctx(batch_size);
let left = build_left_table();
let right = build_right_table();
let filter = prepare_join_filter();
let (columns, batches, metrics) = multi_partitioned_join_collect(
left,
right,
&JoinType::LeftAnti,
Some(filter),
task_ctx,
)
.await?;
assert_eq!(columns, vec!["a1", "b1", "c1"]);
allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+-----+
| a1 | b1 | c1 |
+----+----+-----+
| 11 | 8 | 110 |
| 9 | 8 | 90 |
+----+----+-----+
"));
assert_join_metrics!(metrics, 2);
Ok(())
}
#[tokio::test]
async fn join_has_correct_stats() -> Result<()> {
let left = build_left_table();
let right = build_right_table();
let nested_loop_join = NestedLoopJoinExec::try_new(
left,
right,
None,
&JoinType::Left,
Some(vec![1, 2]),
)?;
let stats = StatisticsContext::new()
.compute(&nested_loop_join, &StatisticsArgs::new())?;
assert_eq!(
nested_loop_join.schema().fields().len(),
stats.column_statistics.len(),
);
assert_eq!(2, stats.column_statistics.len());
Ok(())
}
#[test]
fn right_existence_compacts_zero_column_candidates() -> Result<()> {
let right = create_record_batch_with_empty_schema(Arc::new(Schema::empty()), 5)?;
let mut probe = RightExistenceProbe::new(&right, None)?;
probe.update_matches(&BooleanBuffer::from(vec![true, false, true, true, false]));
probe.compact()?;
assert_eq!(probe.candidates.num_columns(), 0);
assert_eq!(probe.candidates.num_rows(), 2);
assert_eq!(probe.original_indices, Some(vec![1, 4]));
probe.update_matches(&BooleanBuffer::from(vec![false, true]));
assert_eq!(probe.remaining, 1);
assert_eq!(
probe.matched.finish().set_indices().collect::<Vec<_>>(),
vec![0, 2, 3, 4]
);
Ok(())
}
#[rstest]
fn right_existence_sliced_match_words(
#[values(63, 64, 65)] rows: usize,
) -> Result<()> {
let right =
create_record_batch_with_empty_schema(Arc::new(Schema::empty()), rows)?;
let mut probe = RightExistenceProbe::new(&right, None)?;
let mut bits = vec![true; 3 + rows * 3 + 7];
for left in 0..3 {
for candidate in 0..rows {
bits[3 + left * rows + candidate] =
candidate == 0 || candidate == rows - 1;
}
}
let mask = BooleanBuffer::from(bits).slice(3, rows * 3);
probe.update_matches(&mask);
probe.update_matches(&mask);
assert_eq!(probe.remaining, rows - 2);
assert_eq!(
probe.matched.finish().set_indices().collect::<Vec<_>>(),
vec![0, rows - 1]
);
Ok(())
}
#[rstest]
#[case(JoinType::RightSemi)]
#[case(JoinType::RightAnti)]
#[tokio::test]
async fn right_existence_stops_after_all_rows_match(
#[case] join_type: JoinType,
#[values(false, true)] with_filter: bool,
) -> Result<()> {
let ctx = new_task_ctx(65);
let left = create_record_batch_with_empty_schema(Arc::new(Schema::empty()), 32)?;
let right = create_record_batch_with_empty_schema(Arc::new(Schema::empty()), 65)?;
let schema = right.schema();
let filter = with_filter.then(|| {
JoinFilter::new(
Arc::new(Literal::new(ScalarValue::Boolean(Some(true)))),
vec![],
Arc::clone(&schema),
)
});
let left_data = JoinLeftData::new(
left.into(),
Mutex::new(BooleanBufferBuilder::new(0)),
MemoryConsumer::new("test").register(ctx.memory_pool()),
);
let mut stream = NestedLoopJoinStream::new(
Arc::clone(&schema),
filter,
join_type,
Box::pin(crate::stream::RecordBatchStreamAdapter::new(
schema,
futures::stream::iter(vec![Ok(right)]),
)),
OnceFut::new(async { internal_err!("unused left input") }),
vec![],
NestedLoopJoinMetrics::new(&ExecutionPlanMetricsSet::new(), 0),
65,
SpillState::Disabled,
);
stream.buffered_left_data = Some(Arc::new(left_data));
let mut cx = std::task::Context::from_waker(futures::task::noop_waker_ref());
assert!(stream.handle_fetching_right(&mut cx).is_continue());
assert!(stream.process_probe_batch()?);
assert_eq!(stream.left_probe_idx, 1);
assert!(
!stream.process_probe_batch()?,
"all right rows already matched"
);
let output = stream.process_right_unmatched()?;
let rows = output.map_or(0, |batch| batch.num_rows());
assert_eq!(
rows,
if join_type == JoinType::RightSemi {
65
} else {
0
}
);
Ok(())
}
#[rstest]
#[tokio::test]
async fn join_right_semi_with_filter(
#[values(1, 2, 16)] batch_size: usize,
) -> Result<()> {
let task_ctx = new_task_ctx(batch_size);
let left = build_left_table();
let right = build_right_table();
let filter = prepare_join_filter();
let (columns, batches, metrics) = multi_partitioned_join_collect(
left,
right,
&JoinType::RightSemi,
Some(filter),
task_ctx,
)
.await?;
assert_eq!(columns, vec!["a2", "b2", "c2"]);
allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+----+
| a2 | b2 | c2 |
+----+----+----+
| 2 | 2 | 80 |
+----+----+----+
"));
assert_join_metrics!(metrics, 1);
Ok(())
}
#[rstest]
#[tokio::test]
async fn join_right_anti_with_filter(
#[values(1, 2, 16)] batch_size: usize,
) -> Result<()> {
let task_ctx = new_task_ctx(batch_size);
let left = build_left_table();
let right = build_right_table();
let filter = prepare_join_filter();
let (columns, batches, metrics) = multi_partitioned_join_collect(
left,
right,
&JoinType::RightAnti,
Some(filter),
task_ctx,
)
.await?;
assert_eq!(columns, vec!["a2", "b2", "c2"]);
allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+-----+
| a2 | b2 | c2 |
+----+----+-----+
| 10 | 10 | 100 |
| 12 | 10 | 40 |
+----+----+-----+
"));
assert_join_metrics!(metrics, 2);
Ok(())
}
#[rstest]
#[tokio::test]
async fn join_left_mark_with_filter(
#[values(1, 2, 16)] batch_size: usize,
) -> Result<()> {
let task_ctx = new_task_ctx(batch_size);
let left = build_left_table();
let right = build_right_table();
let filter = prepare_join_filter();
let (columns, batches, metrics) = multi_partitioned_join_collect(
left,
right,
&JoinType::LeftMark,
Some(filter),
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 |
+----+----+-----+-------+
| 11 | 8 | 110 | false |
| 5 | 5 | 50 | true |
| 9 | 8 | 90 | false |
+----+----+-----+-------+
"));
assert_join_metrics!(metrics, 3);
Ok(())
}
#[rstest]
#[tokio::test]
async fn join_right_mark_with_filter(
#[values(1, 2, 16)] batch_size: usize,
) -> Result<()> {
let task_ctx = new_task_ctx(batch_size);
let left = build_left_table();
let right = build_right_table();
let filter = prepare_join_filter();
let (columns, batches, metrics) = multi_partitioned_join_collect(
left,
right,
&JoinType::RightMark,
Some(filter),
task_ctx,
)
.await?;
assert_eq!(columns, vec!["a2", "b2", "c2", "mark"]);
allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+-----+-------+
| a2 | b2 | c2 | mark |
+----+----+-----+-------+
| 10 | 10 | 100 | false |
| 12 | 10 | 40 | false |
| 2 | 2 | 80 | true |
+----+----+-----+-------+
"));
assert_join_metrics!(metrics, 3);
Ok(())
}
#[tokio::test]
async fn test_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]),
None,
Vec::new(),
);
let right = build_table(
("a2", &vec![10, 11]),
("b2", &vec![12, 13]),
("c2", &vec![14, 15]),
None,
Vec::new(),
);
let filter = prepare_join_filter();
let fallback_join_types = vec![
JoinType::Inner,
JoinType::Right,
JoinType::RightSemi,
JoinType::RightAnti,
JoinType::RightMark,
JoinType::Full,
];
for join_type in &fallback_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 _result = multi_partitioned_join_collect(
Arc::clone(&left),
Arc::clone(&right),
join_type,
Some(filter.clone()),
task_ctx,
)
.await?;
}
Ok(())
}
fn columns(schema: &Schema) -> Vec<String> {
schema.fields().iter().map(|f| f.name().clone()).collect()
}
async fn join_collect(
left: Arc<dyn ExecutionPlan>,
right: Arc<dyn ExecutionPlan>,
join_type: &JoinType,
join_filter: Option<JoinFilter>,
context: Arc<TaskContext>,
) -> Result<(Vec<String>, Vec<RecordBatch>, MetricsSet)> {
let nested_loop_join =
NestedLoopJoinExec::try_new(left, right, join_filter, join_type, None)?;
let columns = columns(&nested_loop_join.schema());
let stream = nested_loop_join.execute(0, context)?;
let batches: Vec<RecordBatch> = common::collect(stream)
.await?
.into_iter()
.filter(|b| b.num_rows() > 0)
.collect();
let metrics = nested_loop_join.metrics().unwrap();
Ok((columns, batches, metrics))
}
fn task_ctx_with_memory_limit(
memory_limit: usize,
batch_size: usize,
) -> Result<Arc<TaskContext>> {
let runtime = RuntimeEnvBuilder::new()
.with_memory_limit(memory_limit, 1.0)
.build_arc()?;
let cfg = TaskContext::default()
.session_config()
.clone()
.with_batch_size(batch_size);
let task_ctx = TaskContext::default()
.with_runtime(runtime)
.with_session_config(cfg);
Ok(Arc::new(task_ctx))
}
#[tokio::test]
async fn test_nlj_memory_limited_inner_join() -> Result<()> {
let task_ctx = task_ctx_with_memory_limit(50, 16)?;
let left = build_left_table();
let right = build_right_table();
let filter = prepare_join_filter();
let (columns, batches, metrics) =
join_collect(left, right, &JoinType::Inner, Some(filter), task_ctx).await?;
assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b2", "c2"]);
assert!(
metrics.spill_count().unwrap_or(0) > 0,
"Expected spilling to occur under tight memory limit"
);
allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+----+----+----+----+
| a1 | b1 | c1 | a2 | b2 | c2 |
+----+----+----+----+----+----+
| 5 | 5 | 50 | 2 | 2 | 80 |
+----+----+----+----+----+----+
"));
Ok(())
}
#[tokio::test]
async fn test_nlj_memory_limited_left_join() -> Result<()> {
let task_ctx = task_ctx_with_memory_limit(50, 16)?;
let left = build_left_table();
let right = build_right_table();
let filter = prepare_join_filter();
let (columns, batches, metrics) =
join_collect(left, right, &JoinType::Left, Some(filter), task_ctx).await?;
assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b2", "c2"]);
assert!(
metrics.spill_count().unwrap_or(0) > 0,
"Expected spilling to occur under tight memory limit"
);
allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+-----+----+----+----+
| a1 | b1 | c1 | a2 | b2 | c2 |
+----+----+-----+----+----+----+
| 11 | 8 | 110 | | | |
| 5 | 5 | 50 | 2 | 2 | 80 |
| 9 | 8 | 90 | | | |
+----+----+-----+----+----+----+
"));
Ok(())
}
#[tokio::test]
async fn test_nlj_memory_limited_left_semi_join() -> Result<()> {
let task_ctx = task_ctx_with_memory_limit(50, 16)?;
let left = build_left_table();
let right = build_right_table();
let filter = prepare_join_filter();
let (columns, batches, metrics) =
join_collect(left, right, &JoinType::LeftSemi, Some(filter), task_ctx)
.await?;
assert_eq!(columns, vec!["a1", "b1", "c1"]);
assert!(
metrics.spill_count().unwrap_or(0) > 0,
"Expected spilling to occur under tight memory limit"
);
allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+----+
| a1 | b1 | c1 |
+----+----+----+
| 5 | 5 | 50 |
+----+----+----+
"));
Ok(())
}
#[tokio::test]
async fn test_nlj_memory_limited_left_anti_join() -> Result<()> {
let task_ctx = task_ctx_with_memory_limit(50, 16)?;
let left = build_left_table();
let right = build_right_table();
let filter = prepare_join_filter();
let (columns, batches, metrics) =
join_collect(left, right, &JoinType::LeftAnti, Some(filter), task_ctx)
.await?;
assert_eq!(columns, vec!["a1", "b1", "c1"]);
assert!(
metrics.spill_count().unwrap_or(0) > 0,
"Expected spilling to occur under tight memory limit"
);
allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+-----+
| a1 | b1 | c1 |
+----+----+-----+
| 11 | 8 | 110 |
| 9 | 8 | 90 |
+----+----+-----+
"));
Ok(())
}
#[tokio::test]
async fn test_nlj_memory_limited_left_mark_join() -> Result<()> {
let task_ctx = task_ctx_with_memory_limit(50, 16)?;
let left = build_left_table();
let right = build_right_table();
let filter = prepare_join_filter();
let (columns, batches, metrics) =
join_collect(left, right, &JoinType::LeftMark, Some(filter), task_ctx)
.await?;
assert_eq!(columns, vec!["a1", "b1", "c1", "mark"]);
assert!(
metrics.spill_count().unwrap_or(0) > 0,
"Expected spilling to occur under tight memory limit"
);
allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+-----+-------+
| a1 | b1 | c1 | mark |
+----+----+-----+-------+
| 11 | 8 | 110 | false |
| 5 | 5 | 50 | true |
| 9 | 8 | 90 | false |
+----+----+-----+-------+
"));
Ok(())
}
#[tokio::test]
async fn test_nlj_fits_in_memory_no_spill() -> Result<()> {
let task_ctx = task_ctx_with_memory_limit(10_000_000, 16)?;
let left = build_left_table();
let right = build_right_table();
let filter = prepare_join_filter();
let (columns, batches, metrics) =
join_collect(left, right, &JoinType::Inner, Some(filter), task_ctx).await?;
assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b2", "c2"]);
assert_eq!(
metrics.spill_count().unwrap_or(0),
0,
"Expected no spilling with generous memory limit"
);
allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+----+----+----+----+
| a1 | b1 | c1 | a2 | b2 | c2 |
+----+----+----+----+----+----+
| 5 | 5 | 50 | 2 | 2 | 80 |
+----+----+----+----+----+----+
"));
Ok(())
}
#[tokio::test]
async fn test_nlj_memory_limited_empty_inputs() -> Result<()> {
let task_ctx = task_ctx_with_memory_limit(50, 16)?;
let empty_left = build_table(
("a1", &vec![]),
("b1", &vec![]),
("c1", &vec![]),
None,
Vec::new(),
);
let right = build_right_table();
let filter = prepare_join_filter();
let (_columns, batches, _metrics) =
join_collect(empty_left, right, &JoinType::Inner, Some(filter), task_ctx)
.await?;
assert!(batches.is_empty() || batches.iter().all(|b| b.num_rows() == 0));
let task_ctx2 = task_ctx_with_memory_limit(50, 16)?;
let left = build_left_table();
let empty_right = build_table(
("a2", &vec![]),
("b2", &vec![]),
("c2", &vec![]),
None,
Vec::new(),
);
let filter2 = prepare_join_filter();
let (_columns, batches, _metrics) = join_collect(
left,
empty_right,
&JoinType::Inner,
Some(filter2),
task_ctx2,
)
.await?;
assert!(batches.is_empty() || batches.iter().all(|b| b.num_rows() == 0));
Ok(())
}
#[tokio::test]
async fn test_nlj_memory_limited_no_disk_falls_back_to_oom() -> Result<()> {
use datafusion_execution::disk_manager::{DiskManagerBuilder, DiskManagerMode};
let runtime = RuntimeEnvBuilder::new()
.with_memory_limit(100, 1.0)
.with_disk_manager_builder(
DiskManagerBuilder::default().with_mode(DiskManagerMode::Disabled),
)
.build_arc()?;
let task_ctx = Arc::new(TaskContext::default().with_runtime(runtime));
let left = build_left_table();
let right = build_right_table();
let filter = prepare_join_filter();
let err = join_collect(left, right, &JoinType::Inner, Some(filter), task_ctx)
.await
.unwrap_err();
assert_contains!(err.to_string(), "Resources exhausted");
Ok(())
}
#[tokio::test]
async fn test_nlj_memory_limited_right_join() -> Result<()> {
let task_ctx = task_ctx_with_memory_limit(50, 16)?;
let left = build_left_table();
let right = build_right_table();
let filter = prepare_join_filter();
let (columns, batches, metrics) =
join_collect(left, right, &JoinType::Right, Some(filter), task_ctx).await?;
assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b2", "c2"]);
assert!(
metrics.spill_count().unwrap_or(0) > 0,
"Expected spilling to occur under tight memory limit"
);
allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+----+----+----+-----+
| a1 | b1 | c1 | a2 | b2 | c2 |
+----+----+----+----+----+-----+
| | | | 10 | 10 | 100 |
| | | | 12 | 10 | 40 |
| 5 | 5 | 50 | 2 | 2 | 80 |
+----+----+----+----+----+-----+
"));
Ok(())
}
#[tokio::test]
async fn test_nlj_memory_limited_full_join() -> Result<()> {
let task_ctx = task_ctx_with_memory_limit(50, 16)?;
let left = build_left_table();
let right = build_right_table();
let filter = prepare_join_filter();
let (columns, batches, metrics) =
join_collect(left, right, &JoinType::Full, Some(filter), task_ctx).await?;
assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b2", "c2"]);
assert!(
metrics.spill_count().unwrap_or(0) > 0,
"Expected spilling to occur under tight memory limit"
);
allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+-----+----+----+-----+
| a1 | b1 | c1 | a2 | b2 | c2 |
+----+----+-----+----+----+-----+
| | | | 10 | 10 | 100 |
| | | | 12 | 10 | 40 |
| 11 | 8 | 110 | | | |
| 5 | 5 | 50 | 2 | 2 | 80 |
| 9 | 8 | 90 | | | |
+----+----+-----+----+----+-----+
"));
Ok(())
}
#[tokio::test]
async fn test_nlj_memory_limited_right_semi_join() -> Result<()> {
let task_ctx = task_ctx_with_memory_limit(50, 16)?;
let left = build_left_table();
let right = build_right_table();
let filter = prepare_join_filter();
let (columns, batches, metrics) =
join_collect(left, right, &JoinType::RightSemi, Some(filter), task_ctx)
.await?;
assert_eq!(columns, vec!["a2", "b2", "c2"]);
assert!(
metrics.spill_count().unwrap_or(0) > 0,
"Expected spilling to occur under tight memory limit"
);
allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+----+
| a2 | b2 | c2 |
+----+----+----+
| 2 | 2 | 80 |
+----+----+----+
"));
Ok(())
}
#[tokio::test]
async fn test_nlj_memory_limited_right_anti_join() -> Result<()> {
let task_ctx = task_ctx_with_memory_limit(50, 16)?;
let left = build_left_table();
let right = build_right_table();
let filter = prepare_join_filter();
let (columns, batches, metrics) =
join_collect(left, right, &JoinType::RightAnti, Some(filter), task_ctx)
.await?;
assert_eq!(columns, vec!["a2", "b2", "c2"]);
assert!(
metrics.spill_count().unwrap_or(0) > 0,
"Expected spilling to occur under tight memory limit"
);
allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+-----+
| a2 | b2 | c2 |
+----+----+-----+
| 10 | 10 | 100 |
| 12 | 10 | 40 |
+----+----+-----+
"));
Ok(())
}
#[tokio::test]
async fn test_nlj_memory_limited_right_mark_join() -> Result<()> {
let task_ctx = task_ctx_with_memory_limit(50, 16)?;
let left = build_left_table();
let right = build_right_table();
let filter = prepare_join_filter();
let (columns, batches, metrics) =
join_collect(left, right, &JoinType::RightMark, Some(filter), task_ctx)
.await?;
assert_eq!(columns, vec!["a2", "b2", "c2", "mark"]);
assert!(
metrics.spill_count().unwrap_or(0) > 0,
"Expected spilling to occur under tight memory limit"
);
allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+-----+-------+
| a2 | b2 | c2 | mark |
+----+----+-----+-------+
| 10 | 10 | 100 | false |
| 12 | 10 | 40 | false |
| 2 | 2 | 80 | true |
+----+----+-----+-------+
"));
Ok(())
}
fn build_right_table_one_batch_per_row() -> Arc<dyn ExecutionPlan> {
build_table(
("a2", &vec![12, 2, 10]),
("b2", &vec![10, 2, 10]),
("c2", &vec![40, 80, 100]),
Some(1),
Vec::new(),
)
}
fn build_left_table_multi_chunk() -> Arc<dyn ExecutionPlan> {
build_table(
("a1", &vec![5, 9, 11, 13, 15, 17, 19, 21]),
("b1", &vec![5, 8, 8, 8, 8, 8, 8, 8]),
("c1", &vec![50, 90, 110, 130, 150, 170, 190, 210]),
Some(1),
Vec::new(),
)
}
async fn multi_partition_memory_limited_join_collect(
left: Arc<dyn ExecutionPlan>,
right: Arc<dyn ExecutionPlan>,
join_type: &JoinType,
join_filter: Option<JoinFilter>,
context: Arc<TaskContext>,
) -> Result<(Vec<String>, Vec<RecordBatch>, MetricsSet)> {
let partition_count = 4;
let right = Arc::new(RepartitionExec::try_new(
right,
Partitioning::RoundRobinBatch(partition_count),
)?) as Arc<dyn ExecutionPlan>;
let nested_loop_join =
NestedLoopJoinExec::try_new(left, right, join_filter, join_type, None)?;
let columns = columns(&nested_loop_join.schema());
let mut handles = vec![];
for i in 0..partition_count {
let stream = nested_loop_join.execute(i, Arc::clone(&context))?;
handles.push(SpawnedTask::spawn(
async move { common::collect(stream).await },
));
}
let mut batches = vec![];
for handle in handles {
batches.extend(handle.join().await.expect("partition task panicked")?);
}
batches.retain(|b| b.num_rows() > 0);
let metrics = nested_loop_join.metrics().unwrap();
Ok((columns, batches, metrics))
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_nlj_memory_limited_multi_partition_left_join() -> Result<()> {
let task_ctx = task_ctx_with_memory_limit(50, 16)?;
let left = build_left_table_multi_chunk();
let right = build_right_table_one_batch_per_row();
let filter = prepare_join_filter();
let (columns, batches, metrics) = multi_partition_memory_limited_join_collect(
left,
right,
&JoinType::Left,
Some(filter),
task_ctx,
)
.await?;
assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b2", "c2"]);
assert!(
metrics.spill_count().unwrap_or(0) > 0,
"Expected spilling under tight memory limit"
);
allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+-----+----+----+----+
| a1 | b1 | c1 | a2 | b2 | c2 |
+----+----+-----+----+----+----+
| 11 | 8 | 110 | | | |
| 13 | 8 | 130 | | | |
| 15 | 8 | 150 | | | |
| 17 | 8 | 170 | | | |
| 19 | 8 | 190 | | | |
| 21 | 8 | 210 | | | |
| 5 | 5 | 50 | 2 | 2 | 80 |
| 9 | 8 | 90 | | | |
+----+----+-----+----+----+----+
"));
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_nlj_memory_limited_multi_partition_full_join() -> Result<()> {
let task_ctx = task_ctx_with_memory_limit(50, 16)?;
let left = build_left_table_multi_chunk();
let right = build_right_table_one_batch_per_row();
let filter = prepare_join_filter();
let (columns, batches, metrics) = multi_partition_memory_limited_join_collect(
left,
right,
&JoinType::Full,
Some(filter),
task_ctx,
)
.await?;
assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b2", "c2"]);
assert!(
metrics.spill_count().unwrap_or(0) > 0,
"Expected spilling under tight memory limit"
);
allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+-----+----+----+-----+
| a1 | b1 | c1 | a2 | b2 | c2 |
+----+----+-----+----+----+-----+
| | | | 10 | 10 | 100 |
| | | | 12 | 10 | 40 |
| 11 | 8 | 110 | | | |
| 13 | 8 | 130 | | | |
| 15 | 8 | 150 | | | |
| 17 | 8 | 170 | | | |
| 19 | 8 | 190 | | | |
| 21 | 8 | 210 | | | |
| 5 | 5 | 50 | 2 | 2 | 80 |
| 9 | 8 | 90 | | | |
+----+----+-----+----+----+-----+
"));
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_nlj_memory_limited_multi_partition_left_semi_join() -> Result<()> {
let task_ctx = task_ctx_with_memory_limit(50, 16)?;
let left = build_left_table_multi_chunk();
let right = build_table(
("a2", &vec![2, 3, 10]),
("b2", &vec![2, 2, 10]),
("c2", &vec![80, 70, 100]),
Some(1),
Vec::new(),
);
let filter = prepare_join_filter();
let (columns, batches, metrics) = multi_partition_memory_limited_join_collect(
left,
right,
&JoinType::LeftSemi,
Some(filter),
task_ctx,
)
.await?;
assert_eq!(columns, vec!["a1", "b1", "c1"]);
assert!(
metrics.spill_count().unwrap_or(0) > 0,
"Expected spilling under tight memory limit"
);
allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+----+
| a1 | b1 | c1 |
+----+----+----+
| 5 | 5 | 50 |
+----+----+----+
"));
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_nlj_memory_limited_multi_partition_left_anti_join() -> Result<()> {
let task_ctx = task_ctx_with_memory_limit(50, 16)?;
let left = build_left_table_multi_chunk();
let right = build_right_table_one_batch_per_row();
let filter = prepare_join_filter();
let (columns, batches, metrics) = multi_partition_memory_limited_join_collect(
left,
right,
&JoinType::LeftAnti,
Some(filter),
task_ctx,
)
.await?;
assert_eq!(columns, vec!["a1", "b1", "c1"]);
assert!(
metrics.spill_count().unwrap_or(0) > 0,
"Expected spilling under tight memory limit"
);
allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+-----+
| a1 | b1 | c1 |
+----+----+-----+
| 11 | 8 | 110 |
| 13 | 8 | 130 |
| 15 | 8 | 150 |
| 17 | 8 | 170 |
| 19 | 8 | 190 |
| 21 | 8 | 210 |
| 9 | 8 | 90 |
+----+----+-----+
"));
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_nlj_memory_limited_multi_partition_left_mark_join() -> Result<()> {
let task_ctx = task_ctx_with_memory_limit(50, 16)?;
let left = build_left_table_multi_chunk();
let right = build_right_table_one_batch_per_row();
let filter = prepare_join_filter();
let (columns, batches, metrics) = multi_partition_memory_limited_join_collect(
left,
right,
&JoinType::LeftMark,
Some(filter),
task_ctx,
)
.await?;
assert_eq!(columns, vec!["a1", "b1", "c1", "mark"]);
assert!(
metrics.spill_count().unwrap_or(0) > 0,
"Expected spilling under tight memory limit"
);
allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+-----+-------+
| a1 | b1 | c1 | mark |
+----+----+-----+-------+
| 11 | 8 | 110 | false |
| 13 | 8 | 130 | false |
| 15 | 8 | 150 | false |
| 17 | 8 | 170 | false |
| 19 | 8 | 190 | false |
| 21 | 8 | 210 | false |
| 5 | 5 | 50 | true |
| 9 | 8 | 90 | false |
+----+----+-----+-------+
"));
Ok(())
}
async fn assert_memory_released_after_completion(join_type: JoinType) -> Result<()> {
let runtime = RuntimeEnvBuilder::new()
.with_memory_limit(50, 1.0)
.build_arc()?;
let pool = Arc::clone(&runtime.memory_pool);
let cfg = TaskContext::default()
.session_config()
.clone()
.with_batch_size(16);
let task_ctx = Arc::new(
TaskContext::default()
.with_runtime(runtime)
.with_session_config(cfg),
);
let partition_count = 4;
let right = Arc::new(RepartitionExec::try_new(
build_right_table_one_batch_per_row(),
Partitioning::RoundRobinBatch(partition_count),
)?) as Arc<dyn ExecutionPlan>;
let nested_loop_join = Arc::new(NestedLoopJoinExec::try_new(
build_left_table_multi_chunk(),
right,
Some(prepare_join_filter()),
&join_type,
None,
)?);
let mut handles = vec![];
for i in 0..partition_count {
let stream = nested_loop_join.execute(i, Arc::clone(&task_ctx))?;
handles.push(SpawnedTask::spawn(
async move { common::collect(stream).await },
));
}
for handle in handles {
handle.join().await.expect("partition task panicked")?;
}
assert!(
nested_loop_join
.metrics()
.unwrap()
.spill_count()
.unwrap_or(0)
> 0,
"{join_type}: expected spilling under a tight memory limit"
);
assert_eq!(
pool.reserved(),
0,
"{join_type}: memory is still reserved after every partition finished"
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_nlj_memory_limited_releases_memory_left_join() -> Result<()> {
assert_memory_released_after_completion(JoinType::Left).await
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_nlj_memory_limited_releases_memory_full_join() -> Result<()> {
assert_memory_released_after_completion(JoinType::Full).await
}
const LEFT_EMITTING_JOIN_TYPES: [JoinType; 5] = [
JoinType::Left,
JoinType::LeftSemi,
JoinType::LeftAnti,
JoinType::LeftMark,
JoinType::Full,
];
fn count_final_left_rows(join_type: JoinType, batches: &[RecordBatch]) -> usize {
batches
.iter()
.map(|batch| match join_type {
JoinType::Left | JoinType::Full => {
let left = batch.column(0);
let right = batch.column(3);
(0..batch.num_rows())
.filter(|&i| left.is_valid(i) && right.is_null(i))
.count()
}
_ => batch.num_rows(),
})
.sum()
}
fn dropped_partition_test_plan(
right: Arc<dyn ExecutionPlan>,
join_type: JoinType,
) -> Result<(Arc<NestedLoopJoinExec>, Arc<TaskContext>)> {
let task_ctx = task_ctx_with_memory_limit(50, 1)?;
let right = Arc::new(RepartitionExec::try_new(
right,
Partitioning::RoundRobinBatch(2),
)?) as Arc<dyn ExecutionPlan>;
let plan = Arc::new(NestedLoopJoinExec::try_new(
build_left_table_multi_chunk(),
right,
Some(prepare_join_filter()),
&join_type,
None,
)?);
Ok((plan, task_ctx))
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_nlj_memory_limited_dropped_partition_does_not_stall_peers() -> Result<()>
{
let (plan, task_ctx) = dropped_partition_test_plan(
build_right_table_one_batch_per_row(),
JoinType::Left,
)?;
let mut handles = vec![];
for i in 0..2 {
let mut stream = plan.execute(i, Arc::clone(&task_ctx))?;
handles.push(SpawnedTask::spawn(async move {
while let Some(batch) = stream.next().await {
let batch = batch?;
if batch.num_rows() > 0 {
return Ok(Some(batch));
}
}
Ok::<_, DataFusionError>(None)
}));
}
let mut batches = vec![];
for handle in handles {
let batch = tokio::time::timeout(Duration::from_secs(30), handle.join())
.await
.expect("a partition stalled after its peer was dropped")
.expect("partition task panicked")?;
batches.extend(batch);
}
assert!(
plan.metrics().unwrap().spill_count().unwrap_or(0) > 0,
"Expected spilling under tight memory limit"
);
allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+----+----+----+----+
| a1 | b1 | c1 | a2 | b2 | c2 |
+----+----+----+----+----+----+
| 5 | 5 | 50 | 2 | 2 | 80 |
+----+----+----+----+----+----+
"));
assert_eq!(
task_ctx.memory_pool().reserved(),
0,
"a dropped partition must not strand the chunk's or the bitmap's memory"
);
drop(plan);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_nlj_memory_limited_partition_dropped_while_waiting_for_peers()
-> Result<()> {
for join_type in LEFT_EMITTING_JOIN_TYPES {
assert_partition_dropped_while_waiting_for_peers(join_type).await?;
}
Ok(())
}
async fn assert_partition_dropped_while_waiting_for_peers(
join_type: JoinType,
) -> Result<()> {
let right = build_table(
("a2", &vec![12, 10]),
("b2", &vec![10, 10]),
("c2", &vec![40, 100]),
Some(1),
Vec::new(),
);
let (plan, task_ctx) = dropped_partition_test_plan(right, join_type)?;
let mut waiting = plan.execute(0, Arc::clone(&task_ctx))?;
let survivor = plan.execute(1, Arc::clone(&task_ctx))?;
tokio::time::timeout(Duration::from_secs(30), async {
while plan.left_chunk_barrier.inner.lock().finished == 0 {
assert!(
futures::poll!(waiting.next()).is_pending(),
"the partition cannot get past the first chunk on its own"
);
tokio::time::sleep(Duration::from_millis(1)).await;
}
})
.await
.expect("the partition never finished the first chunk");
drop(waiting);
{
let barrier = plan.left_chunk_barrier.inner.lock();
assert_eq!(
(barrier.chunk_index, barrier.live, barrier.finished),
(0, 1, 0)
);
}
let batches =
tokio::time::timeout(Duration::from_secs(30), common::collect(survivor))
.await
.expect("the remaining partition stalled")?;
let expected_rows = usize::from(join_type == JoinType::Full);
assert_eq!(
batches.iter().map(RecordBatch::num_rows).sum::<usize>(),
expected_rows,
"{join_type}"
);
assert_eq!(plan.left_chunk_barrier.inner.lock().chunk_index, 8);
assert_eq!(task_ctx.memory_pool().reserved(), 0, "{join_type}");
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_nlj_memory_limited_partition_dropped_while_loading() -> Result<()> {
let (plan, task_ctx) = dropped_partition_test_plan(
build_right_table_one_batch_per_row(),
JoinType::Left,
)?;
let mut loading = plan.execute(0, Arc::clone(&task_ctx))?;
let survivor = plan.execute(1, Arc::clone(&task_ctx))?;
tokio::time::timeout(Duration::from_secs(30), async {
while plan.left_chunk_barrier.inner.lock().chunk.is_none() {
let _ = futures::poll!(loading.next());
tokio::time::sleep(Duration::from_millis(1)).await;
}
})
.await
.expect("the partition never asked for the first chunk");
drop(loading);
tokio::time::timeout(Duration::from_secs(30), common::collect(survivor))
.await
.expect("the remaining partition stalled")?;
assert_eq!(plan.left_chunk_barrier.inner.lock().chunk_index, 8);
assert_eq!(task_ctx.memory_pool().reserved(), 0);
Ok(())
}
struct FailFinalPassSpillFile {
inner: Arc<dyn SpillFile>,
reads: AtomicUsize,
}
impl SpillFile for FailFinalPassSpillFile {
fn path(&self) -> Option<&std::path::Path> {
self.inner.path()
}
fn size(&self) -> Option<u64> {
self.inner.size()
}
fn read_stream(
&self,
) -> Result<Pin<Box<dyn Stream<Item = Result<Bytes>> + Send>>> {
if self.reads.fetch_add(1, Ordering::Relaxed) > 0 {
return internal_err!("final pass cannot be opened");
}
self.inner.read_stream()
}
fn open_writer(&self) -> Result<Box<dyn SpillWriter>> {
self.inner.open_writer()
}
}
#[derive(Debug)]
struct FailFinalPassTempFileFactory {
inner: Arc<DiskManager>,
}
impl TempFileFactory for FailFinalPassTempFileFactory {
fn create_temp_file(&self, description: &str) -> Result<Arc<dyn SpillFile>> {
let file = self.inner.create_tmp_file(description)?;
if description != "NestedLoopJoin left spill" {
return Ok(file);
}
Ok(Arc::new(FailFinalPassSpillFile {
inner: file,
reads: AtomicUsize::new(0),
}))
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_nlj_memory_limited_final_pass_open_error_releases_bitmap() -> Result<()>
{
let inner = Arc::new(
DiskManagerBuilder::default()
.with_mode(DiskManagerMode::OsTmpDirectory)
.build()?,
);
let runtime = RuntimeEnvBuilder::new()
.with_memory_limit(50, 1.0)
.with_disk_manager_builder(DiskManagerBuilder::default().with_mode(
DiskManagerMode::Custom(Arc::new(FailFinalPassTempFileFactory { inner })),
))
.build_arc()?;
let cfg = TaskContext::default()
.session_config()
.clone()
.with_batch_size(1);
let task_ctx = Arc::new(
TaskContext::default()
.with_runtime(runtime)
.with_session_config(cfg),
);
let right = Arc::new(RepartitionExec::try_new(
build_right_table_one_batch_per_row(),
Partitioning::RoundRobinBatch(2),
)?) as Arc<dyn ExecutionPlan>;
let plan = Arc::new(NestedLoopJoinExec::try_new(
build_left_table_multi_chunk(),
right,
Some(prepare_join_filter()),
&JoinType::Left,
None,
)?);
let streams = (0..2)
.map(|i| plan.execute(i, Arc::clone(&task_ctx)))
.collect::<Result<Vec<_>>>()?;
let results = tokio::time::timeout(
Duration::from_secs(30),
futures::future::join_all(streams.into_iter().map(common::collect)),
)
.await
.expect("the join stalled");
let err = results
.into_iter()
.find_map(Result::err)
.expect("the emitter fails to open the final pass");
assert_contains!(err.to_string(), "final pass cannot be opened");
assert_eq!(task_ctx.memory_pool().reserved(), 0);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_nlj_memory_limited_unpolled_partition_dropped() -> Result<()> {
for join_type in LEFT_EMITTING_JOIN_TYPES {
for after_spill in [false, true] {
let (plan, task_ctx) = dropped_partition_test_plan(
build_right_table_one_batch_per_row(),
join_type,
)?;
let unpolled = plan.execute(0, Arc::clone(&task_ctx))?;
let mut survivor = plan.execute(1, Arc::clone(&task_ctx))?;
let mut batches = vec![];
if after_spill {
tokio::time::timeout(Duration::from_secs(30), async {
while plan.left_chunk_barrier.inner.lock().finished == 0 {
if let Poll::Ready(Some(batch)) =
futures::poll!(survivor.next())
{
batches.push(batch?);
}
tokio::time::sleep(Duration::from_millis(1)).await;
}
Ok::<_, DataFusionError>(())
})
.await
.expect("the survivor never finished the first chunk")?;
assert!(plan.left_chunk_barrier.inner.lock().left_spill.is_some());
}
drop(unpolled);
batches.extend(
tokio::time::timeout(
Duration::from_secs(30),
common::collect(survivor),
)
.await
.expect("the remaining partition stalled")?,
);
assert!(
plan.metrics().unwrap().spill_count().unwrap_or(0) > 0,
"{join_type}: expected spilling under tight memory limit"
);
assert_eq!(
count_final_left_rows(join_type, &batches),
0,
"{join_type} after_spill={after_spill}"
);
assert_eq!(
task_ctx.memory_pool().reserved(),
0,
"{join_type} after_spill={after_spill}: memory still reserved \
while the plan is alive"
);
}
}
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_nlj_memory_limited_full_join_dropped_during_right_replay() -> Result<()>
{
let (plan, task_ctx) = dropped_partition_test_plan(
build_right_table_one_batch_per_row(),
JoinType::Full,
)?;
let mut streams = vec![
plan.execute(0, Arc::clone(&task_ctx))?,
plan.execute(1, Arc::clone(&task_ctx))?,
];
let replaying = tokio::time::timeout(Duration::from_secs(30), async {
loop {
for (i, stream) in streams.iter_mut().enumerate() {
if let Poll::Ready(Some(batch)) = futures::poll!(stream.next()) {
let batch = batch?;
if batch.num_rows() > 0 && batch.column(0).null_count() > 0 {
return Ok::<_, DataFusionError>(i);
}
}
}
tokio::time::sleep(Duration::from_millis(1)).await;
}
})
.await
.expect("no partition reached the right replay")?;
let left_spill = Arc::clone(
plan.left_chunk_barrier
.inner
.lock()
.left_spill
.as_ref()
.expect("the left side spilled"),
);
drop(streams.remove(replaying));
let survivor = streams.pop().unwrap();
let batches =
tokio::time::timeout(Duration::from_secs(30), common::collect(survivor))
.await
.expect("the remaining partition stalled")?;
assert_eq!(
count_final_left_rows(JoinType::Full, &batches),
0,
"the replaying partition must not have reported before it was dropped"
);
drop(left_spill);
assert_eq!(task_ctx.memory_pool().reserved(), 0);
Ok(())
}
fn task_ctx_with_memory_limit_no_coordinated_fallback(
memory_limit: usize,
batch_size: usize,
) -> Result<Arc<TaskContext>> {
let runtime = RuntimeEnvBuilder::new()
.with_memory_limit(memory_limit, 1.0)
.build_arc()?;
let mut cfg = TaskContext::default()
.session_config()
.clone()
.with_batch_size(batch_size);
cfg.options_mut().execution.enable_nlj_coordinated_fallback = false;
let task_ctx = TaskContext::default()
.with_runtime(runtime)
.with_session_config(cfg);
Ok(Arc::new(task_ctx))
}
async fn multi_partition_join_collect_err(
left: Arc<dyn ExecutionPlan>,
right: Arc<dyn ExecutionPlan>,
join_type: &JoinType,
join_filter: Option<JoinFilter>,
context: Arc<TaskContext>,
) -> Result<()> {
let partition_count = 4;
let right = Arc::new(RepartitionExec::try_new(
right,
Partitioning::RoundRobinBatch(partition_count),
)?) as Arc<dyn ExecutionPlan>;
let nested_loop_join = Arc::new(NestedLoopJoinExec::try_new(
left,
right,
join_filter,
join_type,
None,
)?);
let mut handles = vec![];
for i in 0..partition_count {
let stream = nested_loop_join.execute(i, Arc::clone(&context))?;
handles.push(SpawnedTask::spawn(
async move { common::collect(stream).await },
));
}
for handle in handles {
handle.join().await.expect("partition task panicked")?;
}
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_nlj_memory_limited_fallback_disabled_left_join_oom() -> Result<()> {
let task_ctx = task_ctx_with_memory_limit_no_coordinated_fallback(50, 16)?;
let left = build_left_table_multi_chunk();
let right = build_right_table_one_batch_per_row();
let filter = prepare_join_filter();
let err = multi_partition_join_collect_err(
left,
right,
&JoinType::Left,
Some(filter),
task_ctx,
)
.await
.unwrap_err();
assert_contains!(err.to_string(), "Resources exhausted");
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_nlj_memory_limited_fallback_disabled_full_join_oom() -> Result<()> {
let task_ctx = task_ctx_with_memory_limit_no_coordinated_fallback(50, 16)?;
let left = build_left_table_multi_chunk();
let right = build_right_table_one_batch_per_row();
let filter = prepare_join_filter();
let err = multi_partition_join_collect_err(
left,
right,
&JoinType::Full,
Some(filter),
task_ctx,
)
.await
.unwrap_err();
assert_contains!(err.to_string(), "Resources exhausted");
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_nlj_memory_limited_fallback_disabled_right_join_still_spills()
-> Result<()> {
for join_type in [JoinType::Right, JoinType::Inner] {
let task_ctx = task_ctx_with_memory_limit_no_coordinated_fallback(50, 16)?;
let (_columns, _batches, metrics) =
multi_partition_memory_limited_join_collect(
build_left_table_multi_chunk(),
build_right_table_one_batch_per_row(),
&join_type,
Some(prepare_join_filter()),
task_ctx,
)
.await?;
assert!(
metrics.spill_count().unwrap_or(0) > 0,
"{join_type}: the opt-out must not disable the spill fallback for \
a join type that does not need left-bitmap coordination"
);
}
Ok(())
}
}