ranflarion opened a new issue, #28024:
URL: https://github.com/apache/datafusion/issues/28024

   ### Describe the bug
   
   The sort-merge join's materializing stream (Inner, Left, Right, Full) 
reserves memory for each buffered batch by 
`RecordBatch::get_array_memory_size()` plus `get_array_memory_size()` of each 
key array (`BufferedBatch::try_new`). That counts an allocation once for every 
buffer that views it. A batch decoded from uncompressed Arrow IPC keeps all its 
columns in the one allocation that holds the message body, so every column is 
charged the whole body and a batch of N columns is reserved about N times its 
size. Such batches come from Arrow file scans and from uncompressed spill 
files, which is the default `datafusion.execution.spill_compression`. A sort 
whose spilled runs end up in a single spill file hands the batches it reads 
back from that file on unchanged (the `(1, 0)` case in 
`MultiLevelMergeBuilder`), so a join above a spilling sort can receive them 
too. A 16-column `Int64` batch read back from an uncompressed spill file 
reports 16,778,752 bytes from `get_array_memory_size()` ag
 ainst 1,048,576 allocated.
   
   The key arrays are usually the batch's own columns, so they are counted a 
second time even when no buffer is shared.
   
   The join then spills batches that fit, or fails when spilling is disabled. 
In a production job joining rows of about 10,500 columns, the join's 
reservation reached 6.0 GB while it held about two buffered batches.
   
   ### To Reproduce
   
   A sort-merge join over an Arrow file of 8 batches, each 8,192 rows of a 
unique sorted key and 64 `Int64` columns (4.3 MB). The keys are unique, so the 
join holds one or two buffered batches at a time. Output on main (a46ac133b):
   
   ```
   64 MB pool, spilling false: Execution error: Additional allocation failed 
for SMJStream[0] with top memory consumers (across reservations) as:
     ExternalSorter[0]#0(can spill: true) consumed 0.0 B, peak 64.0 B,
     ExternalSorterMerge[0]#1(can spill: false) consumed 0.0 B, peak 0.0 B,
     SMJStream[0]#3(can spill: true) consumed 0.0 B, peak 0.0 B.
   Error: Failed to allocate additional 268.4 MB for SMJStream[0] with 0.0 B 
already allocated for this reservation - 64.0 MB remain available for the total 
memory pool: greedy(used: 0.0 B, pool_size: 64.0 MB). Disk spilling disabled.
   64 MB pool, spilling true: peak_mem_used 285699960, spill_count 8, 
spilled_bytes 34130112
   4096 MB pool, spilling false: peak_mem_used 562873520, spill_count 0, 
spilled_bytes 0
   ```
   
   <details><summary>Reproducer</summary>
   
   Save as `datafusion/core/tests/smj_shared_allocation.rs` and run `cargo test 
-p datafusion --test smj_shared_allocation -- --nocapture`.
   
   ```rust
   use std::sync::Arc;
   
   use arrow::array::{ArrayRef, Int64Array, RecordBatch};
   use arrow::compute::SortOptions;
   use arrow::ipc::writer::FileWriter;
   use datafusion::common::{JoinType, NullEquality, Result};
   use datafusion::execution::disk_manager::{DiskManagerBuilder, 
DiskManagerMode};
   use datafusion::execution::runtime_env::RuntimeEnvBuilder;
   use datafusion::physical_expr::expressions::Column;
   use datafusion::physical_plan::joins::SortMergeJoinExec;
   use datafusion::physical_plan::{ExecutionPlan, collect};
   use datafusion::prelude::{SessionConfig, SessionContext};
   
   #[tokio::test]
   async fn sort_merge_join_over_arrow_file() -> Result<()> {
       // 8 batches of 8,192 rows: a unique sorted key and 64 Int64 columns, 
4.3 MB each
       let dir = tempfile::tempdir()?;
       let path = dir.path().join("wide.arrow");
       let rows = 8192_i64;
       let mut writer: Option<FileWriter<std::fs::File>> = None;
       for b in 0..8 {
           let keys = b * rows..(b + 1) * rows;
           let mut columns: Vec<(String, ArrayRef)> = vec![(
               "k".to_string(),
               Arc::new(Int64Array::from_iter_values(keys.clone())),
           )];
           for c in 0..64 {
               let values = keys.clone().map(|v| v * (c + 1));
               columns.push((
                   format!("c{c}"),
                   Arc::new(Int64Array::from_iter_values(values)),
               ));
           }
           let batch = RecordBatch::try_from_iter(columns)?;
           if writer.is_none() {
               let file = std::fs::File::create(&path)?;
               writer = Some(FileWriter::try_new(file, &batch.schema())?);
           }
           writer.as_mut().unwrap().write(&batch)?;
       }
       writer.unwrap().finish()?;
   
       for (pool_mb, spilling) in [(64, false), (64, true), (4096, false)] {
           let mut runtime = RuntimeEnvBuilder::new().with_memory_limit(pool_mb 
<< 20, 1.0);
           if !spilling {
               runtime = runtime.with_disk_manager_builder(
                   
DiskManagerBuilder::default().with_mode(DiskManagerMode::Disabled),
               );
           }
           let config = SessionConfig::new().with_target_partitions(1);
           let ctx = SessionContext::new_with_config_rt(config, 
runtime.build_arc()?);
           ctx.sql(&format!(
               "CREATE EXTERNAL TABLE wide STORED AS ARROW LOCATION '{}' WITH 
ORDER (k ASC)",
               path.display()
           ))
           .await?
           .collect()
           .await?;
           let right = ctx.sql("SELECT * FROM wide").await?;
           let left = ctx
               .sql("SELECT column1 AS k FROM (VALUES (5), (10000), (40000), 
(60000)) ORDER BY k")
               .await?;
           let (left, right) = (
               left.create_physical_plan().await?,
               right.create_physical_plan().await?,
           );
           let on = vec![(
               Arc::new(Column::new_with_schema("k", &left.schema())?) as _,
               Arc::new(Column::new_with_schema("k", &right.schema())?) as _,
           )];
           let join = Arc::new(SortMergeJoinExec::try_new(
               left,
               right,
               on,
               None,
               JoinType::Inner,
               vec![SortOptions::default()],
               NullEquality::NullEqualsNothing,
           )?);
           let result = collect(Arc::clone(&join) as _, ctx.task_ctx()).await;
           let metrics = join.metrics().unwrap();
           match result {
               Ok(_) => println!(
                   "{pool_mb} MB pool, spilling {spilling}: peak_mem_used {}, 
spill_count {}, spilled_bytes {}",
                   metrics.sum_by_name("peak_mem_used").unwrap().as_usize(),
                   metrics.spill_count().unwrap(),
                   metrics.spilled_bytes().unwrap(),
               ),
               Err(e) => println!("{pool_mb} MB pool, spilling {spilling}: 
{e}"),
           }
       }
       Ok(())
   }
   ```
   
   </details>
   
   ### Expected behavior
   
   The join reserves the memory its buffered batches hold. Counting each 
allocation once, the same run peaks at 8,657,328 bytes in all three 
configurations and never spills.
   
   ### Additional context
   
   `get_record_batch_memory_size` and `RecordBatchMemoryCounter` already count 
each allocation once, and the sort and the hash join size their batches with 
them.
   
   The semi/anti/mark `BitwiseSortMergeJoinStream` sizes its buffered key-group 
slices with `get_array_memory_size()` too (`buffer_inner_key_group`).
   
   ### Willingness to contribute
   
   I plan to contribute a fix for this bug independently
   


-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to