You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
flight_data_from_arrow_batch sends too much data #208
Arrow arrays can share the same backing store, even if the array is just a "view" of a slice of another array.
Yet, when flight_data_from_arrow_batch encodes the arrays into a FlightData, it blindly copies the entire buffer ready to be sent over the wire.
Thus, for example, when DataFusion uses the arrow::compute::limit operator to return a few elements of an array, we still end up with a the full (potentially) large array being sent over the wire.
Since encoding the array in a FlightData involves copying the data anyway, perhaps it would be beneficial to take the Array length in consideration and copy only the parts of the buffer that contain actual data.
@alamb im interested in looking into this. i see it's been open for a while - can you confirm this is still an issue / if there is any additional context that has come up since this was initially raised? Thx!
And the issue is that the data buffer points to the original larger array. Then, that larger array is ultimately turned into the FlightData which is a waste.
Assuming that's all correct is there a preference as to where a fix should be applied? i.e. whether at flight_data_from_arrow_batch, encoded_batch, or record_batch_to_bytes?
Naively I was thinking at the record_batch_to_bytes level - but i think that might impact IPC in general. Im still figuring out the separation between IPC and Flight functionality though and if this issue is focused only on updating how array data is handled for Flight or for IPC in general. If we wanted it to be closer to the Flight level then i think copying the RecordBatch in flight_data_from_arrow_batch before passing it to encoded_batch would be the way.
What do you think?
Separately, ive been looking if there are any methods / helpers for recreating a RecordBatch out of the data / offsets / len of another RecordBatch. Dont think ive found anything though. If thats the case would the idea be to just remake the batch from scratch with the data from the original?
And the issue is that the data buffer points to the original larger array. Then, that larger array is ultimately turned into the FlightData which is a waste.
Yes, that is the crux of the issue we found.
Assuming that's all correct is there a preference as to where a fix should be applied? i.e. whether at flight_data_from_arrow_batch, encoded_batch, or record_batch_to_bytes?
I am not sure to be honest as I am not familiar with the flight code. Perhaps @nevi-me or @jorgecarleitao who have more experience in how IPC / flight is supposed to work might have thoughts on how to handle serializing bytes for an Array whose backing Buffer is much larger. Another avenue we can explore is to review how the C++ implementation handles the case and/or ask about this on [email protected].
One way to reduce potential unintended side effects could be to make the optimization optional (an option on IpcWriteOptions, perhaps) while we test it out more broadly, and then switch the default value in a later version.
Naively I was thinking at the record_batch_to_bytes level - but i think that might impact IPC in general.
Yes. However, maybe that is ok (as that seems to be optimizing the serialization of Arrow Arrays). However, I am not sure what the expectations are here.
Separately, ive been looking if there are any methods / helpers for recreating a RecordBatch out of the data / offsets / len of another RecordBatch.
I am not sure to be honest as I am not familiar with the flight code. Perhaps @nevi-me or @jorgecarleitao who have more experience in how IPC / flight is supposed to work might have thoughts on how to handle serializing bytes for an Array whose backing Buffer is much larger. Another avenue we can explore is to review how the C++ implementation handles the case and/or ask about this on [email protected].
One way to reduce potential unintended side effects could be to make the optimization optional (an option on IpcWriteOptions, perhaps) while we test it out more broadly, and then switch the default value in a later version.
I am not sure about the root cause of this, but some time ago we merged something like this in arrow2, could you check if jorgecarleitao/arrow2#194, specifically around write_generic_binary in src/io/ipc/write/serialize.rs is what we are looking for here?
Note that the code is significantly different at this point, but the gist is that we need to check if the array was sliced, and if it was, only write the relevant values.
I was going to suggest the same thing, that we only materialise and write
the length that excludes the offsets.
It's something fundamental that I missed when working on the IPC support. I
think that when writing data in IPC we should reset the offsets to 0 and
only write the relevant data.
@jorgecarleitao I believe this is done in write_generic_binary using
let first = *offsets.first().unwrap();
let last = *offsets.last().unwrap();
and then writing to buffer based on those values.
That will apply for strings, lists and binaries, but the overall problem is the below.
We writeBuffers to IPC, and those buffers have a length and an offset (almost always 0). The problem is that when we write a buffer, we have to determine what its correct offset and length is, and the current APis in the crate can't give us that information conveniently.
buffer 1:type = i32, offset = 8(2*4 bytes), len = 8(2*4 bytes)
buffer 2:type = i64, offset = 24(3*8 bytes), len = 24(3*8)// notice how the offset is 3 becaues of the list's first offset, and length is 3 because (6 - 3) on the offsets (and the child data has 3 values)
buffer 3:type = bool, offset = 0(3 offsets don't cross a byte boundary), len = 1 byte 0b00000_010
The root of the challenge above comes from the signature of arrow::buffer::immutable::Buffer
/// Buffer represents a contiguous memory region that can be shared with other buffers and across/// thread boundaries.#[derive(Clone,PartialEq,Debug)]pubstructBuffer{/// the internal byte buffer.data:Arc<Bytes>,/// The offset into the buffer.offset:usize,}
and the current state that the only method that sets the offset above is
pubfnslice(&self,offset:usize) -> Self{assert!(
offset <= self.len(),"the offset of the new Buffer cannot exceed the existing length");Self{data:self.data.clone(),offset:self.offset + offset,}}
One of the foundations of arrow2 is that a Buffer knows its offset and length based on its content. If a string buffer is created with "hello", "you", "world", a slice of 2 means that the buffer will know to offset 8 bytes, making the IPC process easy (@jorgecarleitao this is my understanding without having checked the code as I write this).
So, to only write the correct amount of data in IPC, my approach would be to modify arrow::ipc::writer::fn write_array_data() to account for the offset and correct length, and probably change write_buffer() in the same module to take the sliced bytes instead of Buffer.
@nevi-me thank you for the detailed explanation. very helpful. im working through some examples on my side to solidify my understanding and will come back if any questions else will just open a PR for a fix.
hi @nevi-me - ive been building up a test that i could use to compare the ipc size pre and post the fix. but i havent been able to produce the expected results. Code is below:
pub fn compare_ipc() {
let arr_data = vec![1, 2, 3, 4, 5];
let val_data = vec![5, 6, 7, 8, 9];
let id_arr = Int32Array::from(arr_data);
let val_arr = Int32Array::from(val_data);
let id_arr_slice = id_arr.slice(1, 3);
let val_arr_slice = val_arr.slice(1, 3);
let schema = Schema::new(vec![
Field::new("id", DataType::Int32, false),
Field::new("val", DataType::Int32, false),
]);
let raw_batch = RecordBatch::try_new(
Arc::new(schema.clone()),
vec![Arc::new(id_arr), Arc::new(val_arr)],
)
.unwrap();
println!("{:?}", raw_batch);
let slice_batch =
RecordBatch::try_new(Arc::new(schema.clone()), vec![id_arr_slice, val_arr_slice]).unwrap();
println!("{:?}", slice_batch);
println!("Running first test");
raw_batch
.columns()
.iter()
.zip(slice_batch.columns())
.for_each(|(a, b)| {
println!("{:?} : {:?}", a.data(), b.data());
assert_eq!(a.data_type(), b.data_type());
assert_eq!(a.data().buffers()[0], b.data().buffers()[0]);
});
let raw_path = "raw_data.arrow";
let slice_path = "slice_data.arrow";
{
let raw_file = File::create(raw_path).unwrap();
let mut raw_writer = FileWriter::try_new(raw_file, &schema).unwrap();
raw_writer.write(&raw_batch).unwrap();
raw_writer.finish().unwrap();
}
{
let slice_file = File::create(slice_path).unwrap();
let mut slice_writer = FileWriter::try_new(slice_file, &schema).unwrap();
slice_writer.write(&slice_batch).unwrap();
slice_writer.finish().unwrap();
}
let raw_file = File::open(raw_path).unwrap();
let slice_file = File::open(slice_path).unwrap();
let mut raw_reader = FileReader::try_new(raw_file).unwrap();
let mut slice_reader = FileReader::try_new(slice_file).unwrap();
while let Some(Ok(raw_ipc_batch)) = raw_reader.next() {
println!("{:?}", raw_ipc_batch);
while let Some(Ok(slice_ipc_batch)) = slice_reader.next() {
println!("{:?}", slice_ipc_batch);
raw_ipc_batch
.columns()
.iter()
.zip(slice_ipc_batch.columns())
.for_each(|(a, b)| {
println!("{:?} : {:?}", a.data(), b.data());
assert_eq!(a.data_type(), b.data_type());
assert_eq!(a.data().buffers()[0], b.data().buffers()[0]);
});
}
}
}
Basically, im just trying to compare the buffers from two batches (one batch is a slice of the other) after reading their IPC files and comparing the value buffers. Given what we are working on i was expecting the data to be the same (i guess the assertion would still fail after reading the IPC files as they would have different pointers but i expected the value arrays to have the same values). But the value arrays were different(the full ArrayData values are above):
Activity
matthewmturner commentedon Sep 9, 2021
@alamb im interested in looking into this. i see it's been open for a while - can you confirm this is still an issue / if there is any additional context that has come up since this was initially raised? Thx!
alamb commentedon Sep 9, 2021
Hi @matthewmturner -- thanks!
Some additional context is that we encountered this issue while working on IOx -- see details https://github.com/influxdata/influxdb_iox/issues/1133
@mkmik worked around the issue in IOx via a heuristic in https://github.com/influxdata/influxdb_iox/commit/82ed5d1708458ec9438406ce1fd19aa0c7d23204
Namely there is code that deep clones the array prior to serialization if some guestimate of buffer size is hit.
Fixing the underlying problem (and only serializing the part of the data that is needed) would be great
matthewmturner commentedon Sep 9, 2021
Thank you @alamb , very helpful. I will review and let you know if any questions.
matthewmturner commentedon Sep 10, 2021
@alamb I think im restating the obvious and what has already been said, but i want to make sure i understand whats happening so i made a small sample.
Produces the following output
And the issue is that the data buffer points to the original larger array. Then, that larger array is ultimately turned into the
FlightDatawhich is a waste.Assuming that's all correct is there a preference as to where a fix should be applied? i.e. whether at
flight_data_from_arrow_batch,encoded_batch, orrecord_batch_to_bytes?Naively I was thinking at the
record_batch_to_byteslevel - but i think that might impact IPC in general. Im still figuring out the separation between IPC and Flight functionality though and if this issue is focused only on updating how array data is handled for Flight or for IPC in general. If we wanted it to be closer to the Flight level then i think copying theRecordBatchinflight_data_from_arrow_batchbefore passing it toencoded_batchwould be the way.What do you think?
Separately, ive been looking if there are any methods / helpers for recreating a
RecordBatchout of the data / offsets / len of anotherRecordBatch. Dont think ive found anything though. If thats the case would the idea be to just remake the batch from scratch with the data from the original?Hope that's all clear.
alamb commentedon Sep 12, 2021
Yes, that is the crux of the issue we found.
I am not sure to be honest as I am not familiar with the flight code. Perhaps @nevi-me or @jorgecarleitao who have more experience in how IPC / flight is supposed to work might have thoughts on how to handle serializing bytes for an Array whose backing
Bufferis much larger. Another avenue we can explore is to review how the C++ implementation handles the case and/or ask about this on [email protected].One way to reduce potential unintended side effects could be to make the optimization optional (an option on
IpcWriteOptions, perhaps) while we test it out more broadly, and then switch the default value in a later version.Yes. However, maybe that is ok (as that seems to be optimizing the serialization of Arrow Arrays). However, I am not sure what the expectations are here.
RecordBatch::sliceis what I know of for this purpose: https://docs.rs/arrow/5.3.0/arrow/record_batch/struct.RecordBatch.html#method.slice. (Kudos to @b41sh for adding that one)matthewmturner commentedon Sep 12, 2021
Thanks much for the response @alamb
I checked the
IpcWriteOptionsfor the C++ implementation (http://arrow.apache.org/docs/cpp/api/ipc.html) and I dont think they have an option for that. It also doesnt look like there is a user option for this in their Flight client implementation (http://arrow.apache.org/docs/cpp/api/flight.html#_CPPv4N5arrow6flight17FlightCallOptionsE). I can email the dev email list to see if they have any hidden logic for this not exposed to the end user.Thanks will check that out! Not sure how i missed that function.
@nevi-me @jorgecarleitao any thoughts or preferences on how to handle this?
jorgecarleitao commentedon Sep 12, 2021
I am not sure about the root cause of this, but some time ago we merged something like this in arrow2, could you check if jorgecarleitao/arrow2#194, specifically around
write_generic_binaryinsrc/io/ipc/write/serialize.rsis what we are looking for here?Note that the code is significantly different at this point, but the gist is that we need to check if the array was sliced, and if it was, only write the relevant values.
matthewmturner commentedon Sep 12, 2021
@jorgecarleitao sure will check it out
nevi-me commentedon Sep 12, 2021
matthewmturner commentedon Sep 13, 2021
@jorgecarleitao I believe this is done in
write_generic_binaryusingand then writing to buffer based on those values.
Given the different approaches here between
arrowandarrow2is there a preference for how to handle withinarrow?I was thinking we could use the
RecordBatch::slicemethod withinrecord_batch_to_bytesbefore writing the data.nevi-me commentedon Sep 13, 2021
@matthewmturner
That will apply for strings, lists and binaries, but the overall problem is the below.
We write
Buffers to IPC, and those buffers have a length and an offset (almost always 0). The problem is that when we write a buffer, we have to determine what its correct offset and length is, and the current APis in the crate can't give us that information conveniently.For example, if I have a list of i64 values:
There are 3 buffers to write.
If the list gets sliced,
list.slice(2, 1), we now have a list that looks like:In terms of the buffers, you have:
The root of the challenge above comes from the signature of
arrow::buffer::immutable::Bufferand the current state that the only method that sets the
offsetabove isOne of the foundations of
arrow2is that aBufferknows its offset and length based on its content. If a string buffer is created with "hello", "you", "world", a slice of 2 means that the buffer will know to offset 8 bytes, making the IPC process easy (@jorgecarleitao this is my understanding without having checked the code as I write this).So, to only write the correct amount of data in IPC, my approach would be to modify
arrow::ipc::writer::fn write_array_data()to account for the offset and correct length, and probably changewrite_buffer()in the same module to take the sliced bytes instead ofBuffer.matthewmturner commentedon Sep 14, 2021
@nevi-me thank you for the detailed explanation. very helpful. im working through some examples on my side to solidify my understanding and will come back if any questions else will just open a PR for a fix.
thx again!
matthewmturner commentedon Sep 14, 2021
hi @nevi-me - ive been building up a test that i could use to compare the ipc size pre and post the fix. but i havent been able to produce the expected results. Code is below:
Which produces the following output:
Basically, im just trying to compare the buffers from two batches (one batch is a slice of the other) after reading their IPC files and comparing the value buffers. Given what we are working on i was expecting the data to be the same (i guess the assertion would still fail after reading the IPC files as they would have different pointers but i expected the value arrays to have the same values). But the value arrays were different(the full
ArrayDatavalues are above):I'm going to keep playing around with this but wanted to get your thoughts on if I am approaching this the right way.
Thanks again for all your help - much appreciated.