Repository navigation
Conversation
| let mut buf = MutableBuffer::from_len_zeroed(total_len); | ||
| reader.read_exact(&mut buf)?; | ||
| let mut buf = MutableBuffer::with_capacity(total_len); | ||
| // Buffer is immediately fully initialized by `read_exact` before any read occurs |
There was a problem hiding this comment.
Strictly speaking, this is not sound for arbitrary Read implementations. Unfortunately, nothing would prevent a Read impl from reading the uninitialized bytes in buf, causing undefined behavior. For a known implementation like File this pattern could be fine though.
An alternative could be to combine take and read_to_end to read into a Vec, but note that this changes the alignment of the resulting Buffer:
let mut buf = Vec::with_capacity(total_len);
reader.take(total_len as u64).read_to_end(&mut buf)?;
if buf.len() != total_len {
return Err(...)
}
Ok(buf.into())There was a problem hiding this comment.
Thanks for the reply @jhorstmann , so I dug into this a bit more and agree the set_len + read_exact approach isn’t suitable for generic Read.
While looking into alternatives, I came across the newer read_buf API using BorrowedBuf, which is designed specifically for reading into uninitialized memory safely. It seems like it would let us avoid the zero-fill while still preserving alignment via MutableBuffer.
Something like:
use std::io::{Read, BorrowedBuf};
let mut buf = MutableBuffer::with_capacity(total_len);
{
let spare = buf.spare_capacity_mut();
let mut borrowed = BorrowedBuf::from(spare);
reader.read_buf_exact(borrowed)?;
}
unsafe { buf.set_len(total_len) };There was a problem hiding this comment.
so it seems to be that the read_buf is a nightly api and so may not be compatible with stable rust, so I'm unsure about it.
There was a problem hiding this comment.
Thanks @jhorstmann and @alamb — I revisited this and reworked my approach to avoid unsafe entirely.
The earlier set_len + read_exact pattern is not sound for generic Read. A fully safe alternative must also account for alignment: Arrow buffers require 64-byte alignment (arrow_buffer::buffer::ALIGNMENT), while Vec<u8> does not guarantee this.
To handle both safely:
- read into
Vec<u8>viatake(...).read_to_end(...)(works for allRead) - reuse the allocation only if it is 64-byte aligned
- otherwise copy into
MutableBuffer::from_len_zeroed(...)to ensure proper alignment
To avoid overhead on small reads, my implementation retains the existing path for smaller buffer sizes and applies the optimized path only to larger buffers (8192 bytes or higher), which constitute the majority of cases in the benchmark.
Benchmark (official ipc_reader)
cargo bench -p arrow-ipc --bench ipc_reader --features zstdStreamReader/read_10 ~910 µs → ~772 µs (~15% faster)
StreamReader/no_validation ~441 µs → ~300 µs (~32% faster)
FileReader/read_10 ~900 µs → ~773 µs (~14% faster)
FileReader/no_validation ~576 µs → ~300 µs (~48% faster)
zstd cases: small but consistent improvements
mmap: unchanged or slightly improved
2a3d9bc to
b8bad7c
Compare
|
run benchmark ipc_reader |
alamb
left a comment
There was a problem hiding this comment.
Thanks @pchintar -- using Vec and Vec::read_exact sounds like a great optimization to me
I don't really understand the reason to keep any of the other MutableBuffer based paths though -- i think we can simplify this PR significantly (and probably make it faster) if it always uses Vec
| let mut buf = MutableBuffer::from_len_zeroed(total_len); | ||
| reader.read_exact(&mut buf)?; | ||
| Ok(buf.into()) | ||
| if total_len < 8 * 1024 { |
There was a problem hiding this comment.
Did you benchmark always using Vec? Vec is pretty fast so it might be better to always use the Vec path 🤔
| if ((vec.as_ptr() as usize) & 63) == 0 { | ||
| Ok(Buffer::from_vec(vec)) | ||
| } else { | ||
| let mut buf = MutableBuffer::from_len_zeroed(total_len); |
There was a problem hiding this comment.
I don't understand why we would ever want to do a second copy? (why not always go directly to a Buffer from. a vec?)
|
🤖 Arrow criterion benchmark running (GKE) | trigger CPU Details (lscpu)Comparing reader-zero-init (8de1dd4) to b93240a (merge-base) diff File an issue against this benchmark runner |
|
🤖 Arrow criterion benchmark completed (GKE) | trigger Instance: CPU Details (lscpu)Details
Resource Usagebase (merge-base)
branch
File an issue against this benchmark runner |
|
Thanks @alamb — this is very helpful. My local results were positive, but the CI benchmark clearly shows the current hybrid approach regresses on this machine, so I simplified this and used the always-`Vec' approach now. i got these results below:
|
|
run benchmark ipc_reader |
|
🤖 Arrow criterion benchmark running (GKE) | trigger CPU Details (lscpu)Comparing reader-zero-init (39bc20a) to b93240a (merge-base) diff File an issue against this benchmark runner |
|
🤖 Arrow criterion benchmark completed (GKE) | trigger Instance: CPU Details (lscpu)Details
Resource Usagebase (merge-base)
branch
File an issue against this benchmark runner |
|
Thanks @alamb — so now it seems to be faster for a majority of cases in Specifically: This indicates that reusing the I’m reverting this change for now and will revisit a safe approach that preserves alignment while avoiding any overhead. |
|
@alamb — quick update. That CI "integration / Archery test With other arrows" check failure was isolated to the The issue was specifically with dense union offsets ( self.next_buffer()?.slice_with_length(...).into()I’ve fixed this by ensuring alignment only for that specific case before converting to let offsets_buffer =
ensure_aligned_for::<i32>(self.next_buffer()?.slice_with_length(...));
let offsets: ScalarBuffer<i32> = offsets_buffer.into();Now all the CI checks have passed without impacting the benchmark improvements 👍 |
|
No additional changes/conditions were added to read_block, maybe_next and next_buffer for this specific So, the fast |
|
@alamb & @adriangbot could you pls for one last time, run benchmark ipc_reader |
|
run benchmark ipc_reader |
|
🤖 Arrow criterion benchmark running (GKE) | trigger CPU Details (lscpu)Comparing reader-zero-init (2f683c7) to 620e39d (merge-base) diff File an issue against this benchmark runner |
|
🤖 Arrow criterion benchmark completed (GKE) | trigger Instance: CPU Details (lscpu)Details
Resource Usagebase (merge-base)
branch
File an issue against this benchmark runner |
|
@alamb the results look good 🙂 and are exactly what I expected: ~12–30% improvement in non-compressed IPC read paths, and no regressions in mmap/zstd cases. |
| UnionMode::Dense => { | ||
| let offsets: ScalarBuffer<i32> = | ||
| self.next_buffer()?.slice_with_length(0, len * 4).into(); | ||
| let offsets_buffer = ensure_aligned_for::<i32>( |
There was a problem hiding this comment.
It is really weird that this extra alignment / copy is needed
There was a problem hiding this comment.
My only concern is that there may be alignment requirements that MutableBuffer satisfies but Vec does not and we just happened to catch this alignment problem with the integration tests.
I wonder if we maybe need to pass in the alignment requirements to next_buffer (e.g. instead of reading in Vec in this case we would read in Vec<i32>) 🤔
alamb
left a comment
There was a problem hiding this comment.
Actually after some more thought I think there may be an alignment problem
| UnionMode::Dense => { | ||
| let offsets: ScalarBuffer<i32> = | ||
| self.next_buffer()?.slice_with_length(0, len * 4).into(); | ||
| let offsets_buffer = ensure_aligned_for::<i32>( |
There was a problem hiding this comment.
My only concern is that there may be alignment requirements that MutableBuffer satisfies but Vec does not and we just happened to catch this alignment problem with the integration tests.
I wonder if we maybe need to pass in the alignment requirements to next_buffer (e.g. instead of reading in Vec in this case we would read in Vec<i32>) 🤔
|
Yes @alamb , w.r.t the alignment concern. I checked this specifically before adding the fix. In The So this is effectively the minimal targeted version of passing the alignment requirement to the buffer access point, without adding checks to the common read path. |
Got it -- this makes sense However, that would then suggest to me that there will be cases where the current code on main does not copy the data (because the initial allocation was correctly aligned) but the new code DOES copy the data (because the allocation This may well not be covered in our benchmarks. |
|
Yes @alamb , that’s a fair point. The only new copy introduced by this fix should be limited to dense union offsets, and only when the Vec-backed body buffer is not aligned for
This is not covered by the current That's why I updated the title earlier from Avoid to now just Reduce zero-initialization 😅 bc complete avoidance might not be possible tbh |
I think it applies more broadly than this -- basically for any type of buffer that requires alignment For example, a UInt64Array can now require another copy (if the Vec wasn't 64 bit aligned). However, this copy happens sliently today because the array builder sorts it out, right? |
|
Yes @alamb , so for other types (e.g. The difference here is that So effectively:
|
|
I share @alamb's concern that in some cases this might now require a copy, where it did not need one before, and these cases are probably not covered by the benchmark. We now rely on the alignment of the global allocator, which could be changed by a user, and which might also depend on the size of the allocation. For smaller ipc message blocks, the allocator might use a smaller alignment. I don't see a good way now to avoid these copies, apart from waiting for improvements in the rust standard library itself (https://github.com/rust-lang/rfcs/blob/master/text/2930-read-buf.md#summary). |
One thing we maybe could do (that woudl be more invasive) would be to add a template parameter to So instead of This would ensure the correct underlying buffer alignment but would take some non trivial changes (e.g. move away from usng ArrowData and instead create the various arrays directly (e.g. PrimtiveArray::new())` |
|
@alamb That makes sense — I looked into this, and implementing Today I think that goes beyond the scope of this PR, but I’m happy to explore it later after my midterms if that direction is preferred. |
Yes I agree with this assement I also agree that would likely require a more substantial PR / refactoring
Thank you -- that sounds good. I'll file a ticket to track the idea |
|
I filed #9777 to track the idea of using Vec instead of Vec and will mark this PR as draft |
|
Thank you very much @pchintar |
|
thank you @alamb |
|
Thank you for your contribution. Unfortunately, this pull request is stale because it has been open 60 days with no activity. Please remove the stale label or comment or this will be closed in 7 days. |
Note that @Rich-T-kid has been working on improving IPC performance (really flight, but it uses the same code path) s maybe he will be interested in some of these dieas |
I must have missed this ping, taking a look 👀 |
I also share this concern, we are very fortunate to have existing intergration test to detect bugs like this. |
I think we should add some new tests to explicitly cover this case, if possible |
@Rich-T-kid is there an issue for whatever problem you ran into? |
@alamb no, i tried removing the buffer copy that occured for every the benchmarks for using a vector directly does look good, if arrow exposed an way to align vectors it would be the best of both worlds due to how many optimziations are built into the vector type. I thought about a possible new type pattern where we wrapped a vector in a byte slice of 64 chunks. #[repr(align(64))]
struct Chunk([u8; 64]);this has the benefit of being aligned when its first created as well as being aligned for re-allocations when the vector grows. If this sounds interesting I could continue working on it |

Which issue does this PR close?
Rationale for this change
In
arrow-ipc/src/reader.rs, buffers are currently allocated withMutableBuffer::from_len_zeroed(len)and then passed toread_exact, which fully overwrites the entire buffer contents.This results in an unnecessary full memory pass for all data bytes:
Since
read_exactguarantees that the provided slice is fully written on success, the initial zeroing step is redundant and can be safely avoided by allocating with capacity and setting the length before the read.What changes are included in this PR?
Use
Vecandread_exactrather thanMutableBufferto avoid zerioningRationale
Are these changes tested?
Yes the changes were tested by CI and performance
Are there any user-facing changes?
No, there are no changes made to any public api code.