Skip to content

ARROW-11799: [Rust] fix len of string and binary arrays created from unbound iterator - #9588

Closed
yordan-pavlov wants to merge 2 commits into
apache:masterfrom
yordan-pavlov:fix_array_len_from_unbound_iter
Closed

yordan-pavlov wants to merge 2 commits into
apache:masterfrom
yordan-pavlov:fix_array_len_from_unbound_iter

Conversation

@yordan-pavlov

Copy link
Copy Markdown
Contributor

While looking for a way to make loading array data from parquet files faster, I stumbled on an edge case where string and binary arrays are created with an incorrect length from an iterator with no upper bound.

Here is an example for such an iterator:

 // iterator that doesn't declare (upper) size bound
let string_iter = (0..).scan(0usize, |pos, i| { 
    if *pos < 10 {
        *pos += 1;
        Some(Some(format!("value {}", i)))
    }
    else {
         // actually returns up to 10 values
         None
     }
})
// limited using take()
.take(100);

For even more details please see the new tests I have added in this PR.
Fortunately this is easy to fix by using the length of the child offset array.

@jorgecarleitao

@github-actions

Copy link
Copy Markdown

@nevi-me

nevi-me commented Feb 27, 2021

Copy link
Copy Markdown
Contributor

While looking for a way to make loading array data from parquet files faster

I think the biggest win with strings is if we could avoid ByteArray when using the Arrow reader/writer.

@yordan-pavlov

yordan-pavlov commented Feb 27, 2021 •

Copy link
Copy Markdown
Contributor Author

@nevi-me this probably deserves its own discussion, but you are pretty close with your suggestion to avoid ByteArray;

I have been doing quite a lot of profiling and benchmarking in the past few weeks on loading string arrays from parquet files, and yes, going through an intermediate Vec<ByteArray> adds a lot of overhead due to extra allocation and very interestingly, deallocation (I imagine because of the creation of many ByteArray objects pointing to the same Arc).

I am happy to discuss this in more detail, but in short my benchmarks show that skipping the ByteArrays approximately doubles performance, then replacing Vec with Iterator results in some more improvement and finally removing the intermediate conversion into &str (and just copying the bytes instead) results in another doubling of performance for a total achievable performance improvement of about 5 times. These are still very basic and isolated benchmarks, next step is to find a way to apply these learnings to the actual parquet reader code.

@alamb

alamb commented Feb 28, 2021

Copy link
Copy Markdown
Contributor

I have been doing quite a lot of profiling and benchmarking in the past few weeks on loading string arrays from parquet files, and yes, going through an intermediate Vec

@yordan-pavlov we have observed very similar things while working with the Rust parquet reader in IOx -- I would be interesting in helping to support your efforts to improve the performance (either directly or with reviews, etc).

Thank you for leading the charge

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

Thank you very much @yordan-pavlov -- this seems uniformly better than the current master code. I do worry about issues with MutableBuffer.

I think @jorgecarleitao will be away for a few more weeks. I suggest we merge this PR in and handle any additional potential problems with MutableBuffer as a follow on.

}

// calculate actual data_len, which may be different from the iterator's upper bound
let data_len = offsets.len() - 1;

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.

I wonder if there is a problem of writing off the end of null_buf which was allocated to be only size of data_len?

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.

writing beyond the allocated capacity would only happen if the iterator input returns more items than the declared upper bound - this would be against the Iterator spec and I think that would be unlikely ;
this PR addresses the opposite case where an iterator returns less items than its declared upper bound (which is still within the Iterator spec);

@jorgecarleitao jorgecarleitao Feb 28, 2021 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that @alamb is right (my comment is actually wrong). @yordan-pavlov , the Iterator spec recommends, does not require, that the iterator reports a correct length. Consumer that lead to undefined behavior from an incorrect size_hint are the causers of said undefined behavior.

The only case where consumers can trust the iterators' length is when the interator implement unsafe trait TrustedLen. Unfortunately, TrustedLen is still in unstable. For that reason, we have been exposing unsafe Buffer::from_trusted_len_iter and the like for those cases.

The issue here is that to correctly declare a FromIterator in this case, we must use BooleanBufferBuilder for the null bitmap, which is significantly slower than a MutableBuffer. This is why I added that panic! there, even though it is unsound. This PR is just surfacing this problem where the current implementation is unsound (because the iterator can be larger or smaller than upper_bound).

Since we have been seeing people prefer the FromIter over the Builder APIs, my suggestion is that we use BooleanBufferBuilder, like we are doing for PrimitiveArray, and offer (in a future PR), a from_trusted_len_iter for string arrays.

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.

you are right @jorgecarleitao, it is up to the iterator reader to ensure incorrectly declared bounds do not result in incorrect behavior and, sadly the current implementation could write out of allocated memory in the case of an iterator that produces more items than the declared upper bound;
but although I agree this should be fixed, I think it falls outside of the scope of this PR.

@alamb alamb Mar 4, 2021 •

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.

After some more study I agree (that further improvements could be made, but this PR makes the situation better so it is good as it is)

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.

