ranflarion opened a new issue, #27817:
URL: https://github.com/apache/datafusion/issues/27817
### Is your feature request related to a problem or challenge?
Since #26960 the spill writer copies each run of IPC buffers under 64 KiB
into one `Vec` before writing it, so that a batch takes a few writes instead of
one per buffer. Nothing bounds that `Vec`. A batch whose buffers are all under
64 KiB, such as a wide batch of fixed-width columns or most compressed batches,
is copied whole. The pool does not account for the copy, and it is made while
an operator is spilling because it ran out of memory.
Peak live heap during one `InProgressSpillFile::append_batch`, above the
level just before the call, for batches of 4,096-row `Int64` columns (each
column buffer is 32 KiB):
| batch | uncompressed | zstd | lz4_frame |
|---|---:|---:|---:|
| 206 columns, 6.8 MB | 6.8 MB | 10.2 MB | 14.2 MB |
| 512 columns, 16.8 MB | 27.0 MB | 30.4 MB | 34.5 MB |
An uncompressed spill copies nothing else, since the IPC buffers are the
batch's own, so there the copy is the whole peak, and it can exceed the batch
because the `Vec` grows by doubling. With a codec the peak also includes the
compressed buffers the encoder holds until they are written.
### Describe the solution you'd like
Copy a run of small buffers in pieces of at most 1 MiB, each allocated right
before its write and dropped after it, in both `IPCStreamWriter` and
`AsyncIPCStreamWriter`. With that the same measurement gives:
| batch | uncompressed | zstd | lz4_frame |
|---|---:|---:|---:|
| 206 columns, 6.8 MB | 1.1 MB | 7.9 MB | 15.2 MB |
| 512 columns, 16.8 MB | 1.2 MB | 18.1 MB | 35.4 MB |
`lz4_frame` gains up to 1 MiB: its compressed buffers already peaked above
the old copy, which was built while they were being freed, and a bounded piece
is allocated before the buffers it copies are dropped.
### Describe alternatives you've considered
A smaller bound costs writes. Spilling 30 of the 206-column batches
uncompressed (Apple M4 Pro, best of 25 runs) takes 36 ms on main, 38 ms with
pieces capped at 64 KiB, where every 32 KiB column gets its own write, 27 to 28
ms at 256 KiB and 25 ms at 1 MiB.
A write buffer kept by each open spill file would also bound it, but a
preserve-order `RepartitionExec` keeps one spill file open per input and output
pair, so those buffers add up to memory the pool cannot see (the review of
#26960 measured it), while a per-write copy is alive in one writer at a time.
### Additional context
<details><summary>Reproducer</summary>
Save as `datafusion/physical-plan/tests/spill_peak.rs` and run `cargo test
--release -p datafusion-physical-plan --test spill_peak -- --nocapture`.
```rust
use std::alloc::{GlobalAlloc, Layout, System};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
use arrow::array::{ArrayRef, Int64Array, RecordBatch};
use datafusion_common::config::SpillCompression;
use datafusion_execution::runtime_env::RuntimeEnv;
use datafusion_physical_plan::SpillManager;
use datafusion_physical_plan::metrics::{ExecutionPlanMetricsSet,
SpillMetrics};
struct CountingAllocator;
static LIVE: AtomicUsize = AtomicUsize::new(0);
static PEAK: AtomicUsize = AtomicUsize::new(0);
fn add(bytes: usize) {
PEAK.fetch_max(LIVE.fetch_add(bytes, Relaxed) + bytes, Relaxed);
}
unsafe impl GlobalAlloc for CountingAllocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
add(layout.size());
unsafe { System.alloc(layout) }
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
LIVE.fetch_sub(layout.size(), Relaxed);
unsafe { System.dealloc(ptr, layout) };
}
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, size: usize) ->
*mut u8 {
if size >= layout.size() {
add(size - layout.size());
} else {
LIVE.fetch_sub(layout.size() - size, Relaxed);
}
unsafe { System.realloc(ptr, layout, size) }
}
}
#[global_allocator]
static ALLOCATOR: CountingAllocator = CountingAllocator;
#[test]
fn peak_allocation_of_one_spilled_batch() {
let env = Arc::new(RuntimeEnv::default());
for cols in [206, 512] {
// 4,096 rows of incompressible Int64: every column buffer is 32 KiB
let mut state = 1_u64;
let batch = RecordBatch::try_from_iter((0..cols).map(|col| {
let values = Int64Array::from_iter_values((0..4096).map(|_| {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
state as i64
}));
(format!("c{col}"), Arc::new(values) as ArrayRef)
}))
.unwrap();
for codec in [
SpillCompression::Uncompressed,
SpillCompression::Zstd,
SpillCompression::Lz4Frame,
] {
let metrics = SpillMetrics::new(&ExecutionPlanMetricsSet::new(),
0);
let manager = SpillManager::new(Arc::clone(&env), metrics,
batch.schema())
.with_compression_type(codec);
let mut file = manager.create_in_progress_file("probe").unwrap();
let before = LIVE.load(Relaxed);
PEAK.store(before, Relaxed);
file.append_batch(&batch).unwrap();
println!(
"{cols} columns, {codec}: batch {} bytes, peak {} bytes",
batch.get_array_memory_size(),
PEAK.load(Relaxed) - before
);
file.finish().unwrap();
}
}
}
```
</details>
### Willingness to contribute
I plan to contribute to this feature 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]