You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "2010YOUY01 (via GitHub)" <gi...@apache.org> on 2025/02/22 11:20:21 UTC
[PR] Fix: External sort failing on `StringView` due to shared buffers [datafusion]
2010YOUY01 opened a new pull request, #14823:
URL: https://github.com/apache/datafusion/pull/14823
## Which issue does this PR close?
<!--
We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes #123` indicates that this PR will close issue #123.
-->
Follow up to https://github.com/apache/datafusion/pull/14644, this PR fixes an unsolved failing case for external sort. It's found by https://github.com/apache/datafusion/issues/12136#issuecomment-2656449956.
## Rationale for this change
<!--
Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed.
Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes.
-->
Recap for major steps for external sort (there are detailed doc in datafusion/physical-plan/src/sorts/sort.rs)
1. Inside each partition, input batches will be buffered until it reaches the memory limit.
2. When OOM is triggered, all buffered batches will be sorted one by one, and finally merged into one large sorted run (though physically it's chunked into many small batches)
3. Spill the sorted run to disk. After reading all inputs, read back spilled batches and merge into the final result. Since only one batch is needed for each spilled sorted run to generate the final result, the memory overhead is reduced in this step.
The problem is: if step 2 is done on batches with `StringViewArray` columns, the sorted array will only reorder the `view`s (string prefix plus pointer into range in the payload buffer, if this element is long), and the underlying buffers won't be moved.
When reading back spilled batches from a single sorted run, it's required to read one batch by one batch, otherwise memory pressure won't be reduced. As a result, the spill writer has to write all referenced `buffer`s for each batch, and many buffers will be written multiple times. The size of the spilled batch would explode, and some memory-limited sort query can fail due to this reason.
## Reproducer
Under `benchmarks/`, run
```
cargo run --profile release-nonlto --bin dfbench -- sort-tpch -p '/Users/yongting/Code/datafusion/benchmarks/data/tpch_sf10' -o '/tmp/main.json' -q 10 --iterations 1 --partitions 4 --memory-limit 5000M --debug
```
### Main branch result (20GB spilled)
```
SortExec: expr=[l_orderkey@0 ASC NULLS LAST, l_suppkey@1 ASC NULLS LAST, l_linenumber@2 ASC NULLS LAST, l_comment@3 ASC NULLS LAST], preserve_partitioning=[true], metrics=[output_rows=59986052, elapsed_compute=12.965460651s, spill_count=24, spilled_bytes=19472334146, spilled_rows=51202072]
```
Q10 iteration 0 took 12839.6 ms and returned 59986052 rows
Q10 avg time: 12839.60 ms
### PR result (12GB spilled)
```
SortExec: expr=[l_orderkey@0 ASC NULLS LAST, l_suppkey@1 ASC NULLS LAST, l_linenumber@2 ASC NULLS LAST, l_comment@3 ASC NULLS LAST], preserve_partitioning=[true], metrics=[output_rows=59986052, elapsed_compute=15.363745389s, spill_count=48, spilled_bytes=12600523712, spilled_rows=55216152]
```
Q10 iteration 0 took 9424.3 ms and returned 59986052 rows
Q10 avg time: 9424.33 ms
## What changes are included in this PR?
Before spilling, `StringViewArray` columns must be permutated the way described above, so this PR reorganize the array to sequential order before spilling.
<!--
There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR.
-->
## Are these changes tested?
Added one unit regression test. This test fails without the change.
<!--
We typically require tests for all PRs in order to:
1. Prevent the code from being accidentally broken by subsequent changes
6. Serve as another way to document the expected behavior of the code
If tests are not included in your PR, please explain why (for example, are they covered by existing tests)?
-->
## Are there any user-facing changes?
<!--
If there are user-facing changes then we may require documentation to be updated before approving the PR.
-->
<!--
If there are any breaking changes to public APIs, please add the `api change` label.
-->
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Fix: External sort failing on `StringView` due to shared buffers [datafusion]
Posted by "2010YOUY01 (via GitHub)" <gi...@apache.org>.
2010YOUY01 commented on code in PR #14823:
URL: https://github.com/apache/datafusion/pull/14823#discussion_r1971059228
##########
datafusion/physical-plan/src/sorts/sort.rs:
##########
@@ -1425,7 +1478,7 @@ mod tests {
// Processing 840 KB of data using 400 KB of memory requires at least 2 spills
// It will spill roughly 18000 rows and 800 KBytes.
// We leave a little wiggle room for the actual numbers.
- assert!((2..=10).contains(&spill_count));
+ assert!((12..=18).contains(&spill_count));
Review Comment:
updated in [92ca3b0](https://github.com/apache/datafusion/pull/14823/commits/92ca3b00d99610bd96e4aeed115ae8fcf7cf11b3)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Fix: External sort failing on `StringView` due to shared buffers [datafusion]
Posted by "tustvold (via GitHub)" <gi...@apache.org>.
tustvold commented on PR #14823:
URL: https://github.com/apache/datafusion/pull/14823#issuecomment-2677816002
FWIW I think this compaction logic probably makes sense as part of the IPCWriter, as opposed to a workaround here - https://github.com/apache/arrow-rs/issues/7185
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Fix: External sort failing on `StringView` due to shared buffers [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #14823:
URL: https://github.com/apache/datafusion/pull/14823#issuecomment-2685462913
🚀
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Fix: External sort failing on `StringView` due to shared buffers [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb merged PR #14823:
URL: https://github.com/apache/datafusion/pull/14823
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Fix: External sort failing on `StringView` due to shared buffers [datafusion]
Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on code in PR #14823:
URL: https://github.com/apache/datafusion/pull/14823#discussion_r1966714007
##########
datafusion/physical-plan/src/sorts/sort.rs:
##########
@@ -414,6 +419,66 @@ impl ExternalSorter {
Ok(used)
}
+ /// Reconstruct `self.in_mem_batches` to organize the payload buffers of each
+ /// `StringViewArray` in sequential order by calling `gc()` on them.
+ ///
+ /// # Rationale
+ /// After (merge-based) sorting, all batches will be sorted into a single run,
+ /// but physically this sorted run is chunked into many small batches. For
+ /// `StringViewArray`s inside each sorted run, their inner buffers are not
+ /// re-constructed by default, leading to non-sequential payload locations
+ /// (permutated by `interleave()` Arrow kernel). A single payload buffer might
+ /// be shared by multiple `RecordBatch`es.
+ /// When writing each batch to disk, the writer has to write all referenced buffers,
+ /// because they have to be read back one by one to reduce memory usage. This
+ /// causes extra disk reads and writes, and potentially execution failure.
+ ///
+ /// # Example
+ /// Before sorting:
+ /// batch1 -> buffer1
+ /// batch2 -> buffer2
+ ///
+ /// sorted_batch1 -> buffer1
+ /// -> buffer2
+ /// sorted_batch2 -> buffer1
+ /// -> buffer2
+ ///
+ /// Then when spilling each batch, the writer has to write all referenced buffers
+ /// repeatedly.
+ fn organize_stringview_arrays(&mut self) -> Result<()> {
+ let mut organized_batches = Vec::with_capacity(self.in_mem_batches.len());
+
+ for batch in self.in_mem_batches.drain(..) {
+ let mut new_columns: Vec<Arc<dyn Array>> =
+ Vec::with_capacity(batch.num_columns());
+
+ let mut arr_mutated = false;
+ for array in batch.columns() {
+ if let Some(string_view_array) =
+ array.as_any().downcast_ref::<StringViewArray>()
+ {
+ let new_array = string_view_array.gc();
Review Comment:
Will string_view_array.gc() affect the performance when it call many times?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Fix: External sort failing on `StringView` due to shared buffers [datafusion]
Posted by "2010YOUY01 (via GitHub)" <gi...@apache.org>.
2010YOUY01 commented on code in PR #14823:
URL: https://github.com/apache/datafusion/pull/14823#discussion_r1966496849
##########
datafusion/physical-plan/src/sorts/sort.rs:
##########
@@ -446,21 +511,9 @@ impl ExternalSorter {
None => {
let sorted_size = get_reserved_byte_for_record_batch(&batch);
if self.reservation.try_grow(sorted_size).is_err() {
- // Directly write in_mem_batches as well as all the remaining batches in
- // sorted_stream to disk. Further batches fetched from `sorted_stream` will
- // be handled by the `Some(writer)` matching arm.
- let spill_file =
- self.runtime.disk_manager.create_tmp_file("Sorting")?;
- let mut writer = IPCWriter::new(spill_file.path(), &self.schema)?;
- // Flush everything in memory to the spill file
- for batch in self.in_mem_batches.drain(..) {
- writer.write(&batch)?;
- }
- // as well as the newly sorted batch
- writer.write(&batch)?;
- spill_writer = Some(writer);
+ self.in_mem_batches.push(batch);
+ self.spill().await?;
Review Comment:
This refactor is not related to the PR, I did this along the way.
##########
datafusion/physical-plan/src/sorts/sort.rs:
##########
@@ -1425,7 +1478,7 @@ mod tests {
// Processing 840 KB of data using 400 KB of memory requires at least 2 spills
// It will spill roughly 18000 rows and 800 KBytes.
// We leave a little wiggle room for the actual numbers.
- assert!((2..=10).contains(&spill_count));
+ assert!((12..=18).contains(&spill_count));
Review Comment:
This is caused by the above refactor, the old implementation forget to update the statistics, so we missed several counts.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Fix: External sort failing on `StringView` due to shared buffers [datafusion]
Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on code in PR #14823:
URL: https://github.com/apache/datafusion/pull/14823#discussion_r1966528251
##########
datafusion/physical-plan/src/sorts/sort.rs:
##########
@@ -446,21 +511,9 @@ impl ExternalSorter {
None => {
let sorted_size = get_reserved_byte_for_record_batch(&batch);
if self.reservation.try_grow(sorted_size).is_err() {
- // Directly write in_mem_batches as well as all the remaining batches in
- // sorted_stream to disk. Further batches fetched from `sorted_stream` will
- // be handled by the `Some(writer)` matching arm.
- let spill_file =
- self.runtime.disk_manager.create_tmp_file("Sorting")?;
- let mut writer = IPCWriter::new(spill_file.path(), &self.schema)?;
- // Flush everything in memory to the spill file
- for batch in self.in_mem_batches.drain(..) {
- writer.write(&batch)?;
- }
- // as well as the newly sorted batch
- writer.write(&batch)?;
- spill_writer = Some(writer);
+ self.in_mem_batches.push(batch);
+ self.spill().await?;
Review Comment:
Do we need to keep the original logic:
1. self.spill().await?;
2. And then write the remaining batch to disk.
Because the self.in_mem_batches.push(batch) may cause OOM for memory?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Fix: External sort failing on `StringView` due to shared buffers [datafusion]
Posted by "2010YOUY01 (via GitHub)" <gi...@apache.org>.
2010YOUY01 commented on PR #14823:
URL: https://github.com/apache/datafusion/pull/14823#issuecomment-2684140744
Thank you all for the feedbacks. I have addressed the review comments (also added a small further simplification for the refactor)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Fix: External sort failing on `StringView` due to shared buffers [datafusion]
Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on code in PR #14823:
URL: https://github.com/apache/datafusion/pull/14823#discussion_r1966820859
##########
datafusion/physical-plan/src/sorts/sort.rs:
##########
@@ -414,6 +419,66 @@ impl ExternalSorter {
Ok(used)
}
+ /// Reconstruct `self.in_mem_batches` to organize the payload buffers of each
+ /// `StringViewArray` in sequential order by calling `gc()` on them.
+ ///
+ /// # Rationale
+ /// After (merge-based) sorting, all batches will be sorted into a single run,
+ /// but physically this sorted run is chunked into many small batches. For
+ /// `StringViewArray`s inside each sorted run, their inner buffers are not
+ /// re-constructed by default, leading to non-sequential payload locations
+ /// (permutated by `interleave()` Arrow kernel). A single payload buffer might
+ /// be shared by multiple `RecordBatch`es.
+ /// When writing each batch to disk, the writer has to write all referenced buffers,
+ /// because they have to be read back one by one to reduce memory usage. This
+ /// causes extra disk reads and writes, and potentially execution failure.
+ ///
+ /// # Example
+ /// Before sorting:
+ /// batch1 -> buffer1
+ /// batch2 -> buffer2
+ ///
+ /// sorted_batch1 -> buffer1
+ /// -> buffer2
+ /// sorted_batch2 -> buffer1
+ /// -> buffer2
+ ///
+ /// Then when spilling each batch, the writer has to write all referenced buffers
+ /// repeatedly.
+ fn organize_stringview_arrays(&mut self) -> Result<()> {
+ let mut organized_batches = Vec::with_capacity(self.in_mem_batches.len());
+
+ for batch in self.in_mem_batches.drain(..) {
+ let mut new_columns: Vec<Arc<dyn Array>> =
+ Vec::with_capacity(batch.num_columns());
+
+ let mut arr_mutated = false;
+ for array in batch.columns() {
+ if let Some(string_view_array) =
+ array.as_any().downcast_ref::<StringViewArray>()
+ {
+ let new_array = string_view_array.gc();
Review Comment:
Updated, if i make sense right, it seems not too much affection to performance, because we only remain the used buffer data?
before gc:
/// sorted_batch1 -> buffer1
/// -> buffer2
/// sorted_batch2 -> buffer1
/// -> buffer2
after gc:
/// sorted_batch1 -> new buffer (used data of buffer1, used data of buffer2)
/// sorted_batch2 -> new buffer (used data of buffer1, used data of buffer2)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Fix: External sort failing on `StringView` due to shared buffers [datafusion]
Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on code in PR #14823:
URL: https://github.com/apache/datafusion/pull/14823#discussion_r1966670496
##########
datafusion/physical-plan/src/sorts/sort.rs:
##########
@@ -446,21 +511,9 @@ impl ExternalSorter {
None => {
let sorted_size = get_reserved_byte_for_record_batch(&batch);
if self.reservation.try_grow(sorted_size).is_err() {
- // Directly write in_mem_batches as well as all the remaining batches in
- // sorted_stream to disk. Further batches fetched from `sorted_stream` will
- // be handled by the `Some(writer)` matching arm.
- let spill_file =
- self.runtime.disk_manager.create_tmp_file("Sorting")?;
- let mut writer = IPCWriter::new(spill_file.path(), &self.schema)?;
- // Flush everything in memory to the spill file
- for batch in self.in_mem_batches.drain(..) {
- writer.write(&batch)?;
- }
- // as well as the newly sorted batch
- writer.write(&batch)?;
- spill_writer = Some(writer);
+ self.in_mem_batches.push(batch);
+ self.spill().await?;
Review Comment:
Thank you @2010YOUY01 for explain, got it, i was wrong, so we do not have internal mechanism to update reservation. If we have a RAII way to improve it in the future, this is a great idea, may be we can file a ticket for it!
> `in_mem_batches` is a `Vec<RecordBatch>`, so it doesn't have any internal mechanism to update reservation. Also, the new `batch` is already in memory, so there is no difference to spill together or not. I added a comment for this. Besides, I think manually keep the buffered batch in sync with reservation is quite tricky, it makes the implementation hard to reason and perhaps cause bugs, hopefully we can find a RAII way to improve it in the future.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Fix: External sort failing on `StringView` due to shared buffers [datafusion]
Posted by "2010YOUY01 (via GitHub)" <gi...@apache.org>.
2010YOUY01 commented on code in PR #14823:
URL: https://github.com/apache/datafusion/pull/14823#discussion_r1967214234
##########
datafusion/physical-plan/src/sorts/sort.rs:
##########
@@ -414,6 +419,66 @@ impl ExternalSorter {
Ok(used)
}
+ /// Reconstruct `self.in_mem_batches` to organize the payload buffers of each
+ /// `StringViewArray` in sequential order by calling `gc()` on them.
+ ///
+ /// # Rationale
+ /// After (merge-based) sorting, all batches will be sorted into a single run,
+ /// but physically this sorted run is chunked into many small batches. For
+ /// `StringViewArray`s inside each sorted run, their inner buffers are not
+ /// re-constructed by default, leading to non-sequential payload locations
+ /// (permutated by `interleave()` Arrow kernel). A single payload buffer might
+ /// be shared by multiple `RecordBatch`es.
+ /// When writing each batch to disk, the writer has to write all referenced buffers,
+ /// because they have to be read back one by one to reduce memory usage. This
+ /// causes extra disk reads and writes, and potentially execution failure.
+ ///
+ /// # Example
+ /// Before sorting:
+ /// batch1 -> buffer1
+ /// batch2 -> buffer2
+ ///
+ /// sorted_batch1 -> buffer1
+ /// -> buffer2
+ /// sorted_batch2 -> buffer1
+ /// -> buffer2
+ ///
+ /// Then when spilling each batch, the writer has to write all referenced buffers
+ /// repeatedly.
+ fn organize_stringview_arrays(&mut self) -> Result<()> {
+ let mut organized_batches = Vec::with_capacity(self.in_mem_batches.len());
+
+ for batch in self.in_mem_batches.drain(..) {
+ let mut new_columns: Vec<Arc<dyn Array>> =
+ Vec::with_capacity(batch.num_columns());
+
+ let mut arr_mutated = false;
+ for array in batch.columns() {
+ if let Some(string_view_array) =
+ array.as_any().downcast_ref::<StringViewArray>()
+ {
+ let new_array = string_view_array.gc();
Review Comment:
Good point, there is some inefficiency here, I filed https://github.com/apache/arrow-rs/issues/7184. Once done on `arrow` side, we can remove the copies here to speed it up.
IMO it won't cause regression for datafusion, it's only done when the spill is triggered, and if we don't copy here it can cause larger inefficiency or fail some memory-limited sort queries.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Fix: External sort failing on `StringView` due to shared buffers [datafusion]
Posted by "2010YOUY01 (via GitHub)" <gi...@apache.org>.
2010YOUY01 commented on code in PR #14823:
URL: https://github.com/apache/datafusion/pull/14823#discussion_r1967214234
##########
datafusion/physical-plan/src/sorts/sort.rs:
##########
@@ -414,6 +419,66 @@ impl ExternalSorter {
Ok(used)
}
+ /// Reconstruct `self.in_mem_batches` to organize the payload buffers of each
+ /// `StringViewArray` in sequential order by calling `gc()` on them.
+ ///
+ /// # Rationale
+ /// After (merge-based) sorting, all batches will be sorted into a single run,
+ /// but physically this sorted run is chunked into many small batches. For
+ /// `StringViewArray`s inside each sorted run, their inner buffers are not
+ /// re-constructed by default, leading to non-sequential payload locations
+ /// (permutated by `interleave()` Arrow kernel). A single payload buffer might
+ /// be shared by multiple `RecordBatch`es.
+ /// When writing each batch to disk, the writer has to write all referenced buffers,
+ /// because they have to be read back one by one to reduce memory usage. This
+ /// causes extra disk reads and writes, and potentially execution failure.
+ ///
+ /// # Example
+ /// Before sorting:
+ /// batch1 -> buffer1
+ /// batch2 -> buffer2
+ ///
+ /// sorted_batch1 -> buffer1
+ /// -> buffer2
+ /// sorted_batch2 -> buffer1
+ /// -> buffer2
+ ///
+ /// Then when spilling each batch, the writer has to write all referenced buffers
+ /// repeatedly.
+ fn organize_stringview_arrays(&mut self) -> Result<()> {
+ let mut organized_batches = Vec::with_capacity(self.in_mem_batches.len());
+
+ for batch in self.in_mem_batches.drain(..) {
+ let mut new_columns: Vec<Arc<dyn Array>> =
+ Vec::with_capacity(batch.num_columns());
+
+ let mut arr_mutated = false;
+ for array in batch.columns() {
+ if let Some(string_view_array) =
+ array.as_any().downcast_ref::<StringViewArray>()
+ {
+ let new_array = string_view_array.gc();
Review Comment:
Good point, there is some inefficiency here, I filed https://github.com/apache/arrow-rs/issues/7184. Once done on `arrow` side, we can remove the copies here to speed it up.
IMO it won't cause regression for datafusion, it's only done when the spill is triggered, and if we don't copy here it can cause larger inefficiency and correctness issues.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Fix: External sort failing on `StringView` due to shared buffers [datafusion]
Posted by "2010YOUY01 (via GitHub)" <gi...@apache.org>.
2010YOUY01 commented on code in PR #14823:
URL: https://github.com/apache/datafusion/pull/14823#discussion_r1966660694
##########
datafusion/physical-plan/src/sorts/sort.rs:
##########
@@ -446,21 +511,9 @@ impl ExternalSorter {
None => {
let sorted_size = get_reserved_byte_for_record_batch(&batch);
if self.reservation.try_grow(sorted_size).is_err() {
- // Directly write in_mem_batches as well as all the remaining batches in
- // sorted_stream to disk. Further batches fetched from `sorted_stream` will
- // be handled by the `Some(writer)` matching arm.
- let spill_file =
- self.runtime.disk_manager.create_tmp_file("Sorting")?;
- let mut writer = IPCWriter::new(spill_file.path(), &self.schema)?;
- // Flush everything in memory to the spill file
- for batch in self.in_mem_batches.drain(..) {
- writer.write(&batch)?;
- }
- // as well as the newly sorted batch
- writer.write(&batch)?;
- spill_writer = Some(writer);
+ self.in_mem_batches.push(batch);
+ self.spill().await?;
Review Comment:
`in_mem_batches` is a `Vec<RecordBatch>`, so it doesn't have any internal mechanism to update reservation. Also, the new `batch` is already in memory, so there is no difference to spill together or not. I added a comment for this.
Besides, I think manually keep the buffered batch in sync with reservation is quite tricky, it makes the implementation hard to reason and perhaps cause bugs, hopefully we can find a RAII way to improve it in the future.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Fix: External sort failing on `StringView` due to shared buffers [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #14823:
URL: https://github.com/apache/datafusion/pull/14823#discussion_r1970437292
##########
datafusion/physical-plan/src/sorts/sort.rs:
##########
@@ -414,6 +419,66 @@ impl ExternalSorter {
Ok(used)
}
+ /// Reconstruct `self.in_mem_batches` to organize the payload buffers of each
+ /// `StringViewArray` in sequential order by calling `gc()` on them.
+ ///
Review Comment:
```suggestion
///
/// Note this is a workaround until <https://github.com/apache/arrow-rs/issues/7185> is
/// available
///
```
##########
datafusion/physical-plan/src/sorts/sort.rs:
##########
@@ -1425,7 +1478,7 @@ mod tests {
// Processing 840 KB of data using 400 KB of memory requires at least 2 spills
// It will spill roughly 18000 rows and 800 KBytes.
// We leave a little wiggle room for the actual numbers.
- assert!((2..=10).contains(&spill_count));
+ assert!((12..=18).contains(&spill_count));
Review Comment:
Should we also update the comments?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org