Skip to content

perf(arrow-ipc): decode lz4 frames of independent blocks without a streaming decoder - #12423

Open
ariel-miculas wants to merge 5 commits into
apache:mainfrom
ariel-miculas:improve-lz4-decoder-performance-11129
Open

ariel-miculas wants to merge 5 commits into
apache:mainfrom
ariel-miculas:improve-lz4-decoder-performance-11129

Conversation

@ariel-miculas

@ariel-miculas ariel-miculas commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

Rationale for this change

decompress_lz4 built an lz4_flex::frame::FrameDecoder per buffer, and none of
that decoder's streaming machinery is needed for the frames IPC actually carries.

FrameDecoder sizes its source and destination buffers from the maximum block
size the frame's header declares, and zero-fills the destination up to that
maximum before each block, whatever the block holds. The format lets a writer
declare 4 MiB blocks for a buffer of any size -- lz4_flex's own encoder does so
for anything over 256 KiB -- so decoding a few KiB can cost megabytes of memset,
and an IPC message decodes one buffer after another: one per field node plus its
validity and offsets.

Pooling one decoder in DecompressionContext, as the zstd arm already does for
its decompressor, removes the repeated construction but not the zero-fill, which
happens once per block rather than once per decoder. A decoder cannot in fact be
carried between frames at all: FrameDecoder asserts its destination capacity
equals the declared maximum exactly, which a decoder that has seen a linked frame
no longer satisfies, and that assertion fires in debug builds as soon as frames
of differing block modes go through one decoder.

The uncompressed length is already known from the IPC prefix, so the blocks can
instead be decompressed one after another straight into the output with
lz4_flex::block::decompress_into: no scratch buffer, nothing zeroed beyond the
output, and no dependence on what the header declares. A frame outside that shape
-- linked blocks, a block or content checksum, a dictionary -- still goes to the
streaming decoder, with a decoder of its own as before. Independent blocks and no
checksums is what every Arrow writer produces.

What changes are included in this PR?

New benchmarks to cover lz4 decompression and the performance fix.

Are these changes tested?

New tests cover both paths against every frame shape: independent and linked
blocks, with and without a content checksum, over compressible and incompressible
payloads, plus truncated frames.

Measured through arrow-ipc/benches/ipc_reader.rs, reading 10 batches end to end
(decompression is only part of each figure):

benchmark before after change
no_validation/read_10/lz4 2.14 ms 1.95 ms −8.4%
wide_200x4096/lz4_64kib_blocks 7.44 ms 4.15 ms −44.3%
wide_200x4096/lz4_4096kib_blocks 68.81 ms 4.16 ms −93.9%
wide_20x131072/lz4_64kib_blocks 15.30 ms 11.53 ms −24.1%
wide_20x131072/lz4_4096kib_blocks 21.38 ms 11.55 ms −45.4%

Counted with the system allocator wrapped in a GlobalAlloc that tallies every
allocation, over the same reads of 10 batches -- so these are a census, not a
sample, and the uncompressed and zstd columns are controls that do not move:

shape blocks allocations bytes allocated peak live
4×8192 64 KiB 526 → 366 12.47 → 2.47 MiB 0.37 → 0.25 MiB
4 MiB 526 → 366 642.47 → 2.47 MiB 8.25 → 0.25 MiB
200×4096 64 KiB 24,449 → 16,449 562.94 → 62.94 MiB 6.42 → 6.30 MiB
4 MiB 24,449 → 16,449 32,062.94 → 62.94 MiB 14.30 → 6.30 MiB
20×131072 64 KiB 2,483 → 1,683 246.84 → 196.84 MiB 19.81 → 19.68 MiB
4 MiB 2,483 → 1,683 3,396.82 → 196.82 MiB 27.68 → 19.68 MiB

