Skip to content

feat(ipc): Reduce redundant zero-initialization in IPC reader - #9778

Closed
pchintar wants to merge 6 commits into
apache:mainfrom
pchintar:reader-zero-init
Closed

pchintar wants to merge 6 commits into
apache:mainfrom
pchintar:reader-zero-init

Conversation

@pchintar

@pchintar pchintar commented Apr 21, 2026 •

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

Rationale for this change

In arrow-ipc/src/reader.rs, buffers are currently allocated with MutableBuffer::from_len_zeroed(len) and then passed to read_exact, which fully overwrites the entire buffer contents.

This results in an unnecessary full memory pass for all data bytes:

  • first zero-initialization
  • then complete overwrite by the incoming data

Since read_exact guarantees 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 Vec and read_exact rather than MutableBuffer to avoid zerioning

Rationale

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.

@github-actions github-actions Bot added the arrow Changes to the arrow crate label Apr 21, 2026
Comment thread arrow-ipc/src/reader.rs Outdated
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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())

@pchintar pchintar Apr 21, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) };

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@pchintar pchintar Apr 23, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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> via take(...).read_to_end(...) (works for all Read)
  • 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 zstd
StreamReader/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

@alamb
alamb marked this pull request as draft April 22, 2026 13:31
@pchintar pchintar changed the title feat(ipc): Remove zero-initialization in IPC reader feat(ipc): Reduce redundant zero-initialization in IPC reader Apr 23, 2026
@alamb alamb added the performance Speed or memory optimizations label Apr 23, 2026
@alamb

alamb commented Apr 23, 2026

Copy link
Copy Markdown
Contributor

run benchmark ipc_reader

@alamb alamb left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread arrow-ipc/src/reader.rs Outdated
let mut buf = MutableBuffer::from_len_zeroed(total_len);
reader.read_exact(&mut buf)?;
Ok(buf.into())
if total_len < 8 * 1024 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Did you benchmark always using Vec? Vec is pretty fast so it might be better to always use the Vec path 🤔

Comment thread arrow-ipc/src/reader.rs Outdated
if ((vec.as_ptr() as usize) & 63) == 0 {
Ok(Buffer::from_vec(vec))
} else {
let mut buf = MutableBuffer::from_len_zeroed(total_len);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?)

@adriangbot

Copy link
Copy Markdown

🤖 Arrow criterion benchmark running (GKE) | trigger
Instance: c4a-highmem-16 (12 vCPU / 65 GiB) | Linux bench-c4307614360-1786-zqcd4 6.12.55+ #1 SMP Sun Feb 1 08:59:41 UTC 2026 aarch64 GNU/Linux

CPU Details (lscpu)
Architecture:                            aarch64
CPU op-mode(s):                          64-bit
Byte Order:                              Little Endian
CPU(s):                                  16
On-line CPU(s) list:                     0-15
Vendor ID:                               ARM
Model name:                              Neoverse-V2
Model:                                   1
Thread(s) per core:                      1
Core(s) per cluster:                     16
Socket(s):                               -
Cluster(s):                              1
Stepping:                                r0p1
BogoMIPS:                                2000.00
Flags:                                   fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm sb paca pacg dcpodp sve2 sveaes svepmull svebitperm svesha3 svesm4 flagm2 frint svei8mm svebf16 i8mm bf16 dgh rng bti
L1d cache:                               1 MiB (16 instances)
L1i cache:                               1 MiB (16 instances)
L2 cache:                                32 MiB (16 instances)
L3 cache:                                80 MiB (1 instance)
NUMA node(s):                            1
NUMA node0 CPU(s):                       0-15
Vulnerability Gather data sampling:      Not affected
Vulnerability Indirect target selection: Not affected
Vulnerability Itlb multihit:             Not affected
Vulnerability L1tf:                      Not affected
Vulnerability Mds:                       Not affected
Vulnerability Meltdown:                  Not affected
Vulnerability Mmio stale data:           Not affected
Vulnerability Reg file data sampling:    Not affected
Vulnerability Retbleed:                  Not affected
Vulnerability Spec rstack overflow:      Not affected
Vulnerability Spec store bypass:         Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:                Mitigation; __user pointer sanitization
Vulnerability Spectre v2:                Mitigation; CSV2, BHB
Vulnerability Srbds:                     Not affected
Vulnerability Tsa:                       Not affected
Vulnerability Tsx async abort:           Not affected
Vulnerability Vmscape:                   Not affected

