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
Original file line number Diff line number Diff line change
Expand Up @@ -645,7 +645,11 @@ impl JoinedRecordBatches {
/// get_corrected_filter_mask() to pass them through unchanged.
///
/// Maintains invariant: N rows → N metadata entries (nulls)
fn push_batch_with_null_metadata(&mut self, batch: RecordBatch, join_type: JoinType) {
fn push_batch_with_null_metadata(
&mut self,
batch: RecordBatch,
join_type: JoinType,
) -> Result<()> {
debug_assert!(
matches!(join_type, JoinType::Left | JoinType::Right | JoinType::Full),
"push_batch_with_null_metadata should only be called for deferred-filtered joins"
Expand All @@ -656,9 +660,8 @@ impl JoinedRecordBatches {
self.filter_metadata.append_nulls(num_rows);

self.filter_metadata.debug_assert_metadata_aligned();
self.joined_batches
.push_batch(batch)
.expect("Failed to push batch to BatchCoalescer");
self.joined_batches.push_batch(batch)?;
Ok(())
}

/// Pushes a batch with filter metadata (filtered outer joins)
Expand All @@ -677,7 +680,7 @@ impl JoinedRecordBatches {
filter_mask: &BooleanArray,
streamed_batch_id: usize,
join_type: JoinType,
) {
) -> Result<()> {
debug_assert!(
matches!(join_type, JoinType::Left | JoinType::Right | JoinType::Full),
"push_batch_with_filter_metadata should only be called for outer joins that need deferred filtering"
Expand All @@ -696,20 +699,18 @@ impl JoinedRecordBatches {
);

self.filter_metadata.debug_assert_metadata_aligned();
self.joined_batches
.push_batch(batch)
.expect("Failed to push batch to BatchCoalescer");
self.joined_batches.push_batch(batch)?;
Ok(())
}

/// Pushes a batch without metadata (non-filtered joins)
///
/// No deferred filtering needed. Either every join match is output (Inner),
/// or null-joined rows are handled separately. No need to track which input
/// row produced which output row.
fn push_batch_without_metadata(&mut self, batch: RecordBatch) {
self.joined_batches
.push_batch(batch)
.expect("Failed to push batch to BatchCoalescer");
fn push_batch_without_metadata(&mut self, batch: RecordBatch) -> Result<()> {
self.joined_batches.push_batch(batch)?;
Ok(())
}

fn clear(&mut self, schema: &SchemaRef, batch_size: usize) {
Expand Down Expand Up @@ -1166,16 +1167,9 @@ impl MaterializingSortMergeJoinStream {
.debug_assert_metadata_aligned();

if self.deferred_filtering {
// Filtered joins must concat and filter ALL remaining data at
// once. The result is staged in `output` rather than emitted
// directly: `output` may still hold rows from earlier flushes,
// and those precede these on the streamed side.
if !self.joined_record_batches.joined_batches.is_empty() {
let record_batch = self.filter_joined_batch()?;
self.output
.push_batch(record_batch)
.expect("Failed to push output batch");
}
// Keep the final deferred-filter flush on the same staging path as
// earlier flushes so all filtered output uses one coalescer push site.
self.stage_filtered_output()?;
} else if !self.joined_record_batches.joined_batches.is_empty() {
// For non-filtered joins, finish buffered data first, then emit
// every completed batch.
Expand Down Expand Up @@ -1246,9 +1240,7 @@ impl MaterializingSortMergeJoinStream {

if !self.joined_record_batches.joined_batches.is_empty() {
let out_filtered_batch = self.filter_joined_batch()?;
self.output
.push_batch(out_filtered_batch)
.expect("Failed to push output batch");
self.output.push_batch(out_filtered_batch)?;
Comment thread
efegokdemir marked this conversation as resolved.
Resolved
}

Ok(())
Expand Down Expand Up @@ -1713,7 +1705,7 @@ impl MaterializingSortMergeJoinStream {
&self.buffered_columns,
)? {
self.joined_record_batches
.push_batch_with_null_metadata(record_batch, self.join_type);
.push_batch_with_null_metadata(record_batch, self.join_type)?;
}
buffered_batch.null_joined.clear();
}
Expand Down Expand Up @@ -1751,7 +1743,7 @@ impl MaterializingSortMergeJoinStream {
&self.buffered_columns,
)? {
self.joined_record_batches
.push_batch_with_null_metadata(record_batch, self.join_type);
.push_batch_with_null_metadata(record_batch, self.join_type)?;
}
buffered_batch
.join_filter_status
Expand Down Expand Up @@ -1807,10 +1799,10 @@ impl MaterializingSortMergeJoinStream {
// get_corrected_filter_mask() passes them through unchanged.
if self.deferred_filtering {
self.joined_record_batches
.push_batch_with_null_metadata(batch, self.join_type);
.push_batch_with_null_metadata(batch, self.join_type)?;
} else {
self.joined_record_batches
.push_batch_without_metadata(batch);
.push_batch_without_metadata(batch)?;
}
continue;
}
Expand Down Expand Up @@ -1914,11 +1906,11 @@ impl MaterializingSortMergeJoinStream {
&mask,
self.streamed_batch_counter,
self.join_type,
);
)?;
} else {
let filtered_batch = filter_record_batch(&output_batch, &mask)?;
self.joined_record_batches
.push_batch_without_metadata(filtered_batch);
.push_batch_without_metadata(filtered_batch)?;
}

// Track which buffered rows had all filter matches fail,
Expand Down Expand Up @@ -1957,7 +1949,7 @@ impl MaterializingSortMergeJoinStream {
}
} else {
self.joined_record_batches
.push_batch_without_metadata(output_batch);
.push_batch_without_metadata(output_batch)?;
}

Ok(())
Expand Down Expand Up @@ -2046,7 +2038,7 @@ impl MaterializingSortMergeJoinStream {
kept_rows,
)?;
self.joined_record_batches
.push_batch_without_metadata(output_batch);
.push_batch_without_metadata(output_batch)?;
Ok(true)
}

Expand Down
91 changes: 91 additions & 0 deletions datafusion/physical-plan/src/joins/sort_merge_join/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8713,3 +8713,94 @@ async fn join_inner_early_filtering_matches_hash_join() -> Result<()> {
}
Ok(())
}

/// Errors from coalescing filtered join output must be returned to the query
/// instead of panicking the execution stream.
/// Each right input batch contributes 100 distinct labels after filtering. At
/// a batch size of 200, those 100-row staged outputs are not passed through,
/// so two are coalesced into 200 dictionary values, beyond the 128 non-negative
/// indices available from an Int8 dictionary key.
#[tokio::test]
async fn filtered_join_returns_output_coalescer_error() -> Result<()> {
use arrow::datatypes::Int8Type;

let left_schema = Arc::new(Schema::new(vec![
Field::new("lk", DataType::Int32, false),
Field::new("lx", DataType::Int32, false),
]));
let right_schema = Arc::new(Schema::new(vec![
Field::new("rk", DataType::Int32, false),
Field::new("rx", DataType::Int32, false),
Field::new(
"p",
DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Utf8)),
false,
),
]));
let left = RecordBatch::try_new(
Arc::clone(&left_schema),
vec![
Arc::new(Int32Array::from((0..300).collect::<Vec<_>>())),
Arc::new(Int32Array::from(vec![0; 300])),
],
)?;
let right_batch = |base: i32, tag: &str| -> Result<RecordBatch> {
let (mut keys, mut values, mut labels) = (vec![], vec![], vec![]);
for i in 0..100 {
keys.extend([base + i, base + i]);
values.extend([-1, 0]);
labels.extend([format!("{tag}-fails"), format!("{tag}{i}")]);
}
Ok(RecordBatch::try_new(
Arc::clone(&right_schema),
vec![
Arc::new(Int32Array::from(keys)),
Arc::new(Int32Array::from(values)),
Arc::new(
labels
.iter()
.map(String::as_str)
.collect::<DictionaryArray<Int8Type>>(),
),
],
)?)
};
let right = vec![
right_batch(0, "a")?,
right_batch(100, "b")?,
right_batch(200, "c")?,
];
let left_exec = build_table_from_batches(vec![left]);
let right_exec = build_table_from_batches(right);
let on = vec![(
Arc::new(Column::new_with_schema("lk", &left_schema)?) as _,
Arc::new(Column::new_with_schema("rk", &right_schema)?) as _,
)];
let filter = early_filter(
Arc::new(BinaryExpr::new(
Arc::new(Column::new("lx", 0)),
Operator::LtEq,
Arc::new(Column::new("rx", 1)),
)),
&["lx", "rx"],
&left_schema,
&right_schema,
);
let join = SortMergeJoinExec::try_new(
left_exec,
right_exec,
on,
Some(filter),
Left,
vec![SortOptions::default()],
NullEquality::NullEqualsNothing,
)?;
let ctx = Arc::new(
TaskContext::default()
.with_session_config(SessionConfig::new().with_batch_size(200)),
);

let error = common::collect(join.execute(0, ctx)?).await.unwrap_err();
assert_contains!(error.to_string(), "Dictionary key bigger than the key type");
Ok(())
}