Every delta accounts for itself exactly. The counts fall by 160, 8000 and 800
against 80, 4000 and 400 compressed buffers: two allocations per buffer, the
decoder's src and dst, and what remains matches the zstd arm, which already
pools its decompressor. The bytes fall by 10.00, 500.00 and 1625.00 MiB, which
is 80 and 4000 buffers times a 64 KiB src plus a 64 KiB dst, and -- where
the buffers pass 256 KiB and the frames declare 4 MiB blocks -- 200 values
buffers times 8 MiB plus 200 validity buffers times 128 KiB. On that last shape
the decoder allocated 9.3 times the memory it was decoding.

Allocation count is not the whole cost: dst is grown with Vec::resize, which
zero-fills, so a 4 MiB block mode also memsets 4 MiB per buffer that the decode
then overwrites in full. The bytes column stands in for that memset, since the
same resize both allocates and zeroes.

Are there any significant user-facing changes?

No

AI usage disclosure

Generated with AI

@boring-cyborg boring-cyborg Bot added the arrow-ipc arrow-ipc crate label Nov 23, 2026
ariel-miculas and others added 2 commits November 23, 2026 18:36
…size

`ipc_reader` covers lz4 at one shape: four columns of 8192 rows, at whatever
maximum block size the writer's default declares. Two things that decide what
lz4 decompression costs are invisible there.

The first is how many buffers a message holds. A message carries one compressed
buffer per field node plus its validity and offsets, each its own frame, so the
per-buffer cost is most of what a wide relation pays and a four-column shape
barely shows it. 200 columns of 4096 rows keeps every buffer small; 20 columns
of 131072 rows makes each values buffer half a megabyte.

The second is the maximum block size the frame's header declares, which is what
a frame costs a streaming decoder to open whatever the buffer behind it holds.
The lz4 cases set it explicitly with `try_with_lz4_block_size` rather than
leaving it to the writer's default, and run at both 64 KiB and 4 MiB -- 4 MiB
being what Arrow C++ and Comet declare. Leaving it implicit would also tie the
benchmark to a writer default that has already changed once.

Each shape runs at zstd too, as a control: zstd is untouched by work on the lz4
decoder, so a zstd row that moves is the machine, not the change.

Co-Authored-By: Claude Opus 5 <[email protected]>
…ing decoder

`decompress_lz4` opens an `lz4_flex::frame::FrameDecoder` per buffer, and none
of that decoder's streaming machinery is needed for the frames IPC carries.

`FrameDecoder` sizes its source and destination buffers from the maximum block
size the frame's header *declares*, and zero-fills the destination up to that
maximum before each block, whatever the block holds. The declared maximum has
nothing to do with how much data is behind it: a writer may declare 4 MiB blocks
for a buffer of any size, and Arrow C++ and Comet do. So decoding a few KiB can
cost megabytes of memset, and an IPC message decodes one buffer after another --
one per field node plus its validity and offsets, each its own frame.

Pooling one decoder in `DecompressionContext`, as the zstd arm already does for
its decompressor, would remove the repeated construction but not the zero-fill,
which happens once per block rather than once per decoder. A decoder cannot in
fact be carried between frames at all: `FrameDecoder` asserts its destination
capacity equals the declared maximum exactly, which a decoder that has seen a
linked frame no longer satisfies, and that assertion fires in debug builds as
soon as frames of differing block modes go through one decoder.

The blocks can instead be decompressed one after another straight into the
output with `lz4_flex::block::decompress_into`: no scratch buffer, nothing
zeroed beyond the output, and no dependence on what the header declares. A frame
outside that shape -- linked blocks, a block or content checksum, a dictionary,
a block size the format does not define -- still goes to the streaming decoder,
with a decoder of its own as before. Independent blocks and no checksums is what
every Arrow writer produces.

Like the streaming path, this never sizes the output from the advertised length
alone. That length comes from the IPC prefix and is untrusted, so the output
starts at no more than `MAX_PREALLOC_BYTES` and grows only as the blocks fill
it, bounded per block by the frame's declared maximum and by what the advertised
length leaves. A frame holding more than it advertised is reported as such
rather than decoded.