Comparing reader-zero-init (8de1dd4) to b93240a (merge-base) diff
BENCH_NAME=ipc_reader
BENCH_COMMAND=cargo bench --features=arrow,async,test_common,experimental,object_store --bench ipc_reader
BENCH_FILTER=
Results will be posted here when complete


File an issue against this benchmark runner

@adriangbot

Copy link
Copy Markdown

🤖 Arrow criterion benchmark completed (GKE) | trigger

Instance: c4a-highmem-16 (12 vCPU / 65 GiB)

CPU Details (lscpu)
Architecture:                            aarch64
CPU op-mode(s):                          64-bit
Byte Order:                              Little Endian
CPU(s):                                  16
On-line CPU(s) list:                     0-15
Vendor ID:                               ARM
Model name:                              Neoverse-V2
Model:                                   1
Thread(s) per core:                      1
Core(s) per cluster:                     16
Socket(s):                               -
Cluster(s):                              1
Stepping:                                r0p1
BogoMIPS:                                2000.00
Flags:                                   fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm sb paca pacg dcpodp sve2 sveaes svepmull svebitperm svesha3 svesm4 flagm2 frint svei8mm svebf16 i8mm bf16 dgh rng bti
L1d cache:                               1 MiB (16 instances)
L1i cache:                               1 MiB (16 instances)
L2 cache:                                32 MiB (16 instances)
L3 cache:                                80 MiB (1 instance)
NUMA node(s):                            1
NUMA node0 CPU(s):                       0-15
Vulnerability Gather data sampling:      Not affected
Vulnerability Indirect target selection: Not affected
Vulnerability Itlb multihit:             Not affected
Vulnerability L1tf:                      Not affected
Vulnerability Mds:                       Not affected
Vulnerability Meltdown:                  Not affected
Vulnerability Mmio stale data:           Not affected
Vulnerability Reg file data sampling:    Not affected
Vulnerability Retbleed:                  Not affected
Vulnerability Spec rstack overflow:      Not affected
Vulnerability Spec store bypass:         Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:                Mitigation; __user pointer sanitization
Vulnerability Spectre v2:                Mitigation; CSV2, BHB
Vulnerability Srbds:                     Not affected
Vulnerability Tsa:                       Not affected
Vulnerability Tsx async abort:           Not affected
Vulnerability Vmscape:                   Not affected
Details

group                                                       main                                   reader-zero-init
-----                                                       ----                                   ----------------
arrow_ipc_reader/FileReader/no_validation/read_10           1.00    119.8±2.06µs        ? ?/sec    1.45    173.3±1.08µs        ? ?/sec
arrow_ipc_reader/FileReader/no_validation/read_10/mmap      1.00     56.9±0.28µs        ? ?/sec    1.02     58.3±0.30µs        ? ?/sec
arrow_ipc_reader/FileReader/read_10                         1.00    386.2±8.20µs        ? ?/sec    1.12    434.2±4.05µs        ? ?/sec
arrow_ipc_reader/FileReader/read_10/mmap                    1.01    456.0±2.71µs        ? ?/sec    1.00    452.9±3.58µs        ? ?/sec
arrow_ipc_reader/StreamReader/no_validation/read_10         1.00    118.9±2.25µs        ? ?/sec    1.45    172.3±0.54µs        ? ?/sec
arrow_ipc_reader/StreamReader/no_validation/read_10/zstd    1.00      2.4±0.02ms        ? ?/sec    1.01      2.5±0.02ms        ? ?/sec
arrow_ipc_reader/StreamReader/read_10                       1.00    390.8±5.56µs        ? ?/sec    1.11    434.3±4.63µs        ? ?/sec
arrow_ipc_reader/StreamReader/read_10/zstd                  1.00      2.7±0.02ms        ? ?/sec    1.00      2.7±0.02ms        ? ?/sec

