This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch 
gh-readonly-queue/main/pr-11648-534da94754aae712849ce46e6dc06f9eedf39979
in repository https://gitbox.apache.org/repos/asf/arrow-rs.git

commit ccc426cc27770b1327cc0c0c9d7e6584579965b6
Author: ranflarion <[email protected]>
AuthorDate: Sun Oct 18 09:38:54 2026 +0000

    fix: assemble split IPC messages in StreamDecoder at their declared size 
(#11648)
    
    # Which issue does this PR close?
    
    - Closes #11647.
    
    # Rationale for this change
    
    `StreamDecoder` assembles a message that arrives split across input
    buffers in a scratch `MutableBuffer` that starts empty and doubles as
    the pieces are copied in, and the decoded batch is zero-copy over that
    buffer, so it keeps between 1x and 2x its body alive. A reader that
    feeds fixed-size chunks hits this on nearly every message large enough
    to span one: DataFusion 55 reads spill files back in 128 KiB chunks, and
    a spilling sort's read-back batches held 2,969 MiB for 2,198 MiB of
    data. `StreamReader` avoids it since #10522 by reading a body into
    `min(body_length, MAX_PREALLOC_BYTES)` up front.
    
    # What changes are included in this PR?
    
    When the first bytes of a message flatbuffer or body are copied into the
    empty scratch buffer, the decoder now reserves the declared length,
    capped at `MAX_PREALLOC_BYTES` the same way `read_body_bounded` caps it.
    A message up to 64 MiB is therefore allocated once at its size, while an
    implausible declared length still reserves at most 64 MiB and leaves the
    decoder waiting for bytes that never arrive. Larger messages keep
    growing geometrically past the cap, as they do in `StreamReader`. The
    path that slices a message straight out of a single input buffer is
    unchanged.
    
    # Are these changes tested?
    
    Yes, two tests in `arrow-ipc/src/reader/stream.rs`.
    `test_split_body_is_buffered_at_its_declared_size` feeds a 99,272 byte
    stream one byte at a time and checks the decoded batch holds no more
    than the stream: without the change it holds 131,072 bytes.
    `test_implausible_body_length_reserves_a_bounded_buffer` declares body
    lengths of `i64::MAX` and `1 << 50` and checks the decoder keeps waiting
    for the body: reserving the declared length without the cap fails it
    with `MemoryError("invalid allocation layout for requested capacity")`.
    
    In the DataFusion sort from the issue, built against arrow 59.3 with
    this change, peak native allocation went from 201.8 MiB to 161.0 MiB.
    
    The `arrow-ipc` suite passes (138 library tests, including the two
    above), along with `cargo fmt --all -- --check` and `cargo clippy -p
    arrow-ipc --all-targets --all-features -- -D warnings`.
    
    # Are there any user-facing changes?
    
    No API changes. Batches decoded from split messages hold less memory. No
    breaking changes.
---
 arrow-ipc/src/reader/stream.rs | 85 +++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 83 insertions(+), 2 deletions(-)

diff --git a/arrow-ipc/src/reader/stream.rs b/arrow-ipc/src/reader/stream.rs
index cb863eb9ae..3ba712b117 100644
--- a/arrow-ipc/src/reader/stream.rs
+++ b/arrow-ipc/src/reader/stream.rs
@@ -25,7 +25,7 @@ use arrow_data::UnsafeFlag;
 use arrow_schema::{ArrowError, SchemaRef};
 
 use crate::convert::MessageBuffer;
-use crate::reader::{RecordBatchDecoder, read_dictionary_impl};
+use crate::reader::{MAX_PREALLOC_BYTES, RecordBatchDecoder, 
read_dictionary_impl};
 use crate::{CONTINUATION_MARKER, MessageHeader};
 
 /// A low-level interface for reading [`RecordBatch`] data from a stream of 
bytes
@@ -193,6 +193,7 @@ impl StreamDecoder {
                         continue;
                     }
 
+                    reserve_declared(&mut self.buf, len)?;
                     let to_read = buffer.len().min(len - self.buf.len());
                     self.buf
                         .try_extend_from_slice(&buffer[..to_read])
@@ -212,6 +213,7 @@ impl StreamDecoder {
                         buffer.advance(body_length);
                         body
                     } else {
+                        reserve_declared(&mut self.buf, body_length)?;
                         let to_read = buffer.len().min(body_length - 
self.buf.len());
                         self.buf
                             .try_extend_from_slice(&buffer[..to_read])
@@ -309,12 +311,24 @@ impl StreamDecoder {
     }
 }
 
+/// Reserves a message's declared length before copying its first bytes into 
an empty `buf`,
+/// bounded as in `read_body_bounded`. Growing with each input buffer instead 
doubles the
+/// capacity, and the decoded batch, which is zero-copy over `buf`, keeps up 
to twice its size.
+fn reserve_declared(buf: &mut MutableBuffer, len: usize) -> Result<(), 
ArrowError> {
+    if buf.is_empty() {
+        buf.try_reserve(len.min(MAX_PREALLOC_BYTES))
+            .map_err(|e| ArrowError::MemoryError(e.to_string()))?;
+    }
+    Ok(())
+}
+
 #[cfg(test)]
 mod tests {
     use super::*;
     use crate::writer::{IpcWriteOptions, StreamWriter};
     use arrow_array::{
-        DictionaryArray, Int32Array, Int64Array, RecordBatch, RunArray, 
types::Int32Type,
+        DictionaryArray, Int32Array, Int64Array, RecordBatch, RunArray, 
StringArray,
+        types::Int32Type,
     };
     use arrow_schema::{DataType, Field, Schema};
 
@@ -441,4 +455,71 @@ mod tests {
 
         decoder.finish().expect("Failed to finish decoder");
     }
+
+    /// Fed one byte at a time, every message is split across input buffers, 
so its body is
+    /// assembled in the scratch buffer that the decoded batch then shares.
+    #[test]
+    fn test_split_body_is_buffered_at_its_declared_size() {
+        let schema = Arc::new(Schema::new(vec![Field::new("s", DataType::Utf8, 
false)]));
+        let input = RecordBatch::try_new(
+            schema.clone(),
+            vec![Arc::new(StringArray::from_iter_values(
+                (0..7000).map(|i| format!("value{i:05}")),
+            )) as _],
+        )
+        .unwrap();
+
+        let mut stream = Vec::new();
+        let mut writer = StreamWriter::try_new(&mut stream, &schema).unwrap();
+        writer.write(&input).unwrap();
+        writer.finish().unwrap();
+        drop(writer);
+
+        let mut decoder = StreamDecoder::new();
+        let mut output = None;
+        for byte in stream.chunks(1) {
+            if let Some(batch) = decoder.decode(&mut 
Buffer::from(byte)).unwrap() {
+                output = Some(batch);
+            }
+        }
+        decoder.finish().unwrap();
+        let output = output.unwrap();
+        assert_eq!(output, input);
+
+        let held = output.column(0).to_data().buffers()[0].capacity();
+        assert!(
+            held <= stream.len(),
+            "decoded batch holds {held} bytes, more than the {} byte stream it 
came from",
+            stream.len()
+        );
+    }
+
+    /// A declared length is untrusted, so reserving it up front is bounded: 
an implausible
+    /// one must leave the decoder waiting for more bytes rather than abort on 
allocation.
+    #[test]
+    fn test_implausible_body_length_reserves_a_bounded_buffer() {
+        for body_length in [i64::MAX, 1 << 50] {
+            let mut fbb = flatbuffers::FlatBufferBuilder::new();
+            let mut message = crate::MessageBuilder::new(&mut fbb);
+            message.add_version(crate::MetadataVersion::V5);
+            message.add_header_type(MessageHeader::NONE);
+            message.add_bodyLength(body_length);
+            let root = message.finish();
+            fbb.finish(root, None);
+            let metadata = fbb.finished_data();
+
+            let mut stream = Vec::new();
+            stream.extend_from_slice(&CONTINUATION_MARKER);
+            stream.extend_from_slice(&(metadata.len() as i32).to_le_bytes());
+            stream.extend_from_slice(metadata);
+            stream.extend_from_slice(&[0xAB; 16]);
+
+            let mut decoder = StreamDecoder::new();
+            let decoded = decoder
+                .decode(&mut Buffer::from(stream.as_slice()))
+                .unwrap();
+            assert!(decoded.is_none(), "body_length {body_length}");
+            assert!(decoder.finish().is_err(), "body_length {body_length}");
+        }
+    }
 }

Reply via email to