sunchao commented on code in PR #7746:
URL: https://github.com/apache/datafusion-comet/pull/7746#discussion_r4746933377


##########
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);
+    }
+    // Materialize only padding that a non-null row actually needs, after 
checking the total.
+    let pattern_chars = padder.pad.char_offsets.len() - 1;
+    if let Some(repetitions) = max_padding.checked_div(pattern_chars) {
+        padder.pad.buffer = padder.pad.pattern.repeat(repetitions);

Review Comment:
   `repeat(repetitions)` fills the buffer to capacity. Pushing even a single 
tail byte can then double that allocation, while the builder also reserves the 
full result. In a one-row `lpad('', 1048577, 'ab')` probe the largest 
allocation request went from 1,048,578 to 2,097,152 bytes for the same 
1,048,577-byte output. At the i32 offset limit that is nearly 4 GiB of scratch 
capacity in addition to the result. Could we reserve the exact tail size before 
pushing it, or allocate the checked full padding length once and fill it?



-- 
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]

Reply via email to