Resource Usage

base (merge-base)

Metric Value
Wall time 85.0s
Peak memory 2.7 GiB
Avg memory 2.7 GiB
CPU user 70.5s
CPU sys 11.2s
Peak spill 0 B

branch

Metric Value
Wall time 90.0s
Peak memory 2.7 GiB
Avg memory 2.7 GiB
CPU user 76.1s
CPU sys 10.2s
Peak spill 0 B

File an issue against this benchmark runner

@pchintar

Copy link
Copy Markdown
Contributor Author

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:

Image 4-23-26 at 5 06 PM

@alamb
alamb marked this pull request as ready for review April 24, 2026 16:17
@alamb

alamb commented Apr 24, 2026

Copy link
Copy Markdown
Contributor

run benchmark ipc_reader

@adriangbot

Copy link
Copy Markdown

🤖 Arrow criterion benchmark running (GKE) | trigger
Instance: c4a-highmem-16 (12 vCPU / 65 GiB) | Linux bench-c4314652696-1821-97stt 6.12.55+ #1 SMP Sun Feb 1 08:59:41 UTC 2026 aarch64 GNU/Linux

CPU Details (lscpu)
Architecture:                            aarch64
CPU op-mode(s):                          64-bit
Byte Order:                              Little Endian
CPU(s):                                  16
On-line CPU(s) list:                     0-15
Vendor ID:                               ARM
Model name:                              Neoverse-V2
Model:                                   1
Thread(s) per core:                      1
Core(s) per cluster:                     16
Socket(s):                               -
Cluster(s):                              1
Stepping:                                r0p1
BogoMIPS:                                2000.00
Flags:                                   fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm sb paca pacg dcpodp sve2 sveaes svepmull svebitperm svesha3 svesm4 flagm2 frint svei8mm svebf16 i8mm bf16 dgh rng bti
L1d cache:                               1 MiB (16 instances)
L1i cache:                               1 MiB (16 instances)
L2 cache:                                32 MiB (16 instances)
L3 cache:                                80 MiB (1 instance)
NUMA node(s):                            1
NUMA node0 CPU(s):                       0-15
Vulnerability Gather data sampling:      Not affected
Vulnerability Indirect target selection: Not affected
Vulnerability Itlb multihit:             Not affected
Vulnerability L1tf:                      Not affected
Vulnerability Mds:                       Not affected
Vulnerability Meltdown:                  Not affected
Vulnerability Mmio stale data:           Not affected
Vulnerability Reg file data sampling:    Not affected
Vulnerability Retbleed:                  Not affected
Vulnerability Spec rstack overflow:      Not affected
Vulnerability Spec store bypass:         Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:                Mitigation; __user pointer sanitization
Vulnerability Spectre v2:                Mitigation; CSV2, BHB
Vulnerability Srbds:                     Not affected
Vulnerability Tsa:                       Not affected
Vulnerability Tsx async abort:           Not affected
Vulnerability Vmscape:                   Not affected

Comparing reader-zero-init (39bc20a) to b93240a (merge-base) diff
BENCH_NAME=ipc_reader
BENCH_COMMAND=cargo bench --features=arrow,async,test_common,experimental,object_store --bench ipc_reader
BENCH_FILTER=
Results will be posted here when complete


File an issue against this benchmark runner

@adriangbot

Copy link
Copy Markdown

🤖 Arrow criterion benchmark completed (GKE) | trigger

Instance: c4a-highmem-16 (12 vCPU / 65 GiB)

