Skip to content

Size of (IPC) decompressed data can be larger then the original data #4724

Open

Description

@jdroenner

(Don't really know if this is a bug or a feature)

Describe the bug
We have a use-case where we want to store Arrow data (StructArray) compressed in memory. Currently the best way for this appears to be the IPC FileWriter with compression and then storing the compressed bytes. For our use-case it is important to know that the uncompressed data has the same size in memory as the original input.

Using the FileReader we noticed that our assumption, that the decompressed data has the same size as the original input, does not hold. There is a case that can cause the memory footprint of the decompressed data to become ~ "decompressed bytes + compressed bytes".

If CompressionCodec decompress_to_buffer detects an uncompressed slice of data (decompressed_length == LENGTH_NO_COMPRESSED_DATA) it returns a new Buffer that uses a pointer into the Buffer that holds the raw bytes produced by the reader. This causes the raw Buffer to be kept in memory. Additionally the compressed data slices are decompressed into new Buffers that use newly allocated memory.

To Reproduce
The easiest way is to create a StructArray with one column that is good to compress and one that is not:

use std::{io::Cursor, sync::Arc};

use arrow::{
    array::{Array, ArrayRef, Int32Array, StringArray, StructArray},
    datatypes::{DataType, Field, Fields},
    ipc::{
        writer::{FileWriter, IpcWriteOptions},
        CompressionType,
    },
    record_batch::RecordBatch,
};

fn main() {
    // Setup StructArray with two columns
    let primes = Arc::new(Int32Array::from(vec![
        31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79,
    ]));
    let strings = Arc::new(StringArray::from(vec![
        "Hello world one",
        "Hello world two",
        "Hello world three",
        "Hello world four",
        "Hello world five",
        "Hello world six",
        "Hello world seven",
        "Hello world eight",
        "Hello world nine",
        "Hello world ten",
        "Hello world eleven",
        "Hello world twelve",
    ]));
    let table = StructArray::new(
        Fields::from(vec![
            Field::new("primes", DataType::Int32, false),
            Field::new("strings", DataType::Utf8, false),
        ]),
        vec![primes as ArrayRef, strings as ArrayRef],
        None,
    );
    // Print the size of the original data
    println!("Original size: {:?}", table.get_array_memory_size());

    // Write to file with compression
    let record_batch = RecordBatch::from(&table);
    let mut file_writer = FileWriter::try_new_with_options(
        Vec::new(),
        record_batch.schema().as_ref(),
        IpcWriteOptions::default()
            .try_with_compression(Some(CompressionType::LZ4_FRAME))
            .unwrap(),
    )
    .unwrap();
    file_writer.write(&record_batch).unwrap();
    file_writer.finish().unwrap();
    let bytes = file_writer.into_inner().unwrap();
    // Print the size of the compressed data
    println!("Compressed size: {:?}", bytes.len());

    // Read from file and decompress
    let mut reader = arrow::ipc::reader::FileReader::try_new(Cursor::new(bytes), None).unwrap();
    let record_batch = reader.next().unwrap().unwrap();
    let sr = StructArray::from(record_batch);
    // Print the size of the decompressed data
    println!("Decompressed size: {:?}", sr.get_array_memory_size());
}

The output will be something like this:

Original size: 688
Compressed size: 950
Decompressed size: 1104

Expected behavior
We expected the decompressed data to use the same amount of memory as the original data.
An easy way to fix this would be to change the "uncompressed in compressed" case in decompress_to_buffer to return a real copy of the uncompressed data slice.
The easy fix, might cause a lot of memcopys in cases where compression was preferred but a lot of data could not be compressed. To make the behavior a user choice, we could add a "copy_uncompressed" parameter to the decompress_to_buffer method. Since the user only has access to readers, this should probably be set as a reader option that is passed down to the decompression step...

Additional context

Activity

  1. added
    bug
    on Aug 22, 2023
  2. tustvold commented on Aug 22, 2023

    @tustvold
    Contributor

    We generally try very hard to avoid copying data, as it is a major bottleneck and typically not desirable. The downside as you have discovered is potentially higher memory usage. Another area this turns up in is array slicing, which is zero-copy in a similar manner.

    I'm not averse to adding a kernel or function on Array to "compact" the underlying buffers of an array, but I wonder if you've experimented with writing the data in smaller batches?

    Ultimately if the size of an encoded RecordBatch is large enough to cause concern, you're going to struggle to process it without blowing your memory budget regardless... A smaller batch size might let you get the best of both worlds, zero-copy without blowing your memory budget?

    Edit: changed this to be a feature request as the reader is behaving as intended

  3. added
    enhancement
    and removed
    bug
    on Aug 22, 2023
  4. ChristianBeilschmidt commented on Aug 23, 2023

    @ChristianBeilschmidt
    Contributor

    We generally try very hard to avoid copying data, as it is a major bottleneck and typically not desirable. The downside as you have discovered is potentially higher memory usage. Another area this turns up in is array slicing, which is zero-copy in a similar manner.

    There is no one-size-fits-all I guess. Zero-copy is one intended behavior and memory efficiencies or guarantees another one. Optimally, developers can decide on this.

    I'm not averse to adding a kernel or function on Array to "compact" the underlying buffers of an array, but I wonder if you've experimented with writing the data in smaller batches?

    Such a kernel could be quite efficient, right? We only would need to compact the arrays that aren't compacted and leave the rest as it is.

    Would this be better than adding a config param to the decompress method? The zero-copy thing is more of a special case optimization than a general thing since you cannot point to the buffer data if the data is compressed. In the default case, you couldn't do it anyway.

    Ultimately if the size of an encoded RecordBatch is large enough to cause concern, you're going to struggle to process it without blowing your memory budget regardless... A smaller batch size might let you get the best of both worlds, zero-copy without blowing your memory budget?

    Our use case is more concerned about having lots of records/arrays around in the system and keeping track of overall limits, e.g., having N data chunks (of different data) that do not get larger after compressing/decompressing them. Thus, it is plainly super inconvenient that data becomes larger after a compress-decompress step. I guess twice the size is the upper limit in the current approach. But thank you for the suggestion 👍 .

  5. v0y4g3r commented on Oct 29, 2023

    @v0y4g3r

    Ran into the same problem here. What's worse is that the difference between decoded data size and real data size grows disproportionately to number of fields in record batch.

    I wonder if we can simply shrink the buffer of arrays after we know the exact number of elements, at least for primitive arrays?

    image
    use arrow_array::{ArrayRef, PrimitiveArray, RecordBatchWriter};
    use arrow_ipc::writer::FileWriter;
    use arrow_schema::DataType;
    use datatypes::types::Int64Type;
    
    fn encode_and_decode(num_fields: usize) -> (usize, usize) {
        let fields = (0..num_fields)
            .map(|idx| {
                arrow::datatypes::Field::new(
                    &format!("f_{idx}"),
                    arrow::datatypes::DataType::Float64,
                    false,
                )
            })
            .collect::<Vec<_>>();
    
        let schema = Arc::new(arrow::datatypes::Schema::new(fields));
    
        let mut buffer = vec![];
        let mut writer = FileWriter::try_new(&mut buffer, &*schema).unwrap();
    
        let col_values = (0..num_fields)
            .map(|idx| {
                Arc::new(PrimitiveArray::<arrow_array::types::Float64Type>::from(
                    vec![1.0],
                )) as ArrayRef
            })
            .collect::<Vec<_>>();
        let rb = arrow::record_batch::RecordBatch::try_new(schema.clone(), col_values).unwrap();
    
        let write_mem_size = rb.get_array_memory_size();
        writer.write(&rb).unwrap();
        writer.close().unwrap();
    
        let mut reader =
            arrow::ipc::reader::FileReader::try_new(std::io::Cursor::new(&buffer), None).unwrap();
        let rb = reader.next().unwrap().unwrap();
        let read_mem_size = rb.get_array_memory_size();
        return (write_mem_size, read_mem_size);
    }
    
    fn main() {
        for num_cols in (0..51).step_by(10).skip(1) {
            let (write, read) = encode_and_decode(num_cols);
            println!("{},{},{}", num_cols, write, read)
        }
    }
  6. tustvold commented on Oct 29, 2023

    @tustvold
    Contributor

    Have you tried running with a memory profiler like heaptrack, the code you've provided will count the same allocations multiple times

  7. ChristianBeilschmidt commented on Nov 2, 2023

    @ChristianBeilschmidt
    Contributor

    @tustvold could you point to the multiple counting of the example above?

    I see the original view of not making it a default, but I still would love to have some feedback on the compaction kernel vs. adding an option approach. If there is some common understanding, maybe I can try to come up with something.

  8. tustvold commented on Nov 2, 2023

    @tustvold
    Contributor

    get_array_memory_size returns the total capacity of all the buffers backing the array, e.g. https://github.com/apache/arrow-rs/blob/master/arrow-array/src/array/boolean_array.rs#L305C44-L305C66

    If those buffers are slices of the same underlying allocation, as they will be in the above example, you will count that allocation multiple times.

    FWIW it is relatively trivial to rewrite an array if you so wish

    let data = array.to_data();
    let mutable = MutableArrayData::new(vec![&data], false, 0);
    mutable.extend(0, 0, array.len());
    let compacted = make_array(mutable.freeze());
    

    But at least in the example provided by @v0y4g3r the issue might simply be one of accounting

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions