Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 60 additions & 2 deletions native-engine/datafusion-ext-plans/src/broadcast_join_exec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -836,8 +836,10 @@ fn augment_join_params_with_row_num(
probe_side: JoinSide,
) -> (JoinParams, usize) {
let mut augmented = join_params.clone();
let is_dual_block =
!augmented.projection.left.is_empty() && !augmented.projection.right.is_empty();
let is_dual_block = matches!(
augmented.join_type,
JoinType::Inner | JoinType::Left | JoinType::Right | JoinType::Full
);

match probe_side {
JoinSide::Left => {
Expand Down Expand Up @@ -1460,6 +1462,62 @@ mod fuzztest {
out
}

#[tokio::test]
async fn hybrid_join_reserved_order_with_right_only_projection() -> Result<()> {
MemManager::init(10_000_000);
let left = RecordBatch::try_from_iter(vec![(
"lk",
Arc::new(Int32Array::from(vec![2, 1, 3])) as ArrayRef,
)])?;
let right = RecordBatch::try_from_iter(vec![
("rk", Arc::new(Int32Array::from(vec![1, 2, 3])) as ArrayRef),
(
"rv",
Arc::new(Int32Array::from(vec![100, 200, 300])) as ArrayRef,
),
])?;
let schema = Arc::new(
build_join_schema(
&left.schema(),
&right.schema(),
&datafusion::common::JoinType::Inner,
)
.0,
);
let left_key = Arc::new(Column::new("lk", 0)) as PhysicalExprRef;
let right_key = Arc::new(Column::new("rk", 0)) as PhysicalExprRef;
let built = build_bucketed_groups(
right,
right_key.clone(),
1,
false,
&mut rand::rngs::StdRng::seed_from_u64(0),
)?;
let join: Arc<dyn ExecutionPlan> = Arc::new(
BroadcastJoinExec::try_new(
schema.clone(),
memory(left),
built,
vec![(left_key, right_key)],
JoinType::Inner,
JoinSide::Right,
true,
None,
false,
None,
)?
.with_required_reserved_order(true),
);
let stream = join.execute_projected(0, SessionContext::new().task_ctx(), &[2])?;
assert_eq!(stream.schema().as_ref(), &schema.project(&[2])?);
let batches = collect(stream).await?;
assert_eq!(
extract_i32_col(&batches, "rv"),
vec![Some(200), Some(100), Some(300)]
);
Ok(())
}

/// Verify that a forced hybrid join with `required_reserved_order` preserves
/// the probe side's row order, against a plain in-memory hash join as the
/// reference. Only join-type/broadcast-side combos where the probe side
Expand Down
180 changes: 178 additions & 2 deletions native-engine/datafusion-ext-plans/src/common/column_pruning.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ use futures::StreamExt;
use itertools::Itertools;
use parking_lot::Mutex;

use crate::{broadcast_join_exec::BroadcastJoinExec, sort_merge_join_exec::SortMergeJoinExec};

pub trait ExecuteWithColumnPruning {
fn execute_projected(
&self,
Expand All @@ -51,11 +53,23 @@ impl ExecuteWithColumnPruning for dyn ExecutionPlan {
context: Arc<TaskContext>,
projection: &[usize],
) -> Result<SendableRecordBatchStream> {
if projection.iter().enumerate().all(|(i, &proj)| proj == i) {
if projection.len() == self.schema().fields().len()
&& projection.iter().enumerate().all(|(i, &proj)| proj == i)
{
return self.execute(partition, context);
}
let schema = Arc::new(self.schema().project(projection)?);
// Join output is assembled left then right. Keep reordering and
// duplicates on the generic path to preserve the requested column order.
if projection.windows(2).all(|pair| pair[0] < pair[1]) {
if let Some(join) = self.downcast_ref::<BroadcastJoinExec>() {
return join.execute_projected(partition, context, projection);
}
if let Some(join) = self.downcast_ref::<SortMergeJoinExec>() {
return join.execute_projected(partition, context, projection);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SortMergeJoinExec caches JoinParams in a OnceCell, so the first projection wins. I verified locally that calling execute_projected with [1] and then [2] on the same instance returns column 1 both times.

A subsequent execute() also returns just one column.

Could we cache only the projection-independent parameters and add a regression test that reuses the same join instance?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for catching this! I changed SMJ to create JoinParams per execution and updated the existing test to cover different projections followed by execute() on the same instance.

While checking this path, I also fixed an existing hybrid join layout assumption exposed by column pruning: with a right-only projection, the row-number column used to preserve probe order was placed incorrectly in the output schema. The targeted regression test and Spark SQL reproducer now pass.

}
}
let projection = projection.to_vec();
let schema = Arc::new(self.schema().project(&projection)?);
let stream =
self.execute(partition, context)?
.map(move |batch_result: Result<RecordBatch>| {
Expand Down Expand Up @@ -132,3 +146,165 @@ pub fn map_columns(expr: &PhysicalExprRef, mapping: &HashMap<usize, usize>) -> P
.map(|r| r.data)
.expect("expr transform failed")
}

#[cfg(test)]
mod tests {
use arrow::{
array::{ArrayRef, Int32Array},
compute::concat_batches,
datatypes::{DataType, Field, Schema},
};
use auron_memmgr::MemManager;
use datafusion::{
common::JoinSide,
physical_plan::{common::collect, joins::utils::build_join_schema, test::TestMemoryExec},
prelude::SessionContext,
};

use super::*;
use crate::joins::join_utils::JoinType;

fn memory(batch: RecordBatch) -> Result<Arc<dyn ExecutionPlan>> {
Ok(Arc::new(TestMemoryExec::try_new(
&[vec![batch.clone()]],
batch.schema(),
None,
)?))
}

fn batch(prefix: &str, keys: Vec<Option<i32>>, values: Vec<i32>) -> Result<RecordBatch> {
Ok(RecordBatch::try_from_iter_with_nullable(vec![
(
format!("{prefix}k"),
Arc::new(Int32Array::from(keys)) as ArrayRef,
true,
),
(
format!("{prefix}v"),
Arc::new(Int32Array::from(values)) as ArrayRef,
true,
),
])?)
}

#[tokio::test]
async fn projected_execution_preserves_schema_values_and_row_count() -> Result<()> {
let original = batch("l", vec![Some(1), Some(2), Some(3)], vec![10, 20, 30])?;
let metadata = HashMap::from([("test".to_owned(), "preserved".to_owned())]);
let mut fields = original.schema().fields().to_vec();
fields[0] = Arc::new(fields[0].as_ref().clone().with_metadata(metadata.clone()));
let schema = Arc::new(Schema::new_with_metadata(fields, metadata));
let batch = RecordBatch::try_new(schema, original.columns().to_vec())?;
let input = memory(batch.clone())?;
let context = SessionContext::new().task_ctx();
for projection in [vec![], vec![0], vec![1], vec![1, 0, 1], vec![0, 1]] {
let expected = batch.project(&projection)?;
let stream = input.execute_projected(0, context.clone(), &projection)?;
assert_eq!(stream.schema(), expected.schema());
assert_eq!(
concat_batches(&expected.schema(), &collect(stream).await?)?,
expected
);
}
assert!(input.execute_projected(0, context, &[2]).is_err());
Ok(())
}

#[tokio::test]
async fn joins_preserve_projected_values_and_row_count() -> Result<()> {
MemManager::init(1_000_000);
let left = memory(batch(
"l",
vec![None, Some(1), Some(2), Some(3)],
vec![0, 10, 20, 30],
)?)?;
let right = memory(batch(
"r",
vec![None, Some(1), Some(2), Some(2), Some(4)],
vec![0, 100, 200, 201, 400],
)?)?;
let context = SessionContext::new().task_ctx();
for join_type in [
JoinType::Inner,
JoinType::Left,
JoinType::Right,
JoinType::Full,
JoinType::LeftSemi,
JoinType::LeftAnti,
JoinType::RightSemi,
JoinType::RightAnti,
JoinType::Existence,
] {
let schema = if join_type == JoinType::Existence {
Arc::new(Schema::new(
[
left.schema().fields().to_vec(),
vec![Arc::new(Field::new("exists", DataType::Boolean, false))],
]
.concat(),
))
} else {
Arc::new(
build_join_schema(&left.schema(), &right.schema(), &join_type.try_into()?).0,
)
};
for build_side in [None, Some(JoinSide::Left), Some(JoinSide::Right)] {
let join = || -> Result<Arc<dyn ExecutionPlan>> {
let on = vec![(
Arc::new(Column::new("lk", 0)) as PhysicalExprRef,
Arc::new(Column::new("rk", 0)) as PhysicalExprRef,
)];
Ok(match build_side {
None => Arc::new(SortMergeJoinExec::try_new(
schema.clone(),
left.clone(),
right.clone(),
on,
join_type,
None,
vec![Default::default()],
)?),
Some(side) => Arc::new(BroadcastJoinExec::try_new(
schema.clone(),
left.clone(),
right.clone(),
on,
join_type,
side,
false,
None,
false,
None,
)?),
})
};
let full = concat_batches(
&schema,
&collect(join()?.execute(0, context.clone())?).await?,
)?;
let join = join()?;
let last = schema.fields().len() - 1;
for projection in [
vec![],
vec![0],
vec![last],
vec![0, last],
vec![last, 0, last],
] {
let expected = full.project(&projection)?;
let stream = join.execute_projected(0, context.clone(), &projection)?;
assert_eq!(stream.schema(), expected.schema());
assert_eq!(
concat_batches(&expected.schema(), &collect(stream).await?)?,
expected,
"join_type={join_type:?}, build_side={build_side:?}, projection={projection:?}"
);
}
let stream = join.execute(0, context.clone())?;
assert_eq!(stream.schema(), schema);
assert_eq!(concat_batches(&schema, &collect(stream).await?)?, full);
}
}
Ok(())
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,6 @@ pub struct SortMergeJoinExec {
join_type: JoinType,
sort_options: Vec<SortOptions>,
join_filter: Option<JoinFilter>,
join_params: OnceCell<JoinParams>,
schema: SchemaRef,
metrics: ExecutionPlanMetricsSet,
props: OnceCell<Arc<PlanProperties>>,
Expand All @@ -86,7 +85,6 @@ impl SortMergeJoinExec {
join_type,
sort_options,
join_filter,
join_params: OnceCell::new(),
metrics: ExecutionPlanMetricsSet::new(),
props: OnceCell::new(),
})
Expand Down Expand Up @@ -151,10 +149,7 @@ impl SortMergeJoinExec {
context: Arc<TaskContext>,
projection: Vec<usize>,
) -> Result<SendableRecordBatchStream> {
let mut join_params = self
.join_params
.get_or_try_init(|| self.create_join_params(&projection))?
.clone();
let mut join_params = self.create_join_params(&projection)?;
let exec_ctx = ExecutionContext::new(
context,
partition,
Expand Down