comphead commented on code in PR #7746:
URL: https://github.com/apache/datafusion-comet/pull/7746#discussion_r4743966197
##########
native/spark-expr/src/static_invoke/char_varchar_utils/read_side_padding.rs:
##########
@@ -377,42 +402,32 @@ struct PadPattern<'a> {
}
impl<'a> PadPattern<'a> {
- /// Builds a pattern that can supply up to `max_chars` padding characters.
- fn new(pattern: &'a str, max_chars: usize) -> Self {
+ fn new(pattern: &'a str) -> Self {
let char_offsets: Vec<usize> = pattern
.char_indices()
.map(|(i, _)| i)
.chain(std::iter::once(pattern.len()))
.collect();
- let pattern_chars = char_offsets.len() - 1;
- let buffer = if pattern_chars == 0 {
- String::new()
- } else {
- pattern.repeat(max_chars.div_ceil(pattern_chars))
- };
Self {
pattern,
char_offsets,
- buffer,
+ buffer: String::new(),
}
}
- /// Returns a slice holding exactly `chars` characters of the repeating
pattern,
- /// or an empty slice if the pattern itself is empty. `chars` must not
exceed the
- /// `max_chars` the pattern was built with.
- #[inline]
- fn slice(&self, chars: usize) -> &str {
+ fn byte_len(&self, chars: usize) -> Option<usize> {
let pattern_chars = self.char_offsets.len() - 1;
if pattern_chars == 0 {
- return "";
+ return Some(0);
}
- let bytes = if self.pattern.len() == pattern_chars {
- // One byte per character (the default single space), so no offset
lookup.
- chars
- } else {
- (chars / pattern_chars) * self.pattern.len() +
self.char_offsets[chars % pattern_chars]
- };
- &self.buffer[..bytes]
+ (chars / pattern_chars)
+ .checked_mul(self.pattern.len())?
+ .checked_add(self.char_offsets[chars % pattern_chars])
+ }
+
Review Comment:
The old `slice` returned `chars` directly when the pattern is one byte per
character, which is the default single space. `byte_len` drops that case, so
every row now does a division, a modulo, a `checked_mul` and a `checked_add`,
and it runs twice per row (here and in `append` through `slice`). Restoring `if
self.pattern.len() == pattern_chars { return Some(chars) }` at the top keeps
the default case free of integer division.
##########
native/spark-expr/src/static_invoke/char_varchar_utils/read_side_padding.rs:
##########
@@ -283,85 +280,113 @@ fn spark_read_side_padding_scalar<T: OffsetSizeTrait>(
}
}
-/// Pads each of `strings`. `ascii` says every string is ASCII. When
`pad_type` is an array,
-/// `min_capacity` is a floor for the output's data buffer, covering rows that
pass through
-/// untruncated. When `pad_type` is a scalar, the buffer is sized from the
length alone and
-/// `min_capacity` is ignored.
-fn pad_strings<'a, T: OffsetSizeTrait, I: ExactSizeIterator<Item = Option<&'a
str>>>(
+fn pad_strings<'a, T: OffsetSizeTrait, I: ExactSizeIterator<Item = Option<&'a
str>> + Clone>(
strings: I,
ascii: bool,
- min_capacity: usize,
truncate: bool,
pad_type: ColumnarValue,
pad_string: &str,
is_left_pad: bool,
) -> Result<ArrayRef, DataFusionError> {
+ let limit = if T::IS_LARGE {
+ i64::MAX as usize
+ } else {
+ i32::MAX as usize
+ };
+ pad_strings_with_limit::<T, _>(
+ strings,
+ ascii,
+ truncate,
+ pad_type,
+ pad_string,
+ is_left_pad,
+ limit,
+ )
+}
+
+fn pad_strings_with_limit<
+ 'a,
+ T: OffsetSizeTrait,
+ I: ExactSizeIterator<Item = Option<&'a str>> + Clone,
+>(
+ strings: I,
+ ascii: bool,
+ truncate: bool,
+ pad_type: ColumnarValue,
+ pad_string: &str,
+ is_left_pad: bool,
+ limit: usize,
+) -> Result<ArrayRef, DataFusionError> {
+ let padder = Padder {
+ pad: PadPattern::new(pad_string),
+ ascii,
+ truncate,
+ is_left_pad,
+ };
match pad_type {
ColumnarValue::Array(array_int) => {
- let int_pad_array = array_int.as_primitive::<Int32Type>();
-
- // Every row is padded to its target length, so the sum of the
target
- // lengths sizes the output (exactly, for ASCII input), except
when a
- // row is longer than its target and passes through untruncated.
Null
- // lengths produce null rows and are skipped: the values under null
- // slots are unspecified and must not size the output.
- let mut data_capacity = 0usize;
- let mut max_length = 0usize;
- for length in int_pad_array.iter().flatten() {
- let length = length.max(0) as usize;
- data_capacity = data_capacity.saturating_add(length);
- max_length = max_length.max(length);
- }
- let mut builder = GenericStringBuilder::<T>::with_capacity(
- strings.len(),
- data_capacity.max(min_capacity),
- );
- let padder = Padder {
- pad: PadPattern::new(pad_string, max_length),
- ascii,
- truncate,
- is_left_pad,
- };
-
- for (string, length) in strings.zip(int_pad_array) {
- match (string, length) {
- (Some(string), Some(length)) => {
- if length >= 0 {
- padder.append(&mut builder, string, length as
usize);
- } else {
- builder.append_value("");
- }
- }
- // Spark's StringRPad/StringLPad are null-intolerant: a
null
- // string or a null length yields a null row.
- _ => builder.append_null(),
- }
- }
- Ok(Arc::new(builder.finish()))
+ let lengths = array_int.as_primitive::<Int32Type>();
+ let rows = strings
+ .zip(lengths)
+ .map(|(string, length)| match (string, length) {
+ (Some(_), Some(length)) if length < 0 => Some(("", 0)),
+ (Some(string), Some(length)) => Some((string, length as
usize)),
+ _ => None,
+ });
+ pad_rows::<T, _>(rows, padder, limit)
}
- ColumnarValue::Scalar(const_pad_length) => {
- let length = 0.max(i32::try_from(const_pad_length)?) as usize;
-
- let mut builder = GenericStringBuilder::<T>::with_capacity(
- strings.len(),
- strings.len().saturating_mul(length),
- );
- let padder = Padder {
- pad: PadPattern::new(pad_string, length),
- ascii,
- truncate,
- is_left_pad,
- };
+ ColumnarValue::Scalar(length) => {
+ let length = i32::try_from(length)?.max(0) as usize;
+ pad_rows::<T, _>(strings.map(|s| s.map(|s| (s, length))), padder,
limit)
+ }
+ }
+}
- for string in strings {
- match string {
- Some(string) => padder.append(&mut builder, string,
length),
- _ => builder.append_null(),
- }
- }
- Ok(Arc::new(builder.finish()))
+fn pad_rows<
+ 'a,
+ T: OffsetSizeTrait,
+ I: ExactSizeIterator<Item = Option<(&'a str, usize)>> + Clone,
+>(
+ rows: I,
+ mut padder: Padder<'_>,
+ limit: usize,
+) -> Result<ArrayRef, DataFusionError> {
+ let function = if !padder.truncate {
+ "read_side_padding"
+ } else if padder.is_left_pad {
+ "lpad"
+ } else {
+ "rpad"
+ };
+ let mut capacity = 0usize;
+ let mut max_padding = 0;
+ for (string, length) in rows.clone().flatten() {
+ let (string, padding) = padder.parts(string, length);
+ let bytes = padder
+ .pad
+ .byte_len(padding)
+ .and_then(|n| n.checked_add(string.len()));
+ let bytes = checked_output_size(function, bytes, limit)?;
+ capacity = checked_output_size(function, capacity.checked_add(bytes),
limit)?;
+ max_padding = max_padding.max(padding);
Review Comment:
This first pass calls `padder.parts` for every row and `append` calls it
again. For non-ASCII input that counts `chars()` twice per row. The old code
summed only the length array, and for a scalar length it used `rows * length`
with no pass. `base64` and the binary cast in this same PR use an O(1) upper
bound and count exactly only when the bound exceeds the limit. The same shape
would fit here, for example total string bytes plus the sum of target lengths
times the pattern's bytes per character, with the exact loop only above the
limit. `benches/padding.rs` is ASCII only, so a before and after run with a
non-ASCII column would show whether this matters. I did not run it.
##########
native/spark-expr/src/conversion_funcs/cast.rs:
##########
@@ -966,16 +1041,18 @@ fn cast_binary_to_string<O: OffsetSizeTrait>(
);
let mut valid_prefix = "";
let mut checked = false;
- if utf8_style && 2 * live_bytes >= end - start {
+ if utf8_style && live_bytes >= (end - start).div_ceil(2) {
checked = true;
let data = input.value_data();
match std::str::from_utf8(&data[start..end]) {
Ok(valid) => {
// An offset splits a code point only if it points at a
continuation byte.
- if offsets.iter().all(|offset| {
- let offset = offset.as_usize();
- offset == end || !matches!(data[offset], 0x80..=0xBF)
- }) {
+ if end - start <= limit
Review Comment:
`end - start <= limit` cannot be false in production. For `Binary` the
offsets are `i32`, so the span is at most `i32::MAX`, and for `LargeBinary` the
limit is `i64::MAX`. Only the tests with an injected small limit reach it.
Either drop it from the reuse condition or say in a comment that it exists for
the injected-limit tests.
##########
native/spark-expr/src/nondetermenistic_funcs/randstr.rs:
##########
@@ -61,6 +62,30 @@ impl RandStrExpr {
state_holder: Arc::new(Mutex::new(None)),
}
}
+
+ fn evaluate_with_limit(&self, batch: &RecordBatch, limit: usize) ->
Result<ColumnarValue> {
+ let num_rows = batch.num_rows();
+ if num_rows == 0 {
+ return Ok(ColumnarValue::Array(new_empty_array(&DataType::Utf8)));
+ }
+ checked_output_size("randstr value", Some(self.length), limit)?;
Review Comment:
`num_rows` is at least 1 here, so `num_rows * self.length >= self.length`
and the batch check on the next line already rejects every case this per-value
check rejects. Only the message text differs. Dropping this call removes a
branch and a second wording for one condition.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]