use std::sync::Arc;
use std::task::Poll;
use crate::coalesce::{LimitedBatchCoalescer, PushBatchStatus};
use crate::joins::Map;
use crate::joins::PartitionMode;
use crate::joins::hash_join::exec::JoinLeftData;
use crate::joins::hash_join::not_in::NotInProbe;
use crate::joins::hash_join::shared_bounds::{
PartitionBounds, PartitionBuildData, SharedBuildAccumulator,
};
use crate::joins::join_hash_map::ProbeOffset;
use crate::joins::join_hash_map::ProbeOffset::AtRow;
use crate::joins::probe_completion::{Completion, ProbeSideSummary};
use crate::joins::utils::{
JoinKeyComparator, OnceFut, equal_rows_arr_with_normalized_left, matchable_join_keys,
};
use crate::stream::EmptyRecordBatchStream;
use crate::{
RecordBatchStream, SendableRecordBatchStream, handle_state,
hash_utils::create_hashes,
joins::utils::{
BuildProbeJoinMetrics, ColumnIndex, JoinFilter, JoinHashMapType,
StatefulStreamResult, adjust_indices_by_join_type, apply_join_filter_to_indices,
build_batch_empty_build_side, build_batch_from_indices,
need_produce_result_in_final,
},
};
use arrow::array::{Array, ArrayRef, UInt32Array, UInt64Array};
use arrow::buffer::{BooleanBuffer, NullBuffer};
use arrow::datatypes::{Schema, SchemaRef};
use arrow::record_batch::RecordBatch;
use datafusion_common::{
JoinSide, JoinType, NullEquality, Result, internal_datafusion_err, internal_err,
};
use datafusion_physical_expr::PhysicalExprRef;
use datafusion_common::hash_utils::RandomState;
use datafusion_physical_expr_common::utils::evaluate_expressions_to_arrays;
use futures::{Stream, StreamExt, ready};
pub(super) enum BuildSide {
Initial(BuildSideInitialState),
Ready(BuildSideReadyState),
}
pub(super) struct BuildSideInitialState {
pub(super) left_fut: OnceFut<JoinLeftData>,
}
pub(super) struct BuildSideReadyState {
left_data: Arc<JoinLeftData>,
}
impl BuildSide {
fn try_as_initial_mut(&mut self) -> Result<&mut BuildSideInitialState> {
match self {
BuildSide::Initial(state) => Ok(state),
_ => internal_err!("Expected build side in initial state"),
}
}
fn try_as_ready(&self) -> Result<&BuildSideReadyState> {
match self {
BuildSide::Ready(state) => Ok(state),
_ => internal_err!("Expected build side in ready state"),
}
}
fn try_as_ready_mut(&mut self) -> Result<&mut BuildSideReadyState> {
match self {
BuildSide::Ready(state) => Ok(state),
_ => internal_err!("Expected build side in ready state"),
}
}
}
#[derive(Debug)]
pub(super) enum HashJoinStreamState {
WaitBuildSide,
WaitPartitionBoundsReport,
FetchProbeBatch,
ProcessProbeBatch(ProcessProbeBatchState),
ExhaustedProbeSide,
EmitUnmatchedBuildRows(EmitUnmatchedBuildRowsState),
Completed,
}
impl HashJoinStreamState {
fn try_as_process_probe_batch_mut(&mut self) -> Result<&mut ProcessProbeBatchState> {
match self {
HashJoinStreamState::ProcessProbeBatch(state) => Ok(state),
_ => internal_err!("Expected hash join stream in ProcessProbeBatch state"),
}
}
fn try_as_emit_unmatched_build_rows_mut(
&mut self,
) -> Result<&mut EmitUnmatchedBuildRowsState> {
match self {
HashJoinStreamState::EmitUnmatchedBuildRows(state) => Ok(state),
_ => {
internal_err!("Expected hash join stream in EmitUnmatchedBuildRows state")
}
}
}
}
#[derive(Debug)]
pub(super) struct ProcessProbeBatchState {
batch: RecordBatch,
values: Vec<ArrayRef>,
valid_keys: Option<NullBuffer>,
offset: ProbeOffset,
joined_probe_idx: Option<usize>,
matched_probe_idx: Option<u32>,
key_comparator: Option<JoinKeyComparator>,
}
impl ProcessProbeBatchState {
fn advance(&mut self, offset: ProbeOffset, joined_probe_idx: Option<usize>) {
self.offset = offset;
if joined_probe_idx.is_some() {
self.joined_probe_idx = joined_probe_idx;
}
}
fn count_new_matched_probe_rows(&mut self, right_indices: &UInt32Array) -> usize {
let values = right_indices.values();
let mut count = count_distinct_sorted_indices(right_indices);
if let (Some(&first), Some(&last)) = (values.first(), values.last()) {
if Some(first) == self.matched_probe_idx {
count -= 1;
}
self.matched_probe_idx = Some(last);
}
count
}
fn is_first_chunk(&self) -> bool {
self.offset == AtRow { row: 0 }
}
}
#[derive(Debug, Clone)]
pub(super) struct EmitUnmatchedBuildRowsState {
visited: BooleanBuffer,
cursor: usize,
probe_summary: ProbeSideSummary,
}
#[derive(Debug, PartialEq, Eq)]
enum BuildReportState {
NotReported,
Scheduled,
Delivered,
Canceled,
Finalized,
}
struct BuildReportHandle {
partition: usize,
mode: PartitionMode,
build_accumulator: Option<Arc<SharedBuildAccumulator>>,
waiter: Option<OnceFut<()>>,
state: BuildReportState,
}
impl BuildReportHandle {
fn new(
partition: usize,
mode: PartitionMode,
build_accumulator: Option<Arc<SharedBuildAccumulator>>,
) -> Self {
Self {
partition,
mode,
build_accumulator,
waiter: None,
state: BuildReportState::NotReported,
}
}
fn has_accumulator(&self) -> bool {
self.build_accumulator.is_some()
}
fn schedule(&mut self, build_data: PartitionBuildData) {
let Some(build_accumulator) = &self.build_accumulator else {
self.finalize();
return;
};
debug_assert!(matches!(self.state, BuildReportState::NotReported));
let acc = Arc::clone(build_accumulator);
self.waiter = Some(OnceFut::new(async move {
acc.report_build_data(build_data).await
}));
self.state = BuildReportState::Scheduled;
}
fn poll_delivery(&mut self, cx: &mut std::task::Context<'_>) -> Poll<Result<()>> {
if let Some(ref mut fut) = self.waiter {
ready!(fut.get_shared(cx))?;
if !matches!(self.state, BuildReportState::Delivered) {
debug_assert!(matches!(self.state, BuildReportState::Scheduled));
self.state = BuildReportState::Delivered;
}
}
Poll::Ready(Ok(()))
}
fn cancel_pending(&mut self) {
if matches!(
self.state,
BuildReportState::Delivered
| BuildReportState::Canceled
| BuildReportState::Finalized
) {
return;
}
if self.mode == PartitionMode::Partitioned
&& let Some(build_accumulator) = &self.build_accumulator
{
build_accumulator.report_canceled_partition(self.partition);
self.state = BuildReportState::Canceled;
} else {
self.finalize();
}
}
fn finalize(&mut self) {
self.state = BuildReportState::Finalized;
}
#[cfg(test)]
fn state(&self) -> &BuildReportState {
&self.state
}
}
impl Drop for BuildReportHandle {
fn drop(&mut self) {
self.cancel_pending();
}
}
pub(super) struct HashJoinStream {
partition: usize,
schema: Arc<Schema>,
on_right: Vec<PhysicalExprRef>,
filter: Option<JoinFilter>,
join_type: JoinType,
right: SendableRecordBatchStream,
random_state: RandomState,
join_metrics: BuildProbeJoinMetrics,
column_indices: Vec<ColumnIndex>,
null_equality: NullEquality,
state: HashJoinStreamState,
build_side: BuildSide,
batch_size: usize,
hashes_buffer: Vec<u64>,
probe_indices_buffer: Vec<u32>,
build_indices_buffer: Vec<u64>,
not_in: NotInProbe,
right_side_ordered: bool,
build_report: BuildReportHandle,
mode: PartitionMode,
output_buffer: LimitedBatchCoalescer,
}
impl RecordBatchStream for HashJoinStream {
fn schema(&self) -> SchemaRef {
Arc::clone(&self.schema)
}
}
#[expect(clippy::too_many_arguments)]
pub(super) fn lookup_join_hashmap(
build_hashmap: &dyn JoinHashMapType,
build_side_values: &[ArrayRef],
probe_side_values: &[ArrayRef],
null_equality: NullEquality,
hashes_buffer: &[u64],
valid_keys: Option<&NullBuffer>,
limit: usize,
offset: ProbeOffset,
probe_indices_buffer: &mut Vec<u32>,
build_indices_buffer: &mut Vec<u64>,
key_comparator: &mut Option<JoinKeyComparator>,
) -> Result<(UInt64Array, UInt32Array, Option<ProbeOffset>)> {
let next_offset = build_hashmap.get_matched_indices_with_limit_offset(
hashes_buffer,
valid_keys,
limit,
offset,
probe_indices_buffer,
build_indices_buffer,
);
let build_indices_unfiltered: UInt64Array =
std::mem::take(build_indices_buffer).into();
let probe_indices_unfiltered: UInt32Array =
std::mem::take(probe_indices_buffer).into();
let (build_indices, probe_indices) = equal_rows_arr_with_normalized_left(
&build_indices_unfiltered,
&probe_indices_unfiltered,
build_side_values,
probe_side_values,
null_equality,
key_comparator,
)?;
*build_indices_buffer = build_indices_unfiltered.into_parts().1.into();
*probe_indices_buffer = probe_indices_unfiltered.into_parts().1.into();
Ok((build_indices, probe_indices, next_offset))
}
#[inline]
fn count_distinct_sorted_indices(indices: &UInt32Array) -> usize {
if indices.is_empty() {
return 0;
}
debug_assert_eq!(indices.null_count(), 0);
let values_buf = indices.values();
let values = values_buf.as_ref();
let mut iter = values.iter();
let Some(&first) = iter.next() else {
return 0;
};
let mut count = 1usize;
let mut last = first;
for &value in iter {
if value != last {
last = value;
count += 1;
}
}
count
}
impl HashJoinStream {
#[expect(clippy::too_many_arguments)]
pub(super) fn new(
partition: usize,
schema: Arc<Schema>,
on_right: Vec<PhysicalExprRef>,
filter: Option<JoinFilter>,
join_type: JoinType,
right: SendableRecordBatchStream,
random_state: RandomState,
join_metrics: BuildProbeJoinMetrics,
column_indices: Vec<ColumnIndex>,
null_equality: NullEquality,
state: HashJoinStreamState,
build_side: BuildSide,
batch_size: usize,
hashes_buffer: Vec<u64>,
right_side_ordered: bool,
build_accumulator: Option<Arc<SharedBuildAccumulator>>,
mode: PartitionMode,
fetch: Option<usize>,
) -> Self {
let output_buffer =
LimitedBatchCoalescer::new(Arc::clone(&schema), batch_size, fetch);
Self {
partition,
schema,
on_right,
filter,
join_type,
right,
random_state,
join_metrics,
column_indices,
null_equality,
state,
build_side,
batch_size,
hashes_buffer,
probe_indices_buffer: Vec::with_capacity(batch_size),
build_indices_buffer: Vec::with_capacity(batch_size),
not_in: NotInProbe::default(),
right_side_ordered,
build_report: BuildReportHandle::new(partition, mode, build_accumulator),
mode,
output_buffer,
}
}
fn state_after_build_ready(
join_type: JoinType,
left_data: &JoinLeftData,
) -> HashJoinStreamState {
let build_empty = !left_data.has_build_rows();
let map_empty = !left_data.has_matchable_build_rows();
if (build_empty && join_type.empty_build_side_produces_empty_result())
|| (map_empty && join_type.empty_map_produces_empty_result())
{
HashJoinStreamState::Completed
} else {
HashJoinStreamState::FetchProbeBatch
}
}
fn transition_after_build_collected(
&mut self,
left_data: &Arc<JoinLeftData>,
) -> HashJoinStreamState {
if !self.build_report.has_accumulator() {
return Self::state_after_build_ready(self.join_type, left_data.as_ref());
}
let pushdown = left_data.membership().clone();
let bounds = left_data
.bounds()
.cloned()
.unwrap_or_else(|| PartitionBounds::new(vec![]));
let keys_have_null = left_data
.values()
.iter()
.any(|array| array.logical_null_count() > 0);
let build_data = match self.mode {
PartitionMode::Partitioned => PartitionBuildData::Partitioned {
partition_id: self.partition,
pushdown,
bounds,
keys_have_null,
},
PartitionMode::CollectLeft => PartitionBuildData::CollectLeft {
pushdown,
bounds,
keys_have_null,
},
PartitionMode::Auto => unreachable!(
"PartitionMode::Auto should not be present at execution time. This is a bug in DataFusion, please report it!"
),
};
self.build_report.schedule(build_data);
HashJoinStreamState::WaitPartitionBoundsReport
}
fn poll_next_impl(
&mut self,
cx: &mut std::task::Context<'_>,
) -> Poll<Option<Result<RecordBatch>>> {
loop {
if let Some(batch) = self.output_buffer.next_completed_batch() {
return self
.join_metrics
.baseline
.record_poll(Poll::Ready(Some(Ok(batch))));
}
if self.output_buffer.is_finished() {
return Poll::Ready(None);
}
return match self.state {
HashJoinStreamState::WaitBuildSide => {
handle_state!(ready!(self.collect_build_side(cx)))
}
HashJoinStreamState::WaitPartitionBoundsReport => {
handle_state!(ready!(self.wait_for_partition_bounds_report(cx)))
}
HashJoinStreamState::FetchProbeBatch => {
handle_state!(ready!(self.fetch_probe_batch(cx)))
}
HashJoinStreamState::ProcessProbeBatch(_) => {
handle_state!(self.process_probe_batch())
}
HashJoinStreamState::ExhaustedProbeSide => {
handle_state!(self.prepare_unmatched_build_rows())
}
HashJoinStreamState::EmitUnmatchedBuildRows(_) => {
handle_state!(self.emit_unmatched_build_rows())
}
HashJoinStreamState::Completed if !self.output_buffer.is_empty() => {
self.output_buffer.finish()?;
continue;
}
HashJoinStreamState::Completed => Poll::Ready(None),
};
}
}
fn wait_for_partition_bounds_report(
&mut self,
cx: &mut std::task::Context<'_>,
) -> Poll<Result<StatefulStreamResult<Option<RecordBatch>>>> {
ready!(self.build_report.poll_delivery(cx))?;
let build_side = self.build_side.try_as_ready()?;
self.state =
Self::state_after_build_ready(self.join_type, build_side.left_data.as_ref());
Poll::Ready(Ok(StatefulStreamResult::Continue))
}
fn collect_build_side(
&mut self,
cx: &mut std::task::Context<'_>,
) -> Poll<Result<StatefulStreamResult<Option<RecordBatch>>>> {
let build_timer = self.join_metrics.build_time.timer();
let left_data = ready!(
self.build_side
.try_as_initial_mut()?
.left_fut
.get_shared(cx)
)?;
build_timer.done();
self.state = self.transition_after_build_collected(&left_data);
self.build_side = BuildSide::Ready(BuildSideReadyState { left_data });
Poll::Ready(Ok(StatefulStreamResult::Continue))
}
fn fetch_probe_batch(
&mut self,
cx: &mut std::task::Context<'_>,
) -> Poll<Result<StatefulStreamResult<Option<RecordBatch>>>> {
match ready!(self.right.poll_next_unpin(cx)) {
None => {
let right_schema = self.right.schema();
self.right = Box::pin(EmptyRecordBatchStream::new(right_schema));
self.state = HashJoinStreamState::ExhaustedProbeSide;
}
Some(Ok(batch)) => {
let keys_values = evaluate_expressions_to_arrays(&self.on_right, &batch)?;
let valid_keys = if let Map::HashMap(_) =
self.build_side.try_as_ready()?.left_data.map()
{
self.hashes_buffer.clear();
self.hashes_buffer.resize(batch.num_rows(), 0);
create_hashes(
&keys_values,
&self.random_state,
&mut self.hashes_buffer,
)?;
matchable_join_keys(&keys_values, self.null_equality)
} else {
None
};
self.join_metrics.input_batches.add(1);
self.join_metrics.input_rows.add(batch.num_rows());
self.state =
HashJoinStreamState::ProcessProbeBatch(ProcessProbeBatchState {
batch,
values: keys_values,
valid_keys,
offset: AtRow { row: 0 },
joined_probe_idx: None,
matched_probe_idx: None,
key_comparator: None,
});
}
Some(Err(err)) => return Poll::Ready(Err(err)),
}
Poll::Ready(Ok(StatefulStreamResult::Continue))
}
fn process_probe_batch(
&mut self,
) -> Result<StatefulStreamResult<Option<RecordBatch>>> {
let state = self.state.try_as_process_probe_batch_mut()?;
let build_side = self.build_side.try_as_ready_mut()?;
if state.is_first_chunk() {
self.join_metrics
.probe_hit_rate
.add_total(state.batch.num_rows());
}
let timer = self.join_metrics.join_time.timer();
let skip = self.not_in.before_lookup(
&build_side.left_data,
&state.batch,
&state.values,
state.is_first_chunk(),
self.filter.as_ref(),
&self.random_state,
self.batch_size,
)?;
if skip {
timer.done();
self.state = HashJoinStreamState::FetchProbeBatch;
return Ok(StatefulStreamResult::Continue);
}
let is_empty = !build_side.left_data.has_matchable_build_rows();
if is_empty {
let result = self.not_in.after_empty_build(build_batch_empty_build_side(
&self.schema,
build_side.left_data.batch(),
&state.batch,
&self.column_indices,
self.join_type,
)?)?;
timer.done();
self.output_buffer.push_batch(result)?;
self.state = HashJoinStreamState::FetchProbeBatch;
return Ok(StatefulStreamResult::Continue);
}
let mut array_map_buffers = None;
let (left_indices, right_indices, next_offset) = match build_side.left_data.map()
{
Map::HashMap(map) => lookup_join_hashmap(
map.as_ref(),
build_side.left_data.values(),
&state.values,
self.null_equality,
&self.hashes_buffer,
state.valid_keys.as_ref(),
self.batch_size,
state.offset,
&mut self.probe_indices_buffer,
&mut self.build_indices_buffer,
&mut state.key_comparator,
)?,
Map::ArrayMap(array_map) => {
let next_offset = array_map.get_matched_indices_with_limit_offset(
&state.values,
self.batch_size,
state.offset,
&mut self.probe_indices_buffer,
&mut self.build_indices_buffer,
)?;
let build_indices: UInt64Array =
std::mem::take(&mut self.build_indices_buffer).into();
let probe_indices: UInt32Array =
std::mem::take(&mut self.probe_indices_buffer).into();
array_map_buffers = Some((
build_indices.values().clone(),
probe_indices.values().clone(),
));
(build_indices, probe_indices, next_offset)
}
};
let matched_probe_rows = state.count_new_matched_probe_rows(&right_indices);
self.join_metrics
.probe_hit_rate
.add_part(matched_probe_rows);
self.join_metrics.avg_fanout.add_part(left_indices.len());
self.join_metrics.avg_fanout.add_total(matched_probe_rows);
let (left_indices, right_indices) = if let Some(filter) = &self.filter {
apply_join_filter_to_indices(
build_side.left_data.batch(),
&state.batch,
left_indices,
right_indices,
filter,
JoinSide::Left,
None,
self.join_type,
)?
} else {
(left_indices, right_indices)
};
if need_produce_result_in_final(self.join_type) {
let mut bitmap = build_side.left_data.visited_indices_bitmap().lock();
left_indices.iter().flatten().for_each(|x| {
bitmap.set_bit(x as usize, true);
});
}
let last_joined_right_idx = match right_indices.len() {
0 => None,
n => Some(right_indices.value(n - 1) as usize),
};
let index_alignment_range_start = state.joined_probe_idx.map_or(0, |v| v + 1);
let index_alignment_range_end = if next_offset.is_none() {
state.batch.num_rows()
} else {
last_joined_right_idx.map_or(0, |v| v + 1)
};
let (left_indices, mut right_indices) = adjust_indices_by_join_type(
left_indices,
right_indices,
index_alignment_range_start..index_alignment_range_end,
self.join_type,
self.right_side_ordered,
)?;
if let Some(not_in) = build_side.left_data.not_in() {
right_indices = self.not_in.after_lookup(
not_in,
&state.values,
state.valid_keys.as_ref(),
right_indices,
);
}
let (build_batch, probe_batch, join_side) =
if self.join_type == JoinType::RightMark {
(&state.batch, build_side.left_data.batch(), JoinSide::Right)
} else {
(build_side.left_data.batch(), &state.batch, JoinSide::Left)
};
let batch = build_batch_from_indices(
&self.schema,
build_batch,
probe_batch,
&left_indices,
&right_indices,
&self.column_indices,
join_side,
self.join_type,
None,
)?;
drop((left_indices, right_indices));
if let Some((build_buffer, probe_buffer)) = array_map_buffers {
self.build_indices_buffer = build_buffer.into();
self.probe_indices_buffer = probe_buffer.into();
}
let push_status = self.output_buffer.push_batch(batch)?;
timer.done();
if push_status == PushBatchStatus::LimitReached {
self.output_buffer.finish()?;
self.state = HashJoinStreamState::Completed;
return Ok(StatefulStreamResult::Continue);
}
if next_offset.is_none() {
self.state = HashJoinStreamState::FetchProbeBatch;
} else {
state.advance(
next_offset
.ok_or_else(|| internal_datafusion_err!("unexpected None offset"))?,
last_joined_right_idx,
)
}
Ok(StatefulStreamResult::Continue)
}
fn prepare_unmatched_build_rows(
&mut self,
) -> Result<StatefulStreamResult<Option<RecordBatch>>> {
let timer = self.join_metrics.join_time.timer();
if !need_produce_result_in_final(self.join_type) {
timer.done();
self.state = HashJoinStreamState::Completed;
return Ok(StatefulStreamResult::Continue);
}
let build_side = self.build_side.try_as_ready()?;
let Completion::Emit(probe_summary) =
build_side.left_data.report_probe_completed()
else {
timer.done();
self.state = HashJoinStreamState::Completed;
return Ok(StatefulStreamResult::Continue);
};
let visited = build_side
.left_data
.visited_indices_bitmap()
.lock()
.finish_cloned();
self.join_metrics.input_batches.add(1);
timer.done();
self.state =
HashJoinStreamState::EmitUnmatchedBuildRows(EmitUnmatchedBuildRowsState {
visited,
cursor: 0,
probe_summary,
});
Ok(StatefulStreamResult::Continue)
}
fn emit_unmatched_build_rows(
&mut self,
) -> Result<StatefulStreamResult<Option<RecordBatch>>> {
let timer = self.join_metrics.join_time.timer();
let state = self.state.try_as_emit_unmatched_build_rows_mut()?;
if state.cursor >= state.visited.len() {
timer.done();
self.state = HashJoinStreamState::Completed;
return Ok(StatefulStreamResult::Continue);
}
let build_side = self.build_side.try_as_ready()?;
let probe_summary = state.probe_summary;
let (left_side, right_side) = next_final_indices_chunk(
&state.visited,
&mut state.cursor,
self.join_type,
self.batch_size,
);
let (left_side, right_side, mark_column) = match build_side.left_data.not_in() {
Some(not_in) => not_in.final_chunk(probe_summary, left_side, right_side),
None => (left_side, right_side, None),
};
self.join_metrics.input_rows.add(left_side.len());
if !left_side.is_empty() {
let empty_right_batch = RecordBatch::new_empty(self.right.schema());
let batch = build_batch_from_indices(
&self.schema,
build_side.left_data.batch(),
&empty_right_batch,
&left_side,
&right_side,
&self.column_indices,
JoinSide::Left,
self.join_type,
mark_column.as_ref(),
)?;
let push_status = self.output_buffer.push_batch(batch)?;
if push_status == PushBatchStatus::LimitReached {
self.output_buffer.finish()?;
self.state = HashJoinStreamState::Completed;
}
}
timer.done();
Ok(StatefulStreamResult::Continue)
}
}
fn next_final_indices_chunk(
visited: &BooleanBuffer,
cursor: &mut usize,
join_type: JoinType,
batch_size: usize,
) -> (UInt64Array, UInt32Array) {
let num_rows = visited.len();
let start = *cursor;
if join_type == JoinType::LeftMark {
let end = (start + batch_size).min(num_rows);
let build_indices = (start as u64..end as u64).collect::<UInt64Array>();
let probe_indices = (start..end)
.map(|idx| visited.value(idx).then_some(0))
.collect::<UInt32Array>();
*cursor = end;
return (build_indices, probe_indices);
}
let emit_visited = join_type == JoinType::LeftSemi;
let mut build_indices = Vec::with_capacity(batch_size.min(num_rows - start));
let mut idx = start;
while idx < num_rows && build_indices.len() < batch_size {
if visited.value(idx) == emit_visited {
build_indices.push(idx as u64);
}
idx += 1;
}
*cursor = idx;
let probe_indices = UInt32Array::new_null(build_indices.len());
(UInt64Array::from(build_indices), probe_indices)
}
impl Stream for HashJoinStream {
type Item = Result<RecordBatch>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> Poll<Option<Self::Item>> {
self.poll_next_impl(cx)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::joins::hash_join::shared_bounds::{
PushdownStrategy, completed_partitions_for_test,
make_partitioned_accumulator_for_test,
};
fn empty_build_data(partition_id: usize) -> PartitionBuildData {
PartitionBuildData::Partitioned {
partition_id,
pushdown: PushdownStrategy::Empty,
bounds: PartitionBounds::new(vec![]),
keys_have_null: false,
}
}
fn partitioned_handle(acc: &Arc<SharedBuildAccumulator>) -> BuildReportHandle {
BuildReportHandle::new(0, PartitionMode::Partitioned, Some(Arc::clone(acc)))
}
#[test]
fn build_report_handle_cancels_scheduled_partition_on_drop() {
let acc = Arc::new(make_partitioned_accumulator_for_test(2));
{
let mut handle = partitioned_handle(&acc);
handle.schedule(empty_build_data(0));
assert_eq!(handle.state(), &BuildReportState::Scheduled);
}
assert_eq!(completed_partitions_for_test(&acc), 1);
}
#[test]
fn build_report_handle_does_not_cancel_delivered_partition_on_drop() {
let acc = Arc::new(make_partitioned_accumulator_for_test(1));
{
let mut handle = partitioned_handle(&acc);
handle.schedule(empty_build_data(0));
let mut cx = std::task::Context::from_waker(futures::task::noop_waker_ref());
assert!(matches!(handle.poll_delivery(&mut cx), Poll::Ready(Ok(()))));
assert_eq!(handle.state(), &BuildReportState::Delivered);
}
assert_eq!(completed_partitions_for_test(&acc), 1);
}
#[test]
fn build_report_handle_cancel_pending_is_idempotent() {
let acc = Arc::new(make_partitioned_accumulator_for_test(2));
let mut handle = partitioned_handle(&acc);
handle.schedule(empty_build_data(0));
handle.cancel_pending();
handle.cancel_pending();
assert_eq!(handle.state(), &BuildReportState::Canceled);
assert_eq!(completed_partitions_for_test(&acc), 1);
}
#[test]
fn build_report_handle_no_accumulator_finalizes() {
let mut handle = BuildReportHandle::new(0, PartitionMode::Partitioned, None);
handle.schedule(empty_build_data(0));
handle.cancel_pending();
assert_eq!(handle.state(), &BuildReportState::Finalized);
}
}