Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions rust/arrow/src/array/array_binary.rs
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,8 @@ where
}
}

// 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 array_data = ArrayData::builder(OffsetSize::DATA_TYPE)
.len(data_len)
.add_buffer(Buffer::from_slice_ref(&offsets))
Expand Down Expand Up @@ -867,6 +869,30 @@ mod tests {
test_generic_binary_array_from_opt_vec::<i32>()
}

#[test]
fn test_binary_array_from_unbound_iter() {
// iterator that doesn't declare (upper) size bound
let value_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);

let (_, upper_size_bound) = value_iter.size_hint();
// the upper bound, defined by take above, is 100
assert_eq!(upper_size_bound, Some(100));
let binary_array: BinaryArray = value_iter.collect();
// but the actual number of items in the array should be 10
assert_eq!(binary_array.len(), 10);
}

#[test]
#[should_panic(
expected = "BinaryArray can only be created from List<u8> arrays, mismatched \
Expand Down
25 changes: 24 additions & 1 deletion rust/arrow/src/array/array_primitive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -841,7 +841,6 @@ mod tests {
#[test]
fn test_primitive_from_iter_values() {
// Test building a primitive array with from_iter_values

let arr: PrimitiveArray<Int32Type> = PrimitiveArray::from_iter_values(0..10);
assert_eq!(10, arr.len());
assert_eq!(0, arr.null_count());
Expand All @@ -850,6 +849,30 @@ mod tests {
}
}

#[test]
fn test_primitive_array_from_unbound_iter() {
// iterator that doesn't declare (upper) size bound
let value_iter = (0..)
.scan(0usize, |pos, i| {
if *pos < 10 {
*pos += 1;
Some(Some(i))
} else {
// actually returns up to 10 values
None
}
})
// limited using take()
.take(100);

let (_, upper_size_bound) = value_iter.size_hint();
// the upper bound, defined by take above, is 100
assert_eq!(upper_size_bound, Some(100));
let primitive_array: PrimitiveArray<Int32Type> = value_iter.collect();
// but the actual number of items in the array should be 10
assert_eq!(primitive_array.len(), 10);
}

#[test]
#[should_panic(expected = "PrimitiveArray data should contain a single buffer only \
(values buffer)")]
Expand Down
44 changes: 35 additions & 9 deletions rust/arrow/src/array/array_string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -205,28 +205,30 @@ where
let (_, data_len) = iter.size_hint();
let data_len = data_len.expect("Iterator must be sized"); // panic if no upper bound.
Comment thread
jorgecarleitao marked this conversation as resolved.
Resolved

let mut offsets =
MutableBuffer::new((data_len + 1) * std::mem::size_of::<OffsetSize>());
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.

let null_slice = null_buf.as_slice_mut();
let mut length_so_far = OffsetSize::zero();
offsets.push(length_so_far);

for (i, s) in iter.enumerate() {
if let Some(s) = s {
let s = s.as_ref();
let value_bytes = if let Some(ref s) = s {
// set null bit
bit_util::set_bit(null_slice, i);

length_so_far += OffsetSize::from_usize(s.len()).unwrap();
values.extend_from_slice(s.as_bytes());
let s_bytes = s.as_ref().as_bytes();
length_so_far += OffsetSize::from_usize(s_bytes.len()).unwrap();
s_bytes
} else {
values.extend_from_slice(b"");
}
b""
};
values.extend_from_slice(value_bytes);
offsets.push(length_so_far);
}

// calculate actual data_len, which may be different from the iterator's upper bound
let data_len = (offsets.len() / offset_size) - 1;
let array_data = ArrayData::builder(OffsetSize::DATA_TYPE)
.len(data_len)
.add_buffer(offsets.into())
Expand Down Expand Up @@ -490,4 +492,28 @@ mod tests {
assert_eq!(array1.value(0), "hello");
assert_eq!(array1.value(1), "hello2");
}

#[test]
fn test_string_array_from_unbound_iter() {
// 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);

let (_, upper_size_bound) = string_iter.size_hint();
// the upper bound, defined by take above, is 100
assert_eq!(upper_size_bound, Some(100));
let string_array: StringArray = string_iter.collect();
// but the actual number of items in the array should be 10
assert_eq!(string_array.len(), 10);
}
}