Repository navigation
Conversation
comphead
left a comment
There was a problem hiding this comment.
An error is the right answer here since Spark's StringType maps to Utf8 and LargeUtf8 would change the type contract. The base64 and binary cast guards use an O(1) bound and count exactly only above the limit, and the errors are DataFusionError::Execution (surfacing as CometNativeException, not SparkError::Internal). The padding rewrite is the weak part. It pays a per-row pass and drops a fast path in a hot kernel, with no padding.rs numbers in the description. I did not run any benchmark. No textual conflict with #7760.
| 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); |
There was a problem hiding this 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.
There was a problem hiding this comment.
Updated padding to use a conservative byte bound first. Scalar lengths use rows * length, and column lengths scan only the length array. The exact preflight calls padder.parts only when the bound might exceed the offset limit, so ordinary batches avoid the extra character-count pass.
I also expanded benches/padding.rs to cover UTF-8, short and long strings, different null densities, scalar and column lengths, and random lengths. Against main 1c0eb0b8, short UTF-8 truncation with 10% nulls takes 81.56 µs per batch versus 81.64 µs on main. The six previously flagged column-length cases range from −0.4% to +1.3% in crossover measurements.
One remaining regression is long UTF-8 input with 50% nulls and scalar-length truncation: about +3.9%, or +3.9 µs per 8,192-row batch. I have kept that performance item open. The PR description includes the full 71-case matrix and 16 crossover checks.
| 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]) | ||
| } | ||
|
|
There was a problem hiding this 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.
There was a problem hiding this comment.
Thanks! I restore the one-byte-per-character fast path in byte_len, so the default space pattern returns Some(chars) without division or modulo.
There was a problem hiding this comment.
I measured the extra traversal raised in the existing review. In a standalone base/head kernel benchmark (locked Arrow 59.3.2 and DataFusion 55.2.0, kernel compiled with opt-level=3, 8,192 rows, every tenth row null, 13 alternating rounds, median), default-space ASCII lpad to 20 went from 123 to 223 µs per batch, ASCII truncation to 5 from 90 to 196 µs, and UTF-8 truncation to 5 from 227 to 420 µs. A cheap conservative bound for ordinary batches, with the exact preflight for batches that could cross the offset limit, would keep the safety check. I also found a separate allocation issue below.
One pre-existing case to keep open under #7500 is expanding an all-scalar result at projection time. I tried scalar lpad('x', 262144) and then into_array_of_size(8192), the operation DataFusion's projector uses. The scalar succeeds and Arrow panics with offset overflow when it expands to 2,147,483,648 bytes. #7245 describes how a conditional can yield a scalar at runtime. The right place for this guard is the scalar-to-array boundary, since a scalar-only consumer can use this value safely.
| // 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); |
There was a problem hiding this 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?
There was a problem hiding this comment.
I add reserve_exact(tail.len()) before appending the tail, plus a regression test covering the ab case to verify scratch capacity does not double.
|
Thanks @sunchao ! I switch padding to a conservative bound, with exact preflight only for potentially oversized batches. Benchmark results are in the PR description; long UTF-8 truncation with 50% nulls still shows a 3.9% regression and remains open. |
Which issue does this PR close?
Part of #7500. The later expansion of an all-scalar result is tracked separately in #7247 and is not fixed by this PR.
Rationale for this change
Expanding string kernels can produce batches beyond Arrow's offset limit or reserve an unbounded output before writing any values. Return a recoverable error suggesting a smaller
spark.comet.batchSizebefore allocating the kernel output.What changes are included in this PR?
base64,randstr,lpad,rpad, read-side padding, and binary-to-string casts across all supported output styles.repeat. Check output before initializing or advancing therandstrRNG.How are these changes tested?
randstrrequests preserve the RNG sequence.-D warnings, Rust formatting, and Markdown formatting passed.cargo test --manifest-path native/Cargo.toml -p datafusion-comet-common -p datafusion-comet-spark-expr --lib cargo clippy --manifest-path native/Cargo.toml --workspace --all-targets -- -D warnings cargo fmt --manifest-path native/Cargo.toml --all --checkPadding performance
Apple arm64, rustc 1.97.1, locked Arrow 59.3.2 / DataFusion 55.2.0, Cargo release profile (thin LTO, one codegen unit), 8,192 rows. The baseline is unmodified main snapshot
1c0eb0b8bedbf19341dcbb5b115c0ec2235de576, built from an isolated archive with the identical expanded benchmark and lockfile. The baseline binary hash matches the verified build; the discarded stale-cache baseline was not used.The final 71-case matrix covers ASCII / UTF-8, short / long strings, 0% / 10% / 50% nulls, scalar / column lengths, padding / truncation, and random mixed lengths, plus the existing lpad/rpad benchmarks. For each case, main ran immediately before the revised kernel: 20 samples, 0.2 s warmup, 0.5 s measurement. We independently checked 16 cases with main/revised/revised/main crossover runs, 50 samples, 0.5 s warmup and 1.5 s measurement per process. This includes all six previously reported column-length regressions and every final-matrix signal with median change above +1% and a 95% mean-change interval wholly above +1%. No project builds or tests ran concurrently with these final measurements.
Times below are median microseconds per batch. Percentage change is revised/main - 1; negative is faster. Criterion intervals describe mean changes, so they need not contain the ratio of the two medians. These are kernel measurements on one host, not end-to-end SQL timings or a reproduction of sunchao's benchmark environment.
The ordinary path uses a conservative byte bound and retains direct scalar-length and column-length write loops. Only a potentially oversized bound triggers exact character counting. The length sum uses saturating arithmetic as a bound, avoiding an Option carried per element while retaining exact validation when needed. The long UTF-8 padding shapes also avoid growing an output buffer initially sized in characters rather than bytes.
Representative results (original PR timings are earlier 20-sample measurements, included only as context):
spark_lpad: default paddingspark_lpad: with truncationpadding_review/utf8/short/sparse_nulls/truncate_scalarpadding_review/utf8/long/sparse_nulls/pad_columnThe large extra-traversal regression is removed, but the performance feedback is not fully resolved. The crossover checks still show a measurable cost for long UTF-8 input with 50% nulls, a scalar target length of 5, and truncation: the geometric mean of the two median ratios is +3.87%, about +3.94 µs per 8,192-row batch (averages of the paired medians: 101.08 → 105.02 µs). The main→revised and revised→main median changes are +7.16% and +0.67%; the corresponding 95% mean-change intervals, both expressed as revised/main, are [+1.7%, +7.7%] and [+1.6%, +8.9%]. This is a supported ordinary input shape. We have no production-frequency evidence that would justify calling it rare, and its cause has not yet been isolated. It remains an open performance item before treating this review as resolved.
For the six previously reported column-length cases, the crossover geometric changes are approximately −0.4% to +1.3%; the short UTF-8/no-null padding case is +1.29%, about +2.36 µs per batch, with both process-pair mean-change intervals including zero. Some other positive point estimates are sensitive to execution order: for example short ASCII/sparse-null column truncation is −2.43% in one order and +7.62% in the other. Those observations are retained below. The results do not support a blanket “regression-free” claim.
Next step for the remaining long-UTF-8/dense-null truncation cost: profile the final and main binaries on that exact case, isolate the allocation/code-generation difference, and remeasure the chosen fix. No review thread is being treated as resolved by the benchmark additions alone.
Full 71-case matrix against main
padding_review/ascii/long/dense_nulls/mixed_random_columnpadding_review/ascii/long/dense_nulls/pad_columnpadding_review/ascii/long/dense_nulls/pad_scalarpadding_review/ascii/long/dense_nulls/truncate_columnpadding_review/ascii/long/dense_nulls/truncate_scalarpadding_review/ascii/long/no_nulls/mixed_random_columnpadding_review/ascii/long/no_nulls/pad_columnpadding_review/ascii/long/no_nulls/pad_scalarpadding_review/ascii/long/no_nulls/truncate_columnpadding_review/ascii/long/no_nulls/truncate_scalarpadding_review/ascii/long/sparse_nulls/mixed_random_columnpadding_review/ascii/long/sparse_nulls/pad_columnpadding_review/ascii/long/sparse_nulls/pad_scalarpadding_review/ascii/long/sparse_nulls/truncate_columnpadding_review/ascii/long/sparse_nulls/truncate_scalarpadding_review/ascii/short/dense_nulls/mixed_random_columnpadding_review/ascii/short/dense_nulls/pad_columnpadding_review/ascii/short/dense_nulls/pad_scalarpadding_review/ascii/short/dense_nulls/truncate_columnpadding_review/ascii/short/dense_nulls/truncate_scalarpadding_review/ascii/short/no_nulls/mixed_random_columnpadding_review/ascii/short/no_nulls/pad_columnpadding_review/ascii/short/no_nulls/pad_scalarpadding_review/ascii/short/no_nulls/truncate_columnpadding_review/ascii/short/no_nulls/truncate_scalarpadding_review/ascii/short/sparse_nulls/mixed_random_columnpadding_review/ascii/short/sparse_nulls/pad_columnpadding_review/ascii/short/sparse_nulls/pad_scalarpadding_review/ascii/short/sparse_nulls/truncate_columnpadding_review/ascii/short/sparse_nulls/truncate_scalarpadding_review/utf8/long/dense_nulls/mixed_random_columnpadding_review/utf8/long/dense_nulls/pad_columnpadding_review/utf8/long/dense_nulls/pad_scalarpadding_review/utf8/long/dense_nulls/truncate_columnpadding_review/utf8/long/dense_nulls/truncate_scalarpadding_review/utf8/long/no_nulls/mixed_random_columnpadding_review/utf8/long/no_nulls/pad_columnpadding_review/utf8/long/no_nulls/pad_scalarpadding_review/utf8/long/no_nulls/truncate_columnpadding_review/utf8/long/no_nulls/truncate_scalarpadding_review/utf8/long/sparse_nulls/mixed_random_columnpadding_review/utf8/long/sparse_nulls/pad_columnpadding_review/utf8/long/sparse_nulls/pad_scalarpadding_review/utf8/long/sparse_nulls/truncate_columnpadding_review/utf8/long/sparse_nulls/truncate_scalarpadding_review/utf8/short/dense_nulls/mixed_random_columnpadding_review/utf8/short/dense_nulls/pad_columnpadding_review/utf8/short/dense_nulls/pad_scalarpadding_review/utf8/short/dense_nulls/truncate_columnpadding_review/utf8/short/dense_nulls/truncate_scalarpadding_review/utf8/short/no_nulls/mixed_random_columnpadding_review/utf8/short/no_nulls/pad_columnpadding_review/utf8/short/no_nulls/pad_scalarpadding_review/utf8/short/no_nulls/truncate_columnpadding_review/utf8/short/no_nulls/truncate_scalarpadding_review/utf8/short/sparse_nulls/mixed_random_columnpadding_review/utf8/short/sparse_nulls/pad_columnpadding_review/utf8/short/sparse_nulls/pad_scalarpadding_review/utf8/short/sparse_nulls/truncate_columnpadding_review/utf8/short/sparse_nulls/truncate_scalarspark_lpad: custom paddingspark_lpad: default paddingspark_lpad: length from columnspark_lpad: multi-char paddingspark_lpad: with truncationspark_rpad: custom paddingspark_rpad: default paddingspark_rpad: length from columnspark_rpad: length from column, multi-char paddingspark_rpad: multi-char paddingspark_rpad: with truncation16 crossover checks: main/revised/revised/main
The second pair runs the revised binary first. Its Criterion interval is inverted to express both pairs as revised/main. The geometric mean of the two median ratios is descriptive, without a new confidence interval.
padding_review/ascii/short/dense_nulls/pad_columnpadding_review/ascii/short/no_nulls/mixed_random_columnpadding_review/ascii/short/no_nulls/pad_columnpadding_review/ascii/short/no_nulls/truncate_columnpadding_review/ascii/short/no_nulls/truncate_scalarpadding_review/ascii/short/sparse_nulls/truncate_columnpadding_review/utf8/long/dense_nulls/truncate_scalarpadding_review/utf8/long/no_nulls/truncate_columnpadding_review/utf8/long/no_nulls/truncate_scalarpadding_review/utf8/short/dense_nulls/pad_columnpadding_review/utf8/short/dense_nulls/truncate_columnpadding_review/utf8/short/no_nulls/pad_columnpadding_review/utf8/short/no_nulls/pad_scalarpadding_review/utf8/short/no_nulls/truncate_columnpadding_review/utf8/short/sparse_nulls/pad_columnspark_rpad: with truncationScalar expansion follow-up
#7247 tracks expansion of a valid scalar into an array by its consumer. A scalar
lpad('x', 262144)fits on its own, butinto_array_of_size(8192)needs 2,147,483,648 bytes and still panics at Arrow's i32 offset boundary. This is the pre-existing case raised in sunchao's review, not covered by the kernel's allocation guard.A standalone probe with the locked DataFusion 55.2.0 and Arrow 59.3.2 confirmed that a 262,144-byte Utf8 scalar expands to one row successfully and panics on expansion to 8,192 rows. The failing probe hits Arrow's offset check before allocating the repeated value bytes.
The follow-up must validate expansion at the scalar-to-array boundary without rejecting scalar-only consumers, and test runtime-scalar conditionals (#7245), null/empty values, and the offset boundary. The batch-bounding work in #7316 and #7762 is separate; this PR does not claim that every operator expansion is covered.
Tracking details and acceptance criteria: #7247 (comment)