CPU Details (lscpu)
Architecture:                            aarch64
CPU op-mode(s):                          64-bit
Byte Order:                              Little Endian
CPU(s):                                  16
On-line CPU(s) list:                     0-15
Vendor ID:                               ARM
Model name:                              Neoverse-V2
Model:                                   1
Thread(s) per core:                      1
Core(s) per cluster:                     16
Socket(s):                               -
Cluster(s):                              1
Stepping:                                r0p1
BogoMIPS:                                2000.00
Flags:                                   fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm sb paca pacg dcpodp sve2 sveaes svepmull svebitperm svesha3 svesm4 flagm2 frint svei8mm svebf16 i8mm bf16 dgh rng bti
L1d cache:                               1 MiB (16 instances)
L1i cache:                               1 MiB (16 instances)
L2 cache:                                32 MiB (16 instances)
L3 cache:                                80 MiB (1 instance)
NUMA node(s):                            1
NUMA node0 CPU(s):                       0-15
Vulnerability Gather data sampling:      Not affected
Vulnerability Indirect target selection: Not affected
Vulnerability Itlb multihit:             Not affected
Vulnerability L1tf:                      Not affected
Vulnerability Mds:                       Not affected
Vulnerability Meltdown:                  Not affected
Vulnerability Mmio stale data:           Not affected
Vulnerability Reg file data sampling:    Not affected
Vulnerability Retbleed:                  Not affected
Vulnerability Spec rstack overflow:      Not affected
Vulnerability Spec store bypass:         Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:                Mitigation; __user pointer sanitization
Vulnerability Spectre v2:                Mitigation; CSV2, BHB
Vulnerability Srbds:                     Not affected
Vulnerability Tsa:                       Not affected
Vulnerability Tsx async abort:           Not affected
Vulnerability Vmscape:                   Not affected
Details

group                                                       main                                   reader-zero-init
-----                                                       ----                                   ----------------
arrow_ipc_reader/FileReader/no_validation/read_10           1.47    129.2±9.03µs        ? ?/sec    1.00     87.7±2.13µs        ? ?/sec
arrow_ipc_reader/FileReader/no_validation/read_10/mmap      1.00     57.9±0.72µs        ? ?/sec    1.04     60.1±0.48µs        ? ?/sec
arrow_ipc_reader/FileReader/read_10                         1.16   429.9±24.53µs        ? ?/sec    1.00   370.9±15.24µs        ? ?/sec
arrow_ipc_reader/FileReader/read_10/mmap                    1.04   470.8±10.12µs        ? ?/sec    1.00    454.4±3.31µs        ? ?/sec
arrow_ipc_reader/StreamReader/no_validation/read_10         1.60   141.5±13.39µs        ? ?/sec    1.00     88.6±2.02µs        ? ?/sec
arrow_ipc_reader/StreamReader/no_validation/read_10/zstd    1.00      2.4±0.02ms        ? ?/sec    1.00      2.4±0.04ms        ? ?/sec
arrow_ipc_reader/StreamReader/read_10                       1.18   423.0±27.47µs        ? ?/sec    1.00   357.4±13.12µs        ? ?/sec
arrow_ipc_reader/StreamReader/read_10/zstd                  1.00      2.7±0.02ms        ? ?/sec    1.00      2.7±0.03ms        ? ?/sec

Resource Usage

base (merge-base)

Metric Value
Wall time 90.0s
Peak memory 2.7 GiB
Avg memory 2.6 GiB
CPU user 73.8s
CPU sys 11.2s
Peak spill 0 B

branch

Metric Value
Wall time 90.0s
Peak memory 2.6 GiB
Avg memory 2.6 GiB
CPU user 75.9s
CPU sys 10.5s
Peak spill 0 B

File an issue against this benchmark runner

@pchintar

pchintar commented Apr 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks @alamb — so now it seems to be faster for a majority of cases in ipc_reader which is a good sign but however, there's an integration error in the checks. So I checked the integration failure and found the root cause:
The pure Vec + read_to_end version breaks IPC inter-operability in

