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-12148-857b0043a5d823b5080df0c366715121a4170c6b
in repository https://gitbox.apache.org/repos/asf/arrow-rs.git

commit 3e7ca974f28c7eeb573881494bfea8293ace51c8
Author: Mohit Gurav <[email protected]>
AuthorDate: Thu Nov 19 20:45:21 2026 +0000

    feat(arrow-ipc): make lz4 block size configurable (#12148)
    
    # Which issue does this PR close?
    
    - Closes #12105
    
    # Rationale for this change
    
    #12084 pinned the reusable LZ4 frame encoder to a 256 KiB block size so
    a reused encoder’s block size is not decided by the first buffer it
    writes. Callers who want to trade retained encoder buffers against
    compression ratio currently have no way to choose a different size. This
    change lets callers configure the block size while keeping 256 KiB as
    the default, so existing output remains unchanged.
    
    # What changes are included in this PR?
    
    - Adds `IpcWriteOptions::try_with_lz4_block_size(Option<usize>)`,
    following the existing `try_with_compression_level` pattern with a
    private field and validating builder.
    - Supports 64 KiB, 256 KiB, 1 MiB, and 4 MiB, which are the block sizes
    the LZ4 frame header can represent. The option requires metadata V5 or
    newer and returns an error when used with ZSTD.
    - Updates `IpcWriteContext` to store the selected size and discard its
    cached encoder when that size changes. The setting is synced through the
    shared record batch and dictionary batch encoding path.
    - Preserves the selected size when `Lz4Compressor` rebuilds after a
    mid-frame error.
    - Does not support 8 MiB: `lz4_flex` sets a reserved frame-header bit
    for that size, which its decoder rejects.
    
    # Are these changes tested?
    
    Tests cover the supported frame-header size codes and roundtrips,
    byte-identical output for the default 256 KiB setting, and switching
    block sizes while reusing an `IpcWriteContext`. They also cover
    unsupported sizes, metadata V4, ZSTD in both builder-call orders, and
    end-to-end roundtrips with nulls and a dictionary column.
    
    # Are there any significant user-facing changes?
    
    Yes. This adds the public `IpcWriteOptions::try_with_lz4_block_size`
    method so callers can select an LZ4 frame block size. The addition is
    non-breaking; when the option is unset, the 256 KiB default and encoded
    output are unchanged.
    
    # AI usage disclosure
    
    Codex Desktop and OpenCode assisted with implementation, test updates,
    and reviewer-driven revisions. I guided the changes based on the issue
    and reviewer feedback. The branch was checked with local tests,
    formatting, and lint.
---
 arrow-ipc/src/compression.rs |  77 ++++++++++++++--
 arrow-ipc/src/writer.rs      | 211 ++++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 278 insertions(+), 10 deletions(-)

diff --git a/arrow-ipc/src/compression.rs b/arrow-ipc/src/compression.rs
index 766ba72aa2..0885689c9c 100644
--- a/arrow-ipc/src/compression.rs
+++ b/arrow-ipc/src/compression.rs
@@ -11,18 +11,47 @@ const LENGTH_NO_COMPRESSED_DATA: i64 = -1;
 const LENGTH_OF_PREFIX_DATA: i64 = 8;
 const DEFAULT_ZSTD_COMPRESSION_LEVEL: i32 = 3;
 
+/// LZ4 frame block sizes representable by the frame header. See the [LZ4 
frame format] for the
+/// block size codes; `lz4_flex`'s 8 MiB option sets a reserved bit, which the 
decoder rejects.
+///
+/// [LZ4 frame format]: 
https://github.com/lz4/lz4/blob/dev/doc/lz4_Frame_format.md
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum Lz4BlockSize {
+    Max64KiB,
+    Max256KiB,
+    Max1MiB,
+    Max4MiB,
+}
+
+impl Lz4BlockSize {
+    pub(crate) const DEFAULT: Self = Self::Max256KiB;
+
+    pub(crate) const fn from_bytes(bytes: usize) -> Option<Self> {
+        match bytes {
+            65_536 => Some(Self::Max64KiB),
+            262_144 => Some(Self::Max256KiB),
+            1_048_576 => Some(Self::Max1MiB),
+            4_194_304 => Some(Self::Max4MiB),
+            _ => None,
+        }
+    }
+}
+
 /// Additional context that may be needed for compression.
 ///
 /// In the case of zstd, this will contain the zstd context, which can be 