https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.size_hint says

It is not enforced that an iterator implementation yields the declared number of elements. A buggy iterator may yield less than the lower bound or more than the upper bound of elements.

size_hint() is primarily intended to be used for optimizations such as reserving space for the elements of the iterator, but must not be trusted to e.g., omit bounds checks in unsafe code. An incorrect implementation of size_hint() should not lead to memory safety violations.

I figured i would paste that into this PR as I had looked it up to satisfy my own curiosity

let offset_size = std::mem::size_of::<OffsetSize>();
let mut offsets = MutableBuffer::new((data_len + 1) * offset_size);
let mut values = MutableBuffer::new(0);
let mut null_buf = MutableBuffer::new_null(data_len);

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.

I have the same question about the null buffer's length here as well.

@jorgecarleitao jorgecarleitao left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left a comment that also fixes the case where the upper bound is unknown (because we can :P)

Comment thread rust/arrow/src/array/array_string.rs Resolved
@alamb

alamb commented Mar 4, 2021

Copy link
Copy Markdown
Contributor

I reviewed this PR again, and also locally tested it against the latest apache master and everything still passes.

I filed https://issues.apache.org/jira/browse/ARROW-11862 to track the lurking bug from iterators that report max_size too small

Thanks again @yordan-pavlov for this fix

@alamb alamb closed this in 4f6adc7 Mar 4, 2021
@Dandandan

Dandandan commented Mar 4, 2021 •

Copy link
Copy Markdown
Contributor

@yordan-pavlov
Would be very interested in a faster parquet reader.
Was doing some benchmarking with some queries in DataFusion with Parquet, looks like there is a lot to win in Parquet when looking at profiling results. For example, query 5 showing about 50% of instruction fetches are for reading parquet:

query5

And reading all the parquet files of the benchmark to memory (and running some queries) (left inclusive % instruction fetch, right self %).:

unknown

@yordan-pavlov

yordan-pavlov commented Mar 4, 2021 •

Copy link
Copy Markdown
Contributor Author

@Dandandan I would be happy to collaborate on this;
I have been using MS Visual Studio for profiling DataFusion and Arrow, and most of the time it works fairly well and gives useful insight.
From what I have observed, after my change to push filers down to parquet (by filtering out entire row groups), now about half the time is spent in ComplexObjectArrayReader::next_batch; then inside this method

  • about 16% of total runtime is spent on data_buffer.resize_with(batch_size, T::T::default); where in the case of StringArray, data_bufer is Vec<ByteArray>
  • about 8% of total time is spent on data_buffer.truncate(num_read);
  • about 10% of total time is spent in data_buffer.into_iter().zip(self.def_levels_buffer.as_ref().unwrap().iter()).map(...).collect()
  • another 10% of total time is spent in let mut array = self.converter.convert(data)?; - this is where the Utf8ArrayConverter is used
  • more time is also spent at the very end of the next_batch function, I imagine to deallocate the large number of ByteArray objects created

I have managed to achieve about 10-15% improvement by replacing data_buffer.truncate(num_read) with using an iterator instead, but there is a lot more work to do. As I commented above, there is a number of improvements that could be done:

  • not converting into intermediate ByteArray objects on the way into a StringArray should result in a significant improvement
  • also using iterators to fetch data loaded from parquet, instead of writing values in pre-allocated arrays should avoid a lot of unnecessary allocation
  • for optimal performance, ideally not do any intermediate conversion at all, and just copy bytes slices from an iterator (over parquet data pages) into an arrow array

All of these changes, I think, will propagate all the way to the low-level decoders and will take time, but when done should put us in a good position to transition to async using Streams (my understanding is that a Stream is effectively an async Iterator).
I am still figuring out how to make this work exactly and how to split the work into smaller pieces which could be done over time. I hope to be able to make more progress on this in the next few days.

@jorgecarleitao

Copy link
Copy Markdown
Member

fwiw, I strongly agree with you, @yordan-pavlov on all those marks. I recently went through the arrow/ module of the parquet crate and concluded exactly the same (including the "takes time" part).

@Dandandan

Copy link
Copy Markdown
Contributor

@yordan-pavlov thanks a lot for detailed descriptions. I think that's a great overview of the current situation.

I can help with reviewing your next PR (maybe the 10-15% improvement might be useful to have as PR already?).

I will also have a look at using a sampling profiler (perf?), so far I have been using callgrind / cachegrind for collecting profiles which doesn't always give perfect results (although run time and instructions are quite correlated) and is quite slow.
Using MS Visual Studio sound like a great idea too. I think maybe it's worth to document steps to profile Arrow/Parquet/DataFusion on different profiles, these are my current steps with callgrind:

https://docs.google.com/document/d/1OqM1SSFmopcbz4JtOXJ8pXE7c1b4A2zDm4w207KBjq0/edit?usp=sharing

I think from different queries the source of the "hot path" might be very different. For example, I didn't so far see that much in the ComplexObjectArrayReader in my test so it would be also good to profile / optimize a variety of parquet files / queries.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants