From 2fde083058f7fb9415e49814e45a85537a09c9d7 Mon Sep 17 00:00:00 2001 From: Efe Date: Wed, 25 Nov 2026 01:32:15 +0300 Subject: [PATCH 1/3] fix(physical-plan): propagate sort-merge coalescer errors --- .../sort_merge_join/materializing_stream.rs | 47 +++++---- .../src/joins/sort_merge_join/tests.rs | 96 +++++++++++++++++++ 2 files changed, 118 insertions(+), 25 deletions(-) diff --git a/datafusion/physical-plan/src/joins/sort_merge_join/materializing_stream.rs b/datafusion/physical-plan/src/joins/sort_merge_join/materializing_stream.rs index 65bc6afcc3609..926e3af885c1f 100644 --- a/datafusion/physical-plan/src/joins/sort_merge_join/materializing_stream.rs +++ b/datafusion/physical-plan/src/joins/sort_merge_join/materializing_stream.rs @@ -513,7 +513,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" @@ -524,9 +528,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) @@ -545,7 +548,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" @@ -564,9 +567,8 @@ 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) @@ -574,10 +576,9 @@ impl JoinedRecordBatches { /// 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) { @@ -983,9 +984,7 @@ impl MaterializingSortMergeJoinStream { // 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"); + self.output.push_batch(record_batch)?; } } else if !self.joined_record_batches.joined_batches.is_empty() { // For non-filtered joins, finish buffered data first, then emit @@ -1057,9 +1056,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)?; } Ok(()) @@ -1522,7 +1519,7 @@ impl MaterializingSortMergeJoinStream { buffered_batch, )? { 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(); } @@ -1558,7 +1555,7 @@ impl MaterializingSortMergeJoinStream { buffered_batch, )? { 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 @@ -1608,10 +1605,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; } @@ -1724,11 +1721,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, @@ -1765,7 +1762,7 @@ impl MaterializingSortMergeJoinStream { } } else { self.joined_record_batches - .push_batch_without_metadata(output_batch); + .push_batch_without_metadata(output_batch)?; } Ok(()) diff --git a/datafusion/physical-plan/src/joins/sort_merge_join/tests.rs b/datafusion/physical-plan/src/joins/sort_merge_join/tests.rs index babc9851a985c..94c30de3cef43 100644 --- a/datafusion/physical-plan/src/joins/sort_merge_join/tests.rs +++ b/datafusion/physical-plan/src/joins/sort_merge_join/tests.rs @@ -8395,3 +8395,99 @@ async fn left_join_with_partial_filter_preserves_streamed_order() -> Result<()> ); Ok(()) } + +/// Errors from coalescing filtered join output must be returned to the query +/// instead of panicking the execution stream. +#[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..200).collect::>())), + Arc::new(Int32Array::from(vec![0; 200])), + ], + )?; + let right_batch = |base: i32, tag: &str| -> Result { + 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::>(), + ), + ], + )?) + }; + let right = vec![right_batch(0, "a")?, right_batch(100, "b")?]; + let left_exec = + TestMemoryExec::try_new_exec(&[vec![left]], Arc::clone(&left_schema), None)?; + let right_exec = + TestMemoryExec::try_new_exec(&[right], Arc::clone(&right_schema), None)?; + let on: JoinOn = vec![( + Arc::new(Column::new_with_schema("lk", &left_schema)?) as _, + Arc::new(Column::new_with_schema("rk", &right_schema)?) as _, + )]; + let filter = JoinFilter::new( + Arc::new(BinaryExpr::new( + Arc::new(Column::new("lx", 0)), + Operator::LtEq, + Arc::new(Column::new("rx", 1)), + )), + vec![ + ColumnIndex { + index: 1, + side: JoinSide::Left, + }, + ColumnIndex { + index: 1, + side: JoinSide::Right, + }, + ], + Arc::new(Schema::new(vec![ + Field::new("lx", DataType::Int32, false), + Field::new("rx", DataType::Int32, false), + ])), + ); + 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(()) +} From e4e566b21b46d16a354f63c1f54dea736dacc260 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Efe=20G=C3=B6kdemir?= Date: Fri, 27 Nov 2026 07:43:04 +0300 Subject: [PATCH 2/3] test(physical-plan): cover later coalescer error path --- .../physical-plan/src/joins/sort_merge_join/tests.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/datafusion/physical-plan/src/joins/sort_merge_join/tests.rs b/datafusion/physical-plan/src/joins/sort_merge_join/tests.rs index 94c30de3cef43..5b9336cc66663 100644 --- a/datafusion/physical-plan/src/joins/sort_merge_join/tests.rs +++ b/datafusion/physical-plan/src/joins/sort_merge_join/tests.rs @@ -8418,8 +8418,8 @@ async fn filtered_join_returns_output_coalescer_error() -> Result<()> { let left = RecordBatch::try_new( Arc::clone(&left_schema), vec![ - Arc::new(Int32Array::from((0..200).collect::>())), - Arc::new(Int32Array::from(vec![0; 200])), + Arc::new(Int32Array::from((0..300).collect::>())), + Arc::new(Int32Array::from(vec![0; 300])), ], )?; let right_batch = |base: i32, tag: &str| -> Result { @@ -8443,7 +8443,11 @@ async fn filtered_join_returns_output_coalescer_error() -> Result<()> { ], )?) }; - let right = vec![right_batch(0, "a")?, right_batch(100, "b")?]; + let right = vec![ + right_batch(0, "a")?, + right_batch(100, "b")?, + right_batch(200, "c")?, + ]; let left_exec = TestMemoryExec::try_new_exec(&[vec![left]], Arc::clone(&left_schema), None)?; let right_exec = From ff0854d16e9516ab7f7f12d8fd3694a2c7aae948 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Efe=20G=C3=B6kdemir?= Date: Sat, 5 Dec 2026 17:05:57 +0300 Subject: [PATCH 3/3] Return sort-merge join coalescer errors --- .../sort_merge_join/materializing_stream.rs | 11 ++----- .../src/joins/sort_merge_join/tests.rs | 31 +++++++------------ 2 files changed, 14 insertions(+), 28 deletions(-) diff --git a/datafusion/physical-plan/src/joins/sort_merge_join/materializing_stream.rs b/datafusion/physical-plan/src/joins/sort_merge_join/materializing_stream.rs index 30bc73bd47936..10bfbfd502eeb 100644 --- a/datafusion/physical-plan/src/joins/sort_merge_join/materializing_stream.rs +++ b/datafusion/physical-plan/src/joins/sort_merge_join/materializing_stream.rs @@ -1167,14 +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)?; - } + // 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. diff --git a/datafusion/physical-plan/src/joins/sort_merge_join/tests.rs b/datafusion/physical-plan/src/joins/sort_merge_join/tests.rs index b838037fd4f59..16b9b5a7e5996 100644 --- a/datafusion/physical-plan/src/joins/sort_merge_join/tests.rs +++ b/datafusion/physical-plan/src/joins/sort_merge_join/tests.rs @@ -8716,6 +8716,10 @@ async fn join_inner_early_filtering_matches_hash_join() -> Result<()> { /// 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; @@ -8766,34 +8770,21 @@ async fn filtered_join_returns_output_coalescer_error() -> Result<()> { right_batch(100, "b")?, right_batch(200, "c")?, ]; - let left_exec = - TestMemoryExec::try_new_exec(&[vec![left]], Arc::clone(&left_schema), None)?; - let right_exec = - TestMemoryExec::try_new_exec(&[right], Arc::clone(&right_schema), None)?; - let on: JoinOn = vec![( + 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 = JoinFilter::new( + let filter = early_filter( Arc::new(BinaryExpr::new( Arc::new(Column::new("lx", 0)), Operator::LtEq, Arc::new(Column::new("rx", 1)), )), - vec![ - ColumnIndex { - index: 1, - side: JoinSide::Left, - }, - ColumnIndex { - index: 1, - side: JoinSide::Right, - }, - ], - Arc::new(Schema::new(vec![ - Field::new("lx", DataType::Int32, false), - Field::new("rx", DataType::Int32, false), - ])), + &["lx", "rx"], + &left_schema, + &right_schema, ); let join = SortMergeJoinExec::try_new( left_exec,