Measured through `arrow-ipc/benches/ipc_reader.rs`, reading 10 batches end to
end, so decompression is only part of each figure:

    no_validation/read_10/lz4                     2.14 ms ->  1.95 ms   -8.4%
    wide_200x4096/lz4_64kib_blocks                7.44 ms ->  4.15 ms  -44.3%
    wide_200x4096/lz4_4096kib_blocks             68.81 ms ->  4.16 ms  -93.9%
    wide_20x131072/lz4_64kib_blocks              15.30 ms -> 11.53 ms  -24.1%
    wide_20x131072/lz4_4096kib_blocks            21.38 ms -> 11.55 ms  -45.4%

Both zstd rows are unchanged (p = 0.15 and 0.13), and the two block sizes now
converge: what the header declares no longer decides what the read costs.

Allocations counted with the system allocator wrapped in a `GlobalAlloc` that
tallies every one, over the same reads -- a census, not a sample. Bytes and peak
in MiB; the zstd rows do not move and are left out:

    shape      blocks     allocations     bytes allocated       peak live
    4x8192     64 KiB    526 ->   366   12.47 ->     2.47    0.37 -> 0.25
               4 MiB     526 ->   366  642.47 ->     2.47    8.25 -> 0.25
    200x4096   64 KiB  24449 -> 16449  562.94 ->    62.94    6.42 -> 6.30
               4 MiB   24449 -> 16449  32062.94 ->  62.94   14.30 -> 6.30
    20x131072  64 KiB   2483 ->  1683  246.84 ->   196.84  19.81 -> 19.68
               4 MiB    2483 ->  1683  3396.82 ->   196.82  27.68 -> 19.68

Every delta accounts for itself exactly. The counts fall by 160, 8000 and 800
against 80, 4000 and 400 compressed buffers: two allocations per buffer, the
decoder's `src` and `dst`, and what remains matches the zstd arm, which already
pools its decompressor. The bytes fall by twice the declared block size per
buffer -- 80, 4000 and 400 buffers times 128 KiB, then times 8 MiB -- to the
byte in all six rows. On 200 columns at 4 MiB blocks that is 31.3 GiB allocated
to read a 30 MiB stream, and the figures no longer vary with the declared size
at all.

Measured as well through a Comet in-memory cache read, where each column's
buffers are compressed one at a time and the frames declare 4 MiB blocks. 5M
rows by 6 columns, full projection: 1105 ms to 259 ms. On a 300-column relation,
where a cached batch holds hundreds of buffers, 7519 ms to about the time the
same workload takes when the writer declares 64 KiB blocks instead.

New tests cover both paths against every frame shape: independent and linked
blocks, with and without a content checksum, over compressible and
incompressible payloads, plus truncated frames.

This is apache#11129, which was closed by apache#12084 -- that
PR pooled the frame *encoder* in `IpcWriteContext` and left the decoder as it
was.

Co-Authored-By: Claude Opus 5 <[email protected]>
@ariel-miculas

ariel-miculas commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor Author

I didn't include the counting allocator code, I'm pasting it below arrow-ipc/examples/count_decode_allocations.rs:

//! Counts every heap allocation made while reading an IPC stream.
//!
//! Run with:
//!
//! ```text
//! cargo run --release --example count_decode_allocations --features lz4,zstd
//! ```
//!
//! A `#[global_allocator]` wrapping [`System`] sees every allocation the process makes -- this
//! crate's, its dependencies', and `std`'s -- so what this prints is a census rather than a
//! profiler's sample, and the figures come out as exact integers. That makes it the right
//! instrument for a question a flamegraph cannot answer: *how many* allocations, and of what
//! size, does decoding a message cost?
//!
//! Three details matter for reading the output:
//!
//! - `realloc` counts as one allocation and contributes only its growth. This is load-bearing:
//!   `Vec::resize` -- which zero-fills, and which `lz4_flex`'s `FrameDecoder` uses to grow its
//!   destination buffer to the frame's *declared* maximum block size -- grows through `realloc`,
//!   not `alloc`. A wrapper hooking only `alloc` would miss it entirely.
//! - Each row does one throwaway read before measuring, then resets the counters, so lazy
//!   one-time initialisation is not charged to the measured read.
//! - The counters cover the whole read, array construction included, so the uncompressed row --
//!   not zero -- is the floor to read each compressed row against.