reused between subsequent
 /// compression calls to avoid the performance overhead of initialising a new 
context for every
 /// compression. In the case of lz4, this will contain the lz4 frame encoder, 
whose hash table and
-/// block buffers are likewise reused. Also holds a [`FlatBufferBuilder`] that 
is reused across
-/// IPC writes.
+/// block buffers are likewise reused; its block size is configurable through
+/// [`crate::writer::IpcWriteOptions::try_with_lz4_block_size`]. Also holds a 
[`FlatBufferBuilder`]
+/// that is reused across IPC writes.
 #[derive(Default)]
 pub struct IpcWriteContext {
     scratch: Vec<u8>,
     reserve_scratch: bool,
     fbb: FlatBufferBuilder<'static>,
+    /// The lz4 frame block size to build a cached encoder with; `None` 
selects the default.
+    lz4_block_size: Option<Lz4BlockSize>,
     #[cfg(feature = "zstd")]
     compressor: Option<zstd::bulk::Compressor<'static>>,
     #[cfg(feature = "lz4")]
@@ -52,6 +81,21 @@ impl IpcWriteContext {
         std::mem::take(&mut self.scratch)
     }
 
+    /// Set the lz4 frame block size used by the cached lz4 encoder.
+    ///
+    /// A cached encoder is dropped when the size changes so the next 
compression call builds one
+    /// with the new block size.
+    pub(crate) fn set_lz4_block_size(&mut self, block_size: Lz4BlockSize) {
+        if self.lz4_block_size != Some(block_size) {
+            self.lz4_block_size = Some(block_size);
+            #[cfg(feature = "lz4")]
+            {
+                // The cached encoder was configured for the previous block 
size.
+                self.lz4_compressor = None;
+            }
+        }
+    }
+
     #[cfg(feature = "zstd")]
     fn zstd_compressor(&mut self, level: i32) -> &mut 
zstd::bulk::Compressor<'static> {
         self.compressor.get_or_insert_with(|| {
@@ -61,7 +105,9 @@ impl IpcWriteContext {
 
     #[cfg(feature = "lz4")]
     fn lz4_compressor(&mut self) -> &mut Lz4Compressor {
-        self.lz4_compressor.get_or_insert_with(Lz4Compressor::new)
+        let block_size = self.lz4_block_size.unwrap_or(Lz4BlockSize::DEFAULT);
+        self.lz4_compressor
+            .get_or_insert_with(|| Lz4Compressor::new(block_size))
     }
 }
 
@@ -297,18 +343,19 @@ impl CompressionCodec {
 #[cfg(feature = "lz4")]
 struct Lz4Compressor {
     encoder: lz4_flex::frame::FrameEncoder<Vec<u8>>,
+    block_size: Lz4BlockSize,
 }
 
 #[cfg(feature = "lz4")]
 impl Lz4Compressor {
-    fn new() -> Self {
-        // Pin the block size: with `BlockSize::Auto` the first buffer written 
would fix it for
-        // every subsequent frame of the reused encoder. 256KB keeps large 
buffers as fast as
-        // with bigger blocks while the encoder retains only ~0.5MB of buffers.
+    fn new(block_size: Lz4BlockSize) -> Self {
+        // `BlockSize::Auto` fixes a reused encoder's size from its first 
buffer. Pin the selected
+        // size so later frames keep using the block size requested in the 
write options.
         let frame_info =
-            
lz4_flex::frame::FrameInfo::new().block_size(lz4_flex::frame::BlockSize::Max256KB);
+            
lz4_flex::frame::FrameInfo::new().block_size(to_lz4_block_size(block_size));
         Self {
             encoder: 
lz4_flex::frame::FrameEncoder::with_frame_info(frame_info, Vec::new()),
+            block_size,
         }
     }
 
@@ -331,12 +378,24 @@ impl Lz4Compressor {
         std::mem::swap(self.encoder.get_mut(), output);
         if result.is_err() {
             // The encoder may be left mid-frame, start from a fresh one next 
time.
-            *self = Self::new();
+            let block_size = self.block_size;
+            *self = Self::new(block_size);
         }
         result
     }
 }
 
+/// Maps a validated block size to the `lz4_flex` frame header code.
+#[cfg(feature = "lz4")]
+fn to_lz4_block_size(block_size: Lz4BlockSize) -> lz4_flex::frame::BlockSize {
+    match block_size {
+        Lz4BlockSize::Max64KiB => lz4_flex::frame::BlockSize::Max64KB,
+        Lz4BlockSize::Max256KiB => lz4_flex::frame::BlockSize::Max256KB,
+        Lz4BlockSize::Max1MiB => lz4_flex::frame::BlockSize::Max1MB,
+        Lz4BlockSize::Max4MiB => lz4_flex::frame::BlockSize::Max4MB,
+    }
+}
+
 #[cfg(feature = "lz4")]
 fn compress_lz4(
     input: &[u8],
diff --git a/arrow-ipc/src/writer.rs b/arrow-ipc/src/writer.rs
index 755ac82cdd..3daa338c46 100644
--- a/arrow-ipc/src/writer.rs
+++ b/arrow-ipc/src/writer.rs
@@ -27,7 +27,7 @@ use arrow_data::{ArrayData, ArrayDataBuilder, BufferSpec, 
layout};
 use arrow_schema::*;
 
 use crate::CONTINUATION_MARKER;
-use crate::compression::CompressionCodec;
+use crate::compression::{CompressionCodec, Lz4BlockSize};
 #[expect(deprecated)]
 pub use crate::compression::{CompressionContext, IpcWriteContext};
 use crate::convert::IpcSchemaEncoder;
@@ -54,6 +54,8 @@ pub struct IpcWriteOptions {
     batch_compression_type: Option<crate::CompressionType>,
     // Compression level
     batch_compression_level: Option<i32>,
+    /// The lz4 frame block size; `None` selects 256 KiB.
+    batch_lz4_block_size: Option<Lz4BlockSize>,
     /// How to handle updating dictionaries in IPC messages
     dictionary_handling: DictionaryHandling,
 }
@@ -390,6 +392,14 @@ impl IpcWriteOptions {
         mut self,
         batch_compression_type: Option<crate::CompressionType>,
     ) -> Result<Self, ArrowError> {
+        if matches!(batch_compression_type, Some(crate::CompressionType::ZSTD))
+            && self.batch_lz4_block_size.is_some()
+        {
+            return Err(ArrowError::InvalidArgumentError(
+                "lz4 frame block size does not apply to ZSTD 
compression".to_string(),
+            ));
+        }
+
         self.batch_compression_type = batch_compression_type;
 
         if self.batch_compression_type.is_some()
@@ -436,6 +446,53 @@ impl IpcWriteOptions {
         Ok(self)
     }
 
+    /// Configures the lz4 frame block size used when compressing batches with
+    /// [`crate::CompressionType::LZ4_FRAME`].
+    ///
+    /// `None` restores the default of 256 KiB, which balances compression 
throughput against the
+    /// buffers retained by the reusable encoder. The LZ4 frame header can 
only describe the
+    /// block sizes 64 KiB, 256 KiB, 1 MiB and 4 MiB; any other value returns 
an
+    /// [`ArrowError::InvalidArgumentError`]. Like the other compression 
settings this requires
+    /// metadata version V5 or newer, and it has no effect when another 
compression codec is
+    /// selected.
+    pub fn try_with_lz4_block_size(
+        mut self,
+        block_size: Option<usize>,
+    ) -> Result<Self, ArrowError> {
+        let block_size = block_size.map(|bytes| {
+            Lz4BlockSize::from_bytes(bytes).ok_or_else(|| {
+                ArrowError::InvalidArgumentError(format!(
+                    "Unsupported lz4 block size {bytes}, must be one of 65536, 
262144, 1048576, or 4194304 bytes"
+                ))
+            })
+        }).transpose()?;
+
+        if block_size.is_some() {
+            if self.metadata_version < crate::MetadataVersion::V5 {
+                return Err(ArrowError::InvalidArgumentError(
+                    "Compression only supported in metadata v5 and 
above".to_string(),
+                ));
+            }
+
+            if matches!(
+                self.batch_compression_type,
+                Some(crate::CompressionType::ZSTD)
+            ) {
+                return Err(ArrowError::InvalidArgumentError(
+                    "lz4 frame block size does not apply to ZSTD 
compression".to_string(),
+                ));
+            }
+        }
+
+        self.batch_lz4_block_size = block_size;
+        Ok(self)
+    }
+
+    /// The lz4 frame block size to compress with, in bytes.
+    pub(crate) fn lz4_block_size(&self) -> Lz4BlockSize {
+        self.batch_lz4_block_size.unwrap_or(Lz4BlockSize::DEFAULT)
+    }
+
     #[cfg(not(feature = "zstd"))]
     fn check_zstd_level(self, _level: i32) -> Result<Self, ArrowError> {
         Err(ArrowError::InvalidArgumentError(
@@ -487,6 +544,7 @@ impl IpcWriteOptions {
                 metadata_version,
                 batch_compression_type: None,
                 batch_compression_level: None,
+                batch_lz4_block_size: None,
                 dictionary_handling: DictionaryHandling::default(),
             }),
             crate::MetadataVersion::V5 => {
@@ -501,6 +559,7 @@ impl IpcWriteOptions {
                         metadata_version,
                         batch_compression_type: None,
                         batch_compression_level: None,
+                        batch_lz4_block_size: None,
                         dictionary_handling: DictionaryHandling::default(),
                     })
                 }
@@ -526,6 +585,7 @@ impl Default for IpcWriteOptions {
             metadata_version: crate::MetadataVersion::V5,
             batch_compression_type: None,
             batch_compression_level: None,
+            batch_lz4_block_size: None,
             dictionary_handling: DictionaryHandling::default(),
         }
     }
@@ -1165,6 +1225,10 @@ impl IpcDataGenerator {
     ) -> Result<EncodedRecordBatchMeta, ArrowError> {
         let batch_compression_type = write_options.batch_compression_type;
 
+        // Keep the reusable lz4 encoder cached in `ipc_write_context` in sync 
with these
+        // options: the context may outlive a single writer or option set.
+        ipc_write_context.set_lz4_block_size(write_options.lz4_block_size());
+
         let compression = batch_compression_type.map(|batch_compression_type| {
             let fbb = ipc_write_context.mut_fbb();
             let mut c = crate::BodyCompressionBuilder::new(fbb);
@@ -3142,6 +3206,151 @@ mod tests {
         }
     }
 
+    /// Batch exercising nulls, a dictionary column, and enough bytes that lz4 
emits several
+    /// blocks even at the smallest configurable block size.
+    fn lz4_block_size_batch() -> RecordBatch {
+        let schema = Schema::new(vec![
+            Field::new("ints", DataType::Int32, true),
+            Field::new(
+                "words",
+                DataType::Dictionary(Box::new(DataType::Int32), 
Box::new(DataType::Utf8)),
+                false,
+            ),
+        ]);
+        let ints = Int32Array::from(
+            (0..30_000)
+                .map(|i| if i % 13 == 0 { None } else { Some(i) })
+                .collect::<Vec<Option<i32>>>(),
+        );
+        let keys = Int32Array::from((0..30_000).map(|i| i % 
5).collect::<Vec<i32>>());
+        let values = StringArray::from(vec!["zero", "one", "two", "three", 
"four"]);
+        let words = DictionaryArray::new(keys, Arc::new(values));
+        RecordBatch::try_new(Arc::new(schema), vec![Arc::new(ints), 
Arc::new(words)]).unwrap()
+    }
+
+    #[test]
+    fn test_lz4_block_size_options() {
+        let options = || IpcWriteOptions::try_new(8, false, 
MetadataVersion::V5).unwrap();
+
+        assert_eq!(options().lz4_block_size(), Lz4BlockSize::DEFAULT);
+        assert_eq!(
+            options()
+                .try_with_lz4_block_size(None)
+                .unwrap()
+                .lz4_block_size(),
+            Lz4BlockSize::DEFAULT
+        );
+        assert_eq!(
+            options()
+                .try_with_lz4_block_size(Some(1024 * 1024))
+                .unwrap()
+                .lz4_block_size(),
+            Lz4BlockSize::Max1MiB
+        );
+
+        for block_size in [0, 32 * 1024, 128 * 1024, 2 * 1024 * 1024, 8 * 1024 
* 1024] {
+            let err = options()
+                .try_with_lz4_block_size(Some(block_size))
+                .expect_err("unsupported block size must be rejected");
+            assert!(
+                err.to_string().contains("Unsupported lz4 block size"),
+                "unexpected error: {err}"
+            );
+        }
+
+        let options = IpcWriteOptions::try_new(8, false, 
MetadataVersion::V4).unwrap();
+        let err = options
+            .try_with_lz4_block_size(Some(64 * 1024))
+            .expect_err("block size below metadata V5 must be rejected");
+        assert!(
+            err.to_string().contains("metadata v5"),
+            "unexpected error: {err}"
+        );
+
+        let options = IpcWriteOptions::try_new(8, false, MetadataVersion::V5)
+            .unwrap()
+            .try_with_compression(Some(crate::CompressionType::ZSTD))
+            .unwrap();
+        let err = options
+            .try_with_lz4_block_size(Some(64 * 1024))
+            .expect_err("lz4 block size must be rejected for ZSTD");
+        assert!(err.to_string().contains("ZSTD"), "unexpected error: {err}");
+
+        let err = IpcWriteOptions::try_new(8, false, MetadataVersion::V5)
+            .unwrap()
+            .try_with_lz4_block_size(Some(64 * 1024))
+            .unwrap()
+            .try_with_compression(Some(crate::CompressionType::ZSTD))
+            .expect_err("ZSTD must be rejected after setting an lz4 block 
size");
+        assert!(err.to_string().contains("ZSTD"), "unexpected error: {err}");
+    }
+
+    #[test]
+    #[cfg(feature = "lz4")]
+    fn test_lz4_block_size_configurable_end_to_end() {
+        let batch = lz4_block_size_batch();
+        let schema = batch.schema();
+        let data_gen = IpcDataGenerator::default();
+        let mut ipc_write_context = IpcWriteContext::default();
+
+        let sizes: [Option<usize>; 5] = [
+            None,
+            Some(64 * 1024),
+            Some(256 * 1024),
+            Some(1024 * 1024),
+            Some(4 * 1024 * 1024),
+        ];
+        let mut outputs = Vec::with_capacity(sizes.len());
+        for block_size in sizes {
+            let options = IpcWriteOptions::try_new(8, false, 
MetadataVersion::V5)
+                .unwrap()
+                .try_with_compression(Some(crate::CompressionType::LZ4_FRAME))
+                .unwrap()
+                .try_with_lz4_block_size(block_size)
+                .unwrap();
+
+            let mut dictionary_tracker = DictionaryTracker::new(false);
+            let mut encoded = Vec::new();
+            let schema_data = data_gen.schema_to_bytes_with_dictionary_tracker(
+                &schema,
+                &mut dictionary_tracker,
+                &options,
+            );
+            write_message(&mut encoded, schema_data, &options).unwrap();
+
+            let (encoded_dictionaries, encoded_batch) = data_gen
+                .encode(
+                    &batch,
+                    &mut dictionary_tracker,
+                    &options,
+                    &mut ipc_write_context,
+                )
+                .unwrap();
+            for dictionary in encoded_dictionaries {
+                write_message(&mut encoded, dictionary, &options).unwrap();
+            }
+            write_message(&mut encoded, encoded_batch, &options).unwrap();
+
+            // Reading must not depend on the block size the writer chose.
+            let mut reader = 
StreamReader::try_new(Cursor::new(encoded.as_slice()), None).unwrap();
+            assert_eq!(reader.next().unwrap().unwrap(), batch, 
"{block_size:?}");
+            assert!(reader.next().is_none());
+
+            outputs.push(encoded);
+        }
+
+        // The option must reach the encoder: an explicitly configured default 
is byte
+        // identical to the untouched default, while every other size changes 
the frame
+        // header and therefore the output.
+        assert_eq!(
+            outputs[0], outputs[2],
+            "explicit 256 KiB must match the default"
+        );
+        assert_ne!(outputs[0], outputs[1], "64 KiB must differ from default");
+        assert_ne!(outputs[0], outputs[3], "1 MiB must differ from default");
+        assert_ne!(outputs[0], outputs[4], "4 MiB must differ from default");
+    }
+
     #[test]
     #[cfg(feature = "zstd")]
     fn test_write_file_with_zstd_compression() {

Reply via email to