union nanoarrow producing → Rust consuming

Specifically:

arrow-stream-to-file ... returned non-zero exit status 101

This indicates that reusing the Vec allocation directly is not safe for all IPC cases, likely due to alignment requirements (arrow_buffer::buffer::ALIGNMENT).

I’m reverting this change for now and will revisit a safe approach that preserves alignment while avoiding any overhead.

@pchintar

pchintar commented Apr 24, 2026 •

Copy link
Copy Markdown
Contributor Author

@alamb — quick update.

That CI "integration / Archery test With other arrows" check failure was isolated to the Union path. So, there are only 2 ScalarBuffer<...> conversions in arrow-ipc/src/reader.rs, both inside the Union(fields, mode) branch, and these bypass the usual align_buffers handling.

The issue was specifically with dense union offsets (i32) being constructed directly from the buffer:

self.next_buffer()?.slice_with_length(...).into()

I’ve fixed this by ensuring alignment only for that specific case before converting to ScalarBuffer<i32>:

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 👍

@pchintar

pchintar commented Apr 24, 2026 •

Copy link
Copy Markdown
Contributor Author

No additional changes/conditions were added to read_block, maybe_next and next_buffer for this specific Union alignment fix

So, the fast Vec + read_to_end path remains unchanged for ipc_reader.

@pchintar

Copy link
Copy Markdown
Contributor Author

@alamb & @adriangbot could you pls for one last time, run benchmark ipc_reader

@alamb

alamb commented Apr 24, 2026

Copy link
Copy Markdown
Contributor

run benchmark ipc_reader

@adriangbot

Copy link
Copy Markdown

🤖 Arrow criterion benchmark running (GKE) | trigger
Instance: c4a-highmem-16 (12 vCPU / 65 GiB) | Linux bench-c4316450299-1833-zdc2b 6.12.55+ #1 SMP Sun Feb 1 08:59:41 UTC 2026 aarch64 GNU/Linux

CPU Details (lscpu)
Architecture:                            aarch64
CPU op-mode(s):                          64-bit
Byte Order:                              Little Endian
CPU(s):                                  16
On-line CPU(s) list:                     0-15
Vendor ID:                               ARM
Model name:                              Neoverse-V2
Model:                                   1
Thread(s) per core:                      1
Core(s) per cluster:                     16
Socket(s):                               -
Cluster(s):                              1
Stepping:                                r0p1
BogoMIPS:                                2000.00
Flags:                                   fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm sb paca pacg dcpodp sve2 sveaes svepmull svebitperm svesha3 svesm4 flagm2 frint svei8mm svebf16 i8mm bf16 dgh rng bti
L1d cache:                               1 MiB (16 instances)
L1i cache:                               1 MiB (16 instances)
L2 cache:                                32 MiB (16 instances)
L3 cache:                                80 MiB (1 instance)
NUMA node(s):                            1
NUMA node0 CPU(s):                       0-15
Vulnerability Gather data sampling:      Not affected
Vulnerability Indirect target selection: Not affected
Vulnerability Itlb multihit:             Not affected
Vulnerability L1tf:                      Not affected
Vulnerability Mds:                       Not affected
Vulnerability Meltdown:                  Not affected
Vulnerability Mmio stale data:           Not affected
Vulnerability Reg file data sampling:    Not affected
Vulnerability Retbleed:                  Not affected
Vulnerability Spec rstack overflow:      Not affected
Vulnerability Spec store bypass:         Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:                Mitigation; __user pointer sanitization
Vulnerability Spectre v2:                Mitigation; CSV2, BHB
Vulnerability Srbds:                     Not affected
Vulnerability Tsa:                       Not affected
Vulnerability Tsx async abort:           Not affected
Vulnerability Vmscape:                   Not affected