use arrow_array::RecordBatch;
use arrow_array::builder::Int32Builder;
use arrow_ipc::CompressionType;
use arrow_ipc::reader::StreamReader;
use arrow_ipc::writer::{IpcWriteOptions, StreamWriter};
use arrow_schema::{DataType, Field, Schema};
use std::alloc::{GlobalAlloc, Layout, System};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};

static COUNT: AtomicUsize = AtomicUsize::new(0);
static BYTES: AtomicUsize = AtomicUsize::new(0);
static LIVE: AtomicUsize = AtomicUsize::new(0);
static PEAK: AtomicUsize = AtomicUsize::new(0);

struct Counting;

// SAFETY: every method forwards to `System` with the layout it was given, and the counters are
// plain atomics that allocate nothing themselves, so no method can re-enter the allocator.
unsafe impl GlobalAlloc for Counting {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        COUNT.fetch_add(1, Relaxed);
        BYTES.fetch_add(layout.size(), Relaxed);
        let live = LIVE.fetch_add(layout.size(), Relaxed) + layout.size();
        PEAK.fetch_max(live, Relaxed);
        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, new_size: usize) -> *mut u8 {
        COUNT.fetch_add(1, Relaxed);
        if let Some(growth) = new_size.checked_sub(layout.size()) {
            BYTES.fetch_add(growth, Relaxed);
            let live = LIVE.fetch_add(growth, Relaxed) + growth;
            PEAK.fetch_max(live, Relaxed);
        } else {
            LIVE.fetch_sub(layout.size() - new_size, Relaxed);
        }
        unsafe { System.realloc(ptr, layout, new_size) }
    }
}

// `alloc_zeroed` is deliberately not overridden: its default implementation calls `self.alloc`,
// so those allocations are counted by the method above.
#[global_allocator]
static ALLOCATOR: Counting = Counting;

const BATCHES: usize = 10;

/// A batch of `cols` nullable Int32 columns of `rows` rows, so a message carries many compressed
/// buffers -- one per field node, plus its validity -- rather than a few large ones.
fn wide_batch(cols: usize, rows: usize) -> RecordBatch {
    let schema = Arc::new(Schema::new(
        (0..cols)
            .map(|i| Field::new(format!("c{i}"), DataType::Int32, true))
            .collect::<Vec<_>>(),
    ));
    let columns = (0..cols)
        .map(|col| {
            let mut builder = Int32Builder::with_capacity(rows);
            for row in 0..rows {
                if row % 10 == 0 {
                    builder.append_null();
                } else {
                    builder.append_value((row * (col + 1)) as i32);
                }
            }
            Arc::new(builder.finish()) as _
        })
        .collect::<Vec<_>>();
    RecordBatch::try_new(schema, columns).unwrap()
}

fn stream(
    batch: &RecordBatch,
    compression: Option<CompressionType>,
    lz4_block_size: Option<usize>,
) -> Vec<u8> {
    let mut options = IpcWriteOptions::default();
    if let Some(compression) = compression {
        options = options
            .try_with_compression(Some(compression))
            .unwrap_or_else(|e| {
                panic!("{compression:?} unavailable -- build with that feature: {e}")
            });
    }
    if lz4_block_size.is_some() {
        options = options.try_with_lz4_block_size(lz4_block_size).unwrap();
    }
    let mut buffer = Vec::new();
    let mut writer =
        StreamWriter::try_new_with_options(&mut buffer, batch.schema().as_ref(), options).unwrap();
    for _ in 0..BATCHES {
        writer.write(batch).unwrap();
    }
    writer.finish().unwrap();
    buffer
}

