ariel-miculas opened a new pull request, #12423:
URL: https://github.com/apache/arrow-rs/pull/12423
# Which issue does this PR close?
- Closes #11129
# 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 | improvement | delta
--- | --- | ---
StreamReader/read_10/lz4 | 763 us -> 687 us | -9.8%
StreamReader/no_validation/read_10/lz4 | 656 us -> 565 us |-13.9%
StreamReader/read_10/wide_200x4096/lz4 | 6.88 ms -> 4.27 ms |-37.9%
StreamReader/read_10/wide_20x131072/lz4 | 18.6 ms -> 11.8 ms |-36.5%
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 | codec | allocations | bytes allocated |
peak live
--- | --- | --- | --- | ---
4x8192 |none | 206 | 1.30 MiB | 0.13 MiB
4x8192 |lz4 | 526 -> 366 | 12.47 -> 2.47 MiB | 0.37
-> 0.25
4x8192 |zstd | 366 | 1.95 MiB | 0.20 MiB
200x4096 |none | 8449 | 32.82 MiB | 3.29 MiB
200x4096 |lz4 | 24449 -> 16449 | 562.96 -> 62.96 MiB | 6.43 ->
6.30
200x4096 |zstd | 16449 | 53.52 MiB | 5.36 MiB
20x131072 |none | 883 | 103.19 MiB | 10.32
MiB
20x131072 |lz4 | 2483 -> 1683 | 1821.83 -> 196.83 MiB | 27.68
-> 19.68
20x131072 |zstd | 1683 | 166.45 MiB | 16.65
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.
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>) ->
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}")
});
}
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:<6} {:>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} {:<6} {:>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 puts each values buffer over 256 KiB, which is where
`lz4_flex`'s encoder
// stops declaring 64 KiB blocks and declares 4 MiB ones instead.
for (shape, cols, rows) in [
("4x8192", 4, 8192),
("200x4096", 200, 4096),
("20x131072", 20, 131072),
] {
let batch = wide_batch(cols, rows);
for (codec, compression) in [
("none", None),
("lz4", Some(CompressionType::LZ4_FRAME)),
("zstd", Some(CompressionType::ZSTD)),
] {
let bytes = stream(&batch, compression);
measure(shape, codec, &bytes);
}
println!();
}
}
```
# Are there any significant user-facing changes?
No
# AI usage disclosure
Generated with AI
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]