Comparing reader-zero-init (2f683c7) to 620e39d (merge-base) diff
BENCH_NAME=ipc_reader
BENCH_COMMAND=cargo bench --features=arrow,async,test_common,experimental,object_store --bench ipc_reader
BENCH_FILTER=
Results will be posted here when complete


File an issue against this benchmark runner

@adriangbot

Copy link
Copy Markdown

🤖 Arrow criterion benchmark completed (GKE) | trigger

Instance: c4a-highmem-16 (12 vCPU / 65 GiB)

CPU Details (lscpu)
Architecture:                            aarch64
CPU op-mode(s):                          64-bit
Byte Order:                              Little Endian
CPU(s):                                  16
On-line CPU(s) list:                     0-15
Vendor ID:                               ARM
Model name:                              Neoverse-V2
Model:                                   1
Thread(s) per core:                      1
Core(s) per cluster:                     16
Socket(s):                               -
Cluster(s):                              1
Stepping:                                r0p1
BogoMIPS:                                2000.00
Flags:                                   fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm sb paca pacg dcpodp sve2 sveaes svepmull svebitperm svesha3 svesm4 flagm2 frint svei8mm svebf16 i8mm bf16 dgh rng bti
L1d cache:                               1 MiB (16 instances)
L1i cache:                               1 MiB (16 instances)
L2 cache:                                32 MiB (16 instances)
L3 cache:                                80 MiB (1 instance)
NUMA node(s):                            1
NUMA node0 CPU(s):                       0-15
Vulnerability Gather data sampling:      Not affected
Vulnerability Indirect target selection: Not affected
Vulnerability Itlb multihit:             Not affected
Vulnerability L1tf:                      Not affected
Vulnerability Mds:                       Not affected
Vulnerability Meltdown:                  Not affected
Vulnerability Mmio stale data:           Not affected
Vulnerability Reg file data sampling:    Not affected
Vulnerability Retbleed:                  Not affected
Vulnerability Spec rstack overflow:      Not affected
Vulnerability Spec store bypass:         Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:                Mitigation; __user pointer sanitization
Vulnerability Spectre v2:                Mitigation; CSV2, BHB
Vulnerability Srbds:                     Not affected
Vulnerability Tsa:                       Not affected
Vulnerability Tsx async abort:           Not affected
Vulnerability Vmscape:                   Not affected
Details

group                                                       main                                   reader-zero-init
-----                                                       ----                                   ----------------
arrow_ipc_reader/FileReader/no_validation/read_10           1.40    120.4±3.53µs        ? ?/sec    1.00     85.7±0.37µs        ? ?/sec
arrow_ipc_reader/FileReader/no_validation/read_10/mmap      1.03     58.6±1.81µs        ? ?/sec    1.00     56.8±0.55µs        ? ?/sec
arrow_ipc_reader/FileReader/read_10                         1.14    395.9±5.13µs        ? ?/sec    1.00    347.8±5.16µs        ? ?/sec
arrow_ipc_reader/FileReader/read_10/mmap                    1.01    462.8±6.02µs        ? ?/sec    1.00    460.2±2.05µs        ? ?/sec
arrow_ipc_reader/StreamReader/no_validation/read_10         1.39    119.7±3.89µs        ? ?/sec    1.00     85.9±0.45µs        ? ?/sec
arrow_ipc_reader/StreamReader/no_validation/read_10/zstd    1.00      2.4±0.02ms        ? ?/sec    1.00      2.4±0.02ms        ? ?/sec
arrow_ipc_reader/StreamReader/read_10                       1.14    391.6±6.46µs        ? ?/sec    1.00    344.3±4.96µs        ? ?/sec
arrow_ipc_reader/StreamReader/read_10/zstd                  1.00      2.7±0.03ms        ? ?/sec    1.00      2.7±0.02ms        ? ?/sec

Resource Usage

base (merge-base)

Metric Value
Wall time 85.0s
Peak memory 2.7 GiB
Avg memory 2.6 GiB
CPU user 71.1s
CPU sys 11.3s
Peak spill 0 B