fn read_all(bytes: &[u8]) -> usize {
    let reader = StreamReader::try_new(bytes, None).unwrap();
    reader.map(|b| b.unwrap().num_rows()).sum()
}

fn measure(shape: &str, codec: &str, bytes: &[u8]) {
    // Flush any lazy one-time allocation out of the way before the counters are reset.
    std::hint::black_box(read_all(bytes));

    COUNT.store(0, Relaxed);
    BYTES.store(0, Relaxed);
    let base = LIVE.load(Relaxed);
    PEAK.store(base, Relaxed);

    let rows = read_all(bytes);

    let mib = |n: usize| n as f64 / (1024.0 * 1024.0);
    println!(
        "{shape:<12} {codec:<8} {:>9} {:>14.2} MiB {:>10.2} MiB {:>10.2} MiB   {rows} rows in {BATCHES} batches",
        COUNT.load(Relaxed),
        mib(BYTES.load(Relaxed)),
        mib(PEAK.load(Relaxed).saturating_sub(base)),
        mib(bytes.len()),
    );
}

fn main() {
    println!(
        "{:<12} {:<8} {:>9} {:>18} {:>14} {:>14}",
        "shape", "codec", "allocs", "bytes allocated", "peak live", "stream size"
    );

    // 4x8192 is the shape `benches/ipc_reader.rs` has always used; 200x4096 keeps every buffer
    // small; 20x131072 makes each values buffer half a megabyte. The lz4 rows declare their
    // maximum block size explicitly, since that -- not the size of the buffer behind it -- is
    // what sizes a streaming decoder's scratch buffers.
    for (shape, cols, rows) in [
        ("4x8192", 4, 8192),
        ("200x4096", 200, 4096),
        ("20x131072", 20, 131072),
    ] {
        let batch = wide_batch(cols, rows);
        for (codec, compression, block) in [
            ("none", None, None),
            ("lz4/64k", Some(CompressionType::LZ4_FRAME), Some(64 * 1024)),
            (
                "lz4/4M",
                Some(CompressionType::LZ4_FRAME),
                Some(4 * 1024 * 1024),
            ),
            ("zstd", Some(CompressionType::ZSTD), None),
        ] {
            let bytes = stream(&batch, compression, block);
            measure(shape, codec, &bytes);
        }
        println!();
    }
}

@ariel-miculas
ariel-miculas force-pushed the improve-lz4-decoder-performance-11129 branch from 08dca2d to d85ea4c Compare November 23, 2026 16:45
Comment thread arrow-ipc/src/compression.rs Outdated
at,
decompressed_size,
block_max,
UNCOMPRESSED_BLOCK,

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.

Does this const value need to be passed as an argument to the private function defined in the same module?

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.

indeed, no need to pass it as a parameter

Comment thread arrow-ipc/src/compression.rs Outdated
Comment on lines +545 to +548
// `room` ran out at the advertised size rather than at the block maximum, so the
// frame holds more than the IPC prefix said it would.
if room == decompressed_size - written {
exceeds()

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.

Should the error be inspected before deciding this is the cause?

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.

addressed

ariel-miculas and others added 3 commits November 23, 2026 21:17
The error mapping decided that a block had overrun the advertised size by
looking only at which limit capped the destination slice. That test is
necessary but not sufficient: on the last block of a well-formed frame the
destination is capped by the advertised size as well, so a genuinely corrupt
final block reported "exceeds advertised size" and dropped the real
diagnostic.

Require the error to be `DecompressError::OutputTooSmall` as well, and let
the four corruption variants through as themselves.

The stored-block path conflated the same two cases, decided there by the
block length rather than the error. A block wider than the frame's own
declared maximum is a corrupt frame, not an over-long one, and now says so.

Co-Authored-By: Claude Opus 5 <[email protected]>

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

Looks good, thanks!

This branch has not been deployed

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

Labels

arrow-ipc arrow-ipc crate

Projects

None yet

Development

Successfully merging this pull request may close these issues.

IPC LZ4 decompression allocates and zero-fills a fresh FrameDecoder per buffer

2 participants