-
Notifications
You must be signed in to change notification settings - Fork 1.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Chore: Do not return empty record batches from streams #13794
Merged
ozankabak
merged 17 commits into
apache:main
from
synnada-ai:chore/remove-empty-batches
Dec 18, 2024
Merged
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
e9cc59a
do not emit empty record batches in plans
mertak-synnada 30a6b97
Merge branch 'refs/heads/apache_main' into chore/remove-empty-batches
mertak-synnada 69fbe64
change function signatures to Option<RecordBatch> if empty batches ar…
mertak-synnada 2c7b70d
format code
mertak-synnada 4b56e65
shorten code
mertak-synnada fd44a6e
change list_unnest_at_level for returning Option value
mertak-synnada 4706bc3
Merge branch 'refs/heads/apache_main' into chore/remove-empty-batches
mertak-synnada 72bdab9
add documentation
mertak-synnada 1f9349f
create unit test for row_hash.rs
mertak-synnada cd505f4
add test for unnest
mertak-synnada 0dccc81
add test for unnest
mertak-synnada 466d697
add test for partial sort
mertak-synnada 29e1204
add test for bounded window agg
mertak-synnada f9c2bbe
add test for window agg
mertak-synnada 9978e4d
Merge branch 'refs/heads/apache_main' into chore/remove-empty-batches
mertak-synnada c59afd4
apply simplifications and fix typo
mertak-synnada 2730f81
apply simplifications and fix typo
mertak-synnada File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -654,9 +654,13 @@ impl Stream for GroupedHashAggregateStream { | |
} | ||
|
||
if let Some(to_emit) = self.group_ordering.emit_to() { | ||
let batch = extract_ok!(self.emit(to_emit, false)); | ||
self.exec_state = ExecutionState::ProducingOutput(batch); | ||
timer.done(); | ||
if let Some(batch) = | ||
extract_ok!(self.emit(to_emit, false)) | ||
{ | ||
self.exec_state = | ||
ExecutionState::ProducingOutput(batch); | ||
}; | ||
// make sure the exec_state just set is not overwritten below | ||
break 'reading_input; | ||
} | ||
|
@@ -693,9 +697,13 @@ impl Stream for GroupedHashAggregateStream { | |
} | ||
|
||
if let Some(to_emit) = self.group_ordering.emit_to() { | ||
let batch = extract_ok!(self.emit(to_emit, false)); | ||
self.exec_state = ExecutionState::ProducingOutput(batch); | ||
timer.done(); | ||
if let Some(batch) = | ||
extract_ok!(self.emit(to_emit, false)) | ||
{ | ||
self.exec_state = | ||
ExecutionState::ProducingOutput(batch); | ||
}; | ||
// make sure the exec_state just set is not overwritten below | ||
break 'reading_input; | ||
} | ||
|
@@ -768,6 +776,9 @@ impl Stream for GroupedHashAggregateStream { | |
let output = batch.slice(0, size); | ||
(ExecutionState::ProducingOutput(remaining), output) | ||
}; | ||
// Empty record batches should not be emitted. | ||
// They need to be treated as [`Option<RecordBatch>`]es and handled separately | ||
debug_assert!(output_batch.num_rows() > 0); | ||
return Poll::Ready(Some(Ok( | ||
output_batch.record_output(&self.baseline_metrics) | ||
))); | ||
|
@@ -902,14 +913,14 @@ impl GroupedHashAggregateStream { | |
|
||
/// Create an output RecordBatch with the group keys and | ||
/// accumulator states/values specified in emit_to | ||
fn emit(&mut self, emit_to: EmitTo, spilling: bool) -> Result<RecordBatch> { | ||
fn emit(&mut self, emit_to: EmitTo, spilling: bool) -> Result<Option<RecordBatch>> { | ||
let schema = if spilling { | ||
Arc::clone(&self.spill_state.spill_schema) | ||
} else { | ||
self.schema() | ||
}; | ||
if self.group_values.is_empty() { | ||
return Ok(RecordBatch::new_empty(schema)); | ||
return Ok(None); | ||
} | ||
|
||
let mut output = self.group_values.emit(emit_to)?; | ||
|
@@ -937,7 +948,8 @@ impl GroupedHashAggregateStream { | |
// over the target memory size after emission, we can emit again rather than returning Err. | ||
let _ = self.update_memory_reservation(); | ||
let batch = RecordBatch::try_new(schema, output)?; | ||
Ok(batch) | ||
debug_assert!(batch.num_rows() > 0); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Maybe it would be good to document in comments somewhere the expectation / behavior that no empty record batches are produced |
||
Ok(Some(batch)) | ||
} | ||
|
||
/// Optimistically, [`Self::group_aggregate_batch`] allows to exceed the memory target slightly | ||
|
@@ -963,7 +975,9 @@ impl GroupedHashAggregateStream { | |
|
||
/// Emit all rows, sort them, and store them on disk. | ||
fn spill(&mut self) -> Result<()> { | ||
let emit = self.emit(EmitTo::All, true)?; | ||
let Some(emit) = self.emit(EmitTo::All, true)? else { | ||
return Ok(()); | ||
}; | ||
let sorted = sort_batch(&emit, self.spill_state.spill_expr.as_ref(), None)?; | ||
let spillfile = self.runtime.disk_manager.create_tmp_file("HashAggSpill")?; | ||
// TODO: slice large `sorted` and write to multiple files in parallel | ||
|
@@ -1008,8 +1022,9 @@ impl GroupedHashAggregateStream { | |
{ | ||
assert_eq!(self.mode, AggregateMode::Partial); | ||
let n = self.group_values.len() / self.batch_size * self.batch_size; | ||
let batch = self.emit(EmitTo::First(n), false)?; | ||
self.exec_state = ExecutionState::ProducingOutput(batch); | ||
if let Some(batch) = self.emit(EmitTo::First(n), false)? { | ||
self.exec_state = ExecutionState::ProducingOutput(batch); | ||
}; | ||
} | ||
Ok(()) | ||
} | ||
|
@@ -1019,7 +1034,9 @@ impl GroupedHashAggregateStream { | |
/// Conduct a streaming merge sort between the batch and spilled data. Since the stream is fully | ||
/// sorted, set `self.group_ordering` to Full, then later we can read with [`EmitTo::First`]. | ||
fn update_merged_stream(&mut self) -> Result<()> { | ||
let batch = self.emit(EmitTo::All, true)?; | ||
let Some(batch) = self.emit(EmitTo::All, true)? else { | ||
return Ok(()); | ||
}; | ||
// clear up memory for streaming_merge | ||
self.clear_all(); | ||
self.update_memory_reservation()?; | ||
|
@@ -1067,7 +1084,7 @@ impl GroupedHashAggregateStream { | |
let timer = elapsed_compute.timer(); | ||
self.exec_state = if self.spill_state.spills.is_empty() { | ||
let batch = self.emit(EmitTo::All, false)?; | ||
ExecutionState::ProducingOutput(batch) | ||
batch.map_or(ExecutionState::Done, ExecutionState::ProducingOutput) | ||
} else { | ||
// If spill files exist, stream-merge them. | ||
self.update_merged_stream()?; | ||
|
@@ -1096,8 +1113,9 @@ impl GroupedHashAggregateStream { | |
fn switch_to_skip_aggregation(&mut self) -> Result<()> { | ||
if let Some(probe) = self.skip_aggregation_probe.as_mut() { | ||
if probe.should_skip() { | ||
let batch = self.emit(EmitTo::All, false)?; | ||
self.exec_state = ExecutionState::ProducingOutput(batch); | ||
if let Some(batch) = self.emit(EmitTo::All, false)? { | ||
self.exec_state = ExecutionState::ProducingOutput(batch); | ||
}; | ||
} | ||
} | ||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
|
@@ -363,31 +363,31 @@ impl PartialSortStream { | |||||
if self.is_closed { | ||||||
return Poll::Ready(None); | ||||||
} | ||||||
let result = match ready!(self.input.poll_next_unpin(cx)) { | ||||||
Some(Ok(batch)) => { | ||||||
if let Some(slice_point) = | ||||||
self.get_slice_point(self.common_prefix_length, &batch)? | ||||||
{ | ||||||
self.in_mem_batches.push(batch.slice(0, slice_point)); | ||||||
let remaining_batch = | ||||||
batch.slice(slice_point, batch.num_rows() - slice_point); | ||||||
let sorted_batch = self.sort_in_mem_batches(); | ||||||
self.in_mem_batches.push(remaining_batch); | ||||||
sorted_batch | ||||||
} else { | ||||||
self.in_mem_batches.push(batch); | ||||||
Ok(RecordBatch::new_empty(self.schema())) | ||||||
loop { | ||||||
return Poll::Ready(Some(match ready!(self.input.poll_next_unpin(cx)) { | ||||||
Some(Ok(batch)) => { | ||||||
if let Some(slice_point) = | ||||||
self.get_slice_point(self.common_prefix_length, &batch)? | ||||||
{ | ||||||
self.in_mem_batches.push(batch.slice(0, slice_point)); | ||||||
let remaining_batch = | ||||||
batch.slice(slice_point, batch.num_rows() - slice_point); | ||||||
let sorted_batch = self.sort_in_mem_batches(); | ||||||
self.in_mem_batches.push(remaining_batch); | ||||||
sorted_batch | ||||||
} else { | ||||||
self.in_mem_batches.push(batch); | ||||||
continue; | ||||||
} | ||||||
} | ||||||
} | ||||||
Some(Err(e)) => Err(e), | ||||||
None => { | ||||||
self.is_closed = true; | ||||||
// once input is consumed, sort the rest of the inserted batches | ||||||
self.sort_in_mem_batches() | ||||||
} | ||||||
}; | ||||||
|
||||||
Poll::Ready(Some(result)) | ||||||
Some(Err(e)) => Err(e), | ||||||
None => { | ||||||
self.is_closed = true; | ||||||
// once input is consumed, sort the rest of the inserted batches | ||||||
self.sort_in_mem_batches() | ||||||
} | ||||||
})); | ||||||
} | ||||||
} | ||||||
|
||||||
/// Returns a sorted RecordBatch from in_mem_batches and clears in_mem_batches | ||||||
|
@@ -407,6 +407,9 @@ impl PartialSortStream { | |||||
self.is_closed = true; | ||||||
} | ||||||
} | ||||||
// Empty record batches should not be emitted. | ||||||
// They need to be treated as [`Option<RecordBatch>`]es and handle separately | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
debug_assert!(result.num_rows() > 0); | ||||||
Ok(result) | ||||||
} | ||||||
|
||||||
|
@@ -731,7 +734,7 @@ mod tests { | |||||
let result = collect(partial_sort_exec, Arc::clone(&task_ctx)).await?; | ||||||
assert_eq!( | ||||||
result.iter().map(|r| r.num_rows()).collect_vec(), | ||||||
[0, 125, 125, 0, 150] | ||||||
[125, 125, 150] | ||||||
); | ||||||
|
||||||
assert_eq!( | ||||||
|
@@ -760,10 +763,10 @@ mod tests { | |||||
nulls_first: false, | ||||||
}; | ||||||
for (fetch_size, expected_batch_num_rows) in [ | ||||||
(Some(50), vec![0, 50]), | ||||||
(Some(120), vec![0, 120]), | ||||||
(Some(150), vec![0, 125, 25]), | ||||||
(Some(250), vec![0, 125, 125]), | ||||||
(Some(50), vec![50]), | ||||||
(Some(120), vec![120]), | ||||||
(Some(150), vec![125, 25]), | ||||||
(Some(250), vec![125, 125]), | ||||||
] { | ||||||
let partial_sort_executor = PartialSortExec::new( | ||||||
LexOrdering::new(vec![ | ||||||
|
@@ -810,6 +813,42 @@ mod tests { | |||||
Ok(()) | ||||||
} | ||||||
|
||||||
#[tokio::test] | ||||||
async fn test_partial_sort_no_empty_batches() -> Result<()> { | ||||||
let task_ctx = Arc::new(TaskContext::default()); | ||||||
let mem_exec = prepare_partitioned_input(); | ||||||
let schema = mem_exec.schema(); | ||||||
let option_asc = SortOptions { | ||||||
descending: false, | ||||||
nulls_first: false, | ||||||
}; | ||||||
let fetch_size = Some(250); | ||||||
let partial_sort_executor = PartialSortExec::new( | ||||||
LexOrdering::new(vec![ | ||||||
PhysicalSortExpr { | ||||||
expr: col("a", &schema)?, | ||||||
options: option_asc, | ||||||
}, | ||||||
PhysicalSortExpr { | ||||||
expr: col("c", &schema)?, | ||||||
options: option_asc, | ||||||
}, | ||||||
]), | ||||||
Arc::clone(&mem_exec), | ||||||
1, | ||||||
) | ||||||
.with_fetch(fetch_size); | ||||||
|
||||||
let partial_sort_exec = | ||||||
Arc::new(partial_sort_executor.clone()) as Arc<dyn ExecutionPlan>; | ||||||
let result = collect(partial_sort_exec, Arc::clone(&task_ctx)).await?; | ||||||
for rb in result { | ||||||
assert!(rb.num_rows() > 0); | ||||||
} | ||||||
|
||||||
Ok(()) | ||||||
} | ||||||
|
||||||
#[tokio::test] | ||||||
async fn test_sort_metadata() -> Result<()> { | ||||||
let task_ctx = Arc::new(TaskContext::default()); | ||||||
|
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
👍