branch

Metric Value
Wall time 90.0s
Peak memory 2.7 GiB
Avg memory 2.6 GiB
CPU user 77.1s
CPU sys 10.7s
Peak spill 0 B

File an issue against this benchmark runner

@pchintar

pchintar commented Apr 24, 2026 •

Copy link
Copy Markdown
Contributor Author

@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.

alamb
alamb previously approved these changes Apr 24, 2026

@alamb alamb left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @pchintar -- this looks good to me

Comment thread arrow-ipc/src/reader.rs
UnionMode::Dense => {
let offsets: ScalarBuffer<i32> =
self.next_buffer()?.slice_with_length(0, len * 4).into();
let offsets_buffer = ensure_aligned_for::<i32>(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is really weird that this extra alignment / copy is needed

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>) 🤔

@pchintar

Copy link
Copy Markdown
Contributor Author

Thank You @alamb I will also update the fix proposed in the issue to remove any references to unsafe code in #9777

@alamb
alamb self-requested a review April 24, 2026 22:40
@alamb
alamb dismissed their stale review April 24, 2026 22:41

I think there is an alignment problem

@alamb alamb left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually after some more thought I think there may be an alignment problem

Comment thread arrow-ipc/src/reader.rs
UnionMode::Dense => {
let offsets: ScalarBuffer<i32> =
self.next_buffer()?.slice_with_length(0, len * 4).into();
let offsets_buffer = ensure_aligned_for::<i32>(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>) 🤔

@pchintar

Copy link
Copy Markdown
Contributor Author

Yes @alamb , w.r.t the alignment concern. I checked this specifically before adding the fix.

In arrow-ipc/src/reader.rs, the only direct ScalarBuffer<...> conversions are the two inside the Union(fields, mode) branch. Other array paths go through ArrayDataBuilder::align_buffers(...), so this is the only place in the IPC reader where the Vec-backed buffer can bypass the usual alignment handling before typed access.

The type_ids buffer is i8, so it does not need extra alignment. The dense union offsets buffer is i32, so the fix ensures alignment only for that buffer before converting to ScalarBuffer<i32>.

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.

@alamb

alamb commented Apr 24, 2026

Copy link
Copy Markdown
Contributor

Yes @alamb , w.r.t the alignment concern. I checked this specifically before adding the fix.

In arrow-ipc/src/reader.rs, the only direct ScalarBuffer<...> conversions are the two inside the Union(fields, mode) branch. Other array paths go through ArrayDataBuilder::align_buffers(...), so this is the only place in the IPC reader where the Vec-backed buffer can bypass the usual alignment handling before typed access.

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 read_buffer chose was not aligned) 🤔

This may well not be covered in our benchmarks.

@pchintar

pchintar commented Apr 24, 2026 •

Copy link
Copy Markdown
Contributor Author

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 i32. So the tradeoff is:

  • main: aligned body allocation upfront, no union-offset repair copy
  • this PR: faster Vec read path generally, but possible small copy only for dense union offsets

This is not covered by the current ipc_reader benchmark, since that benchmark does not exercise union-heavy data.

That's why I updated the title earlier from Avoid to now just Reduce zero-initialization 😅 bc complete avoidance might not be possible tbh

@alamb

alamb commented Apr 24, 2026

Copy link
Copy Markdown
Contributor

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 i32. So the tradeoff is:

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?

@pchintar

Copy link
Copy Markdown
Contributor Author

Yes @alamb , so for other types (e.g. UInt64Array), if the underlying buffer is not aligned, the extra copy would already happen today via ArrayDataBuilder::align_buffers(...), so that behavior doesn’t change with this PR.

The difference here is that Union bypasses that path and directly constructs ScalarBuffer<T>, so the alignment repair needs to be made explicit in that one place.

So effectively:

  • for most types → alignment/copy is already handled later (unchanged)
  • for Union → we make that same alignment requirement explicit at the conversion point

@jhorstmann

Copy link
Copy Markdown
Contributor

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).

@alamb

alamb commented Apr 25, 2026

Copy link
Copy Markdown
Contributor

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 read_buffer with the relevant underlying native type to ensure alignment.

So instead of read_buffer it would be something like read_buffer<i32> and read_buffer<i64>

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())`

@pchintar

Copy link
Copy Markdown
Contributor Author

@alamb That makes sense — I looked into this, and implementing read_buffer<T> correctly would require restructuring the current reader flow.

Today read_buffer operates on slices of an already materialized IPC body buffer, so type-aware allocation would need to happen earlier during the body read, or require bypassing ArrayDataBuilder and constructing arrays directly.

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.

@alamb

alamb commented Apr 27, 2026

Copy link
Copy Markdown
Contributor

Today read_buffer operates on slices of an already materialized IPC body buffer, so type-aware allocation would need to happen earlier during the body read, or require bypassing ArrayDataBuilder and constructing arrays directly.

Yes I agree with this assement

I also agree that would likely require a more substantial PR / refactoring

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.

Thank you -- that sounds good. I'll file a ticket to track the idea

@alamb

alamb commented Apr 27, 2026

Copy link
Copy Markdown
Contributor

I filed #9777 to track the idea of using Vec instead of Vec and will mark this PR as draft

@alamb
alamb marked this pull request as draft April 27, 2026 13:37
@alamb

alamb commented Apr 27, 2026

Copy link
Copy Markdown
Contributor

Thank you very much @pchintar

@pchintar

Copy link
Copy Markdown
Contributor Author

thank you @alamb

@github-actions

Copy link
Copy Markdown

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.

@github-actions github-actions Bot added the Stale Used by workflow to mark PRs that will be auto-closed label Jun 28, 2026
@alamb

alamb commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

I filed #9777 to track the idea of using Vec instead of Vec and will mark this PR as draft

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

@alamb alamb closed this Jun 29, 2026
@Rich-T-kid

Copy link
Copy Markdown
Contributor

I filed #9777 to track the idea of using Vec instead of Vec and will mark this PR as draft

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 👀

@Rich-T-kid

Rich-T-kid commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

it seems we ran into the same issue in #10125, mis-aligned buffers were causing issues in arrow-ipc. #10273 resolved these issues. Im not sure if replacing MutableBuffer for Vec<T> can work here unless we had a way to check that vectors underlying allocation was aligned.

@Rich-T-kid

Rich-T-kid commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

@/alamb:
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) 🤔

I also share this concern, we are very fortunate to have existing intergration test to detect bugs like this.

@alamb

alamb commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

it seems we ran into the same issue in #10125, mis-aligned buffers were causing issues in arrow-ipc. #10273 resolved these issues. Im not sure if replacing MutableBuffer for Vec<T> can work here unless we had a way to check that vectors underlying allocation was aligned.

I think we should add some new tests to explicitly cover this case, if possible

@alamb

alamb commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

it seems we ran into the same issue in #10125, mis-aligned buffers were causing issues in arrow-ipc. #10273 resolved these issues. Im not sure if replacing MutableBuffer for Vec can work here unless we had a way to check that vectors underlying allocation was aligned.

@Rich-T-kid is there an issue for whatever problem you ran into?

@Rich-T-kid

Rich-T-kid commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

it seems we ran into the same issue in #10125, mis-aligned buffers were causing issues in arrow-ipc. #10273 resolved these issues. Im not sure if replacing MutableBuffer for Vec can work here unless we had a way to check that vectors underlying allocation was aligned.

@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 flightdata chunk that came in, but this caused issues when the tonic buffer returned a mis-aligned buffer. this was resolved it #10273.

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.
ex

#[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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

arrow Changes to the arrow crate performance Speed or memory optimizations Stale Used by workflow to mark PRs that will be auto-closed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Remove redundant zero-initialization in Arrow IPC reader hot paths

5 participants