Repository navigation
Description
(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: 1104Expected 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
tustvold commentedon Aug 22, 2023
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
ChristianBeilschmidt commentedon Aug 23, 2023
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.
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.
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 👍 .
v0y4g3r commentedon Oct 29, 2023
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?
tustvold commentedon Oct 29, 2023
Have you tried running with a memory profiler like heaptrack, the code you've provided will count the same allocations multiple times
ChristianBeilschmidt commentedon Nov 2, 2023
@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.
tustvold commentedon Nov 2, 2023
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
But at least in the example provided by @v0y4g3r the issue might simply be one of accounting