fix: skip arithmetic and concat operands that Spark skips under ANSI mode #7456
All Vouch review confidence checks passed
Residual risk 0.28 = Change Risk (0.52) × (1 − Review Confidence (0.47)).
Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.52 · 650 lines diff across 8 files
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.02 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size
diff_size
0.388
Shallow Review Depth
shallow_review_depth
0.344
Real PR Conversation Timeline
1 comments
"Review active on #7456"
general
weight: 0.35
sunchao
Which issue does this PR close?
<!--
We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example
Closes #123indicates that this PR will close issue #123.-->
Part of https://github.com/apache/datafusion-comet/issues/7246. It fixes the arithmetic and
concatrows of that issue.OR,ANDandINwere fixed by https://github.com/apache/datafusion-comet/pull/7326, and the later sort keys of a top-K are left for a separate PR, so the issue stays open.Rationale for this change
<!--
Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed.
Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes.
-->
With ANSI mode on, native Comet evaluates an operand over the whole batch even on rows where Spark never evaluates it, so a query that Spark answers fails in Comet with
CAST_INVALID_INPUT:+,-andevaluate the right operand only where the left one is not NULL (BinaryExpression.nullSafeCodeGen)./,DIVand%evaluate the divisor first, and the dividend only where the divisor is not NULL (DivModLike.doGenCode, the same in Spark 3.4 and 4.1).concatevaluates each argument only while no earlier one is NULL (Concat.doGenCode, Spark's default generated code).For example
SELECT n + CAST(txt AS INT) FROM treturns NULL in Spark wherevernis NULL, whatevertxtholds, but fails in Comet when such a row has a malformedtxt.What changes are included in this PR?
<!--
There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR.
-->
The fix reuses
NullShortCircuit, which already evaluates later function arguments only where no earlier one is NULL (https://github.com/apache/datafusion-comet/pull/6716).NullShortCircuit::wrap_in_orderevaluates the arguments in a given order, so that the divisor of a division comes first.wrapkeeps the order of the children.MathExprgainsnull_short_circuit. The serde sets it when the operand that Spark may skip can be skipped (canSkipEvaluation), which is the right operand of+,-andand the left one of/,DIVand%. The planner then wraps the arithmetic, including the checked ANSI functions, decimal arithmetic and the Decimal256 remainder (create_modulo_exprgains anull_short_circuitflag), keepingCheckedBinaryExproutermost so errors still carry the query context.skippableis a required argument ofcreateMathExpression, so a newMathExprserde cannot leave it out.CometConcatwraps the nativeconcatwithwithNullShortCircuitwhen it has more than one argument.LazyLogicaldoes since https://github.com/apache/datafusion-comet/pull/7326. Without speculation,a (b - c)under ANSI, as in TPC-H Q1, was up to 2x slower on batches with NULLs, because selecting the rows costs more than the arithmetic. Whether to speculate depends on the cost of the argument:- A cheap argument is always speculated.
is_cheapis a list of what has been measured: columns, literals, integer and floating point+,-and(including the ANSIchecked_add,checked_subandchecked_mul), and widening casts, over cheap children only. It can grow as more shapes are measured.- Any other argument, such as a cast that parses a string, decimal arithmetic or a string function, is speculated only when at least half the rows need it. Otherwise the rows are selected directly, as before this change.
Masked, shared byNullShortCircuitandLazyLogical, holds a masked argument: its projection, built lazily on the firstevaluateso that planning nested wrappers stays linear, and whether speculation still holds. Both speculate a costly argument when at least half the rows need it;LazyLogicalused to require more than half.Cast::cannot_fail_at_any_costaccepts whatCast::cannot_faildoes, and casts that cannot fail for any value in any eval mode: from an integer to a decimal with enough integral digits, and from an integer, floating point number, boolean or decimal to a string. Dates and timestamps are left out because Arrow's formatter cannot format a value outsidechrono's range, which Spark can hold, and so are binary and nested types.NullShortCircuitdoes not wrap such arguments at all.Cast::cannot_failandCast::is_infallibleare unchanged.case_when.rsgainscannot_fail_at_any_cost, whichNullShortCircuituses instead ofcannot_fail, so these operands are not wrapped at all. Beyondcannot_failit accepts the casts above; aCheckOverflowthat returns NULL on overflow (LEGACY and TRY), withCheckedBinaryExpr, which only adds the query context; decimal+,-andnarrow enough that the planner builds aBinaryExprrather than aWideDecimalBinaryExpr, whose exact result fits in ani128; the string functionsupper,lower,trim,ltrim,rtrimandsubstring, whose kernels only fail on arity or type, which planning catches; and the widening integer casts the planner adds to their arguments. In ANSI theCheckOverflowfails on overflow, so the decimal shape is still wrapped there.cannot_failstays as onmain, becauseLazyLogicalandlazy_in_listuse it forAND,ORandIN. Masking a costlier operand that cannot fail, such assubstring, saves them evaluating it on the rows the earlier operand decides, while forNullShortCircuitmasking it would only add the cost of selecting rows. So each consumer picks its check by cost, as CASE WHEN already does withis_infallible.speculatefield explains why speculation is not tried again after it fails once.is_deterministicmoves from private topub(super), acceptsCheckOverflow, and judges a nestedNullShortCircuitby its inner expression alone, so decimal and nested operands speculate too, and the check stays linear in the size of the tree.unwrap_checkedin the planner also looks throughNullShortCircuit, so the redundantCheckOverflowover a wide decimal add, subtract or multiply is still dropped.NullShortCircuitandwithNullShortCircuitdocs state that the function must return NULL wherever an earlier argument is NULL without checking the later ones, since with speculation it can see any value there.create_binary_exprlost its last caller and is removed. Its tests callcreate_binary_expr_with_options.An operand that Spark does evaluate still fails as before. A wrapped operand is NULL only on rows whose result is NULL anyway.
The same bug is on
branch-1.2, which hasNullShortCircuitbut not https://github.com/apache/datafusion-comet/pull/7326, which this builds on. The backport is tracked in https://github.com/apache/datafusion-comet/issues/7542.How are these changes tested?
<!--
We typically require tests for all PRs in order to:
1. Prevent the code from being accidentally broken by subsequent changes
2. Serve as another way to document the expected behavior of the code
If tests are not included in your PR, please explain why (for example, are they covered by existing tests)?
-->
spark/src/test/resources/sql-tests/expressions/math/arithmetic_ansi_skipped_operands.sqlandspark/src/test/resources/sql-tests/expressions/string/concat_ansi_skipped_arguments.sqlrun every operator over a batch where the failing operand is malformed only on rows that Spark skips, over one where every row is skipped, and overmostly_null, where three rows in four are skipped, so a cheap argument (n (big - 1)) is speculated, overflows on a skipped row and falls back to selecting rows, and a costly one (n + CAST(txt AS INT)) selects the rows directly. They cover tinyint, smallint, int, bigint, double, decimal and the Decimal256 paths,try_addandtry_divide(includingtry_divide(CAST(txt AS INT), n)with a zero divisor, integer and decimal), and a zero divisor, where a NULL dividend gives NULL and a malformed one raisesCAST_INVALID_INPUTbefore the zero check, as in Spark.expect_error_class(CAST_INVALID_INPUT)queries check that an operand Spark evaluates still fails, including the reverse order (CAST(txt AS INT) + n,n DIV CAST(txt AS INT)). Before the fix, the firstqueryin each file fails withCAST_INVALID_INPUT.null_short_circuit.rs,lazy_logical.rsandmodulo_expr.rs: the divisor is evaluated first, it still fails where the dividend is NULL,ordermust be a permutation, the order surviveswith_new_children, speculative evaluation falls back to selected rows, a mostly-NULL batch selects the rows of a costly argument without speculating, a cheap one (checked_mul(a, checked_sub(b, c))) is speculated even with three rows in four skipped and still gives the right result when the skipped rows overflow, decimal and nested operands speculate,is_deterministicchecks 64 nested wrappers in linear time, 64 nested wrappers that each read a different column are planned in linear time in bothnull_short_circuit.rsandlazy_logical.rs, and an argument needed by exactly half the rows is speculated.test_check_overflow_skipped_over_short_circuited_wide_decimalinplanner.rschecks that the redundantCheckOverflowis still dropped over a wrapped wide decimal add.spark/src/test/resources/sql-tests/expressions/math/arithmetic_legacy_skipped_operands.sqlruns LEGACY integer+andchains of 2 to 5 operands, including one that starts with aBIGINTcast, whose last operandelement_at(arr, i)fails on the rows Spark skips, so Comet must return NULL there. It still raisesINVALID_INDEX_OF_ZEROwhere Spark evaluates that operand, and where it comes first.concat_ansi_skipped_arguments.sqlalso has a query whose arguments cast an int, decimal, boolean and double to a string.cast.rs:test_cannot_fail_casts_succeed_on_extreme_values_in_every_modecasts the extreme values of each type thatcannot_fail_at_any_costaccepts beyondcannot_failin LEGACY, TRY and ANSI mode, including decimals of scale 38 and -2, and checks thatcannot_failrejects them.test_casts_that_can_fail_are_not_claimedchecks that one integral digit fewer, a negative scale, dates, timestamps, binary,Decimal256and lists are accepted by neither.infallible_expressionsincase_when.rschecks thatcannot_fail_at_any_cost, and notcannot_fail, accepts a non-failingCheckOverflowover decimal+,-andbelow a width of 38,CheckedBinaryExpr, the six string functions and the widening casts on their arguments, and that it rejects a failingCheckOverflow, a width of 38, a narrowing cast, a function not in the list (initcap) and a listed function over an argument that can fail.costlier_right_operand_that_cannot_fail_is_evaluated_lazilyinlazy_logical.rschecks thatANDwith asubstring, an int todecimal(12,2)cast or an int to string cast on the right is still planned asLazyLogicaland gives the right result, and thatlazy_in_liststill masks asubstringcandidate. It fails on the previous head.native/spark-expr/benches/null_short_circuit.rscompares the eager form with the wrapped one at 0, 10, 50, 70 and 90% NULL, fora + CAST(s AS BIGINT),a (b - c), the decimalp CheckOverflow(1.00 - d)in ANSI and LEGACY mode, aWideDecimalBinaryExprmultiply, a multiply by a rescaling decimal cast,concat(q, upper(s)), andconcat(q, CAST(b AS STRING))over a longb.make_batchmakes exactly the given share of the rows NULL, so the 50% row is where speculation starts. It asserts which shapes are wrapped: the LEGACY decimal shape,concat(q, upper(s))andconcat(q, CAST(b AS STRING))are not. Anyone can rerun it withcd native && cargo bench -p datafusion-comet-spark-expr --bench null_short_circuit.native/spark-expr/benches/lazy_logical.rsaddsx AND substring(s, 2, 4) = '2345', the shape measured in https://github.com/apache/datafusion-comet/pull/7456#discussion_r4704557732 . Rerun it withcd native && cargo bench -p datafusion-comet-spark-expr --bench lazy_logical.µs per 8192-row batch, best of two rounds on one GitHub runner (run, from the measurement-only branch https://github.com/tlfua/datafusion-comet/tree/bench/7246-r6 , which runs the benchmarks on this head, on the source of the previous head d54d9a469, and for
lazy_logicalon the source ofmainf67d51d24). "eager" is the unwrapped expression, which gives wrong errors.x AND substring(s, 2, 4) = '2345'with 10% ofxNULL, where "pending" is the share of rows wherexis true:| pending | eager |
main(f67d51d24) | previous head (d54d9a469) | this head (aa9cb705b) ||---|---|---|---|---|
| 0% | 171.7 | 29.2 | 172.9 | 29.5 |
| 10% | 171.9 | 49.4 | 172.7 | 50.0 |
| 50% | 171.0 | 170.2 | 173.6 | 172.7 |
| 90% | 171.0 | 170.1 | 173.0 | 171.4 |
| 100% | 171.8 | 171.0 | 172.6 | 172.3 |
<details><summary>Full <code>null_short_circuit</code> table</summary>
| shape | NULLs | eager | previous head (d54d9a469) | this head (aa9cb705b) |
|---|---|---|---|---|
|
a + CAST(s AS BIGINT)| 0% | 96.6 | 97.1 | 94.7 || | 10% | 96.9 | 96.9 | 97.0 |
| | 50% | 93.6 | 94.0 | 92.1 |
| | 70% | 90.4 | 49.2 | 49.3 |
| | 90% | 91.2 | 18.8 | 18.8 |
|
a (b - c)over longs | 0% | 14.4 | 14.8 | 14.8 || | 10% | 15.4 | 15.7 | 15.8 |
| | 50% | 12.4 | 12.7 | 12.8 |
| | 70% | 10.8 | 11.1 | 11.1 |
| | 90% | 9.3 | 9.6 | 9.7 |
| decimal
p (1.00 - d), ANSI | 0% | 41.7 | 42.1 | 42.0 || | 10% | 44.6 | 45.2 | 45.0 |
| | 50% | 32.6 | 33.2 | 33.0 |
| | 70% | 26.6 | 23.1 | 22.3 |
| | 90% | 20.8 | 11.4 | 11.1 |
| decimal
p (1.00 - d), LEGACY | 0% | 41.7 | 41.9 | 41.7 || | 10% | 44.6 | 44.8 | 44.6 |
| | 50% | 32.7 | 32.8 | 32.7 |
| | 70% | 26.7 | 26.7 | 26.7 |
| | 90% | 20.9 | 21.0 | 20.9 |
| wide decimal
p (d d)| 0% | 274.6 | 275.3 | 275.2 || | 10% | 258.4 | 258.5 | 258.9 |
| | 50% | 204.8 | 205.6 | 205.6 |
| | 70% | 178.3 | 88.9 | 88.7 |
| | 90% | 151.7 | 32.6 | 32.2 |
|
p CAST(d AS DECIMAL(12,4))| 0% | 93.2 | 93.6 | 93.4 || | 10% | 96.1 | 96.6 | 96.7 |
| | 50% | 84.1 | 84.7 | 84.5 |
| | 70% | 78.0 | 38.3 | 37.7 |
| | 90% | 72.2 | 16.3 | 16.1 |
|
concat(q, upper(s))| 0% | 99.2 | 92.4 | 99.2 || | 10% | 114.3 | 104.9 | 122.0 |
| | 50% | 105.8 | 96.4 | 107.8 |
| | 70% | 98.6 | 86.6 | 96.1 |
| | 90% | 93.4 | 85.3 | 92.0 |
|
concat(q, CAST(b AS STRING))| 0% | 186.9 | 175.8 | 186.9 || | 10% | 208.2 | 199.1 | 207.5 |
| | 50% | 212.8 | 201.3 | 213.7 |
| | 70% | 193.8 | 186.0 | 194.4 |
| | 90% | 181.8 | 173.6 | 181.7 |
</details>
What the numbers show:
x AND substring(s, 2, 4) = '2345'is back tomain: 29.5 against 29.2 µs at 0% pending, where the previous head took 172.9. Every otherlazy_logicalandlazy_inshape is within noise ofmainor faster.null_short_circuitshape changes whether it is wrapped. With exactly 50% NULL, the 50% row now speculates, so the wrapped form costs the same as eager there (92.1 against 93.6 µs fora + CAST(s AS BIGINT)). The previous benchmark made 4108 of 8192 rows NULL there, so fewer than half the rows needed the operand and it measured the case below the threshold.concatshapes read 5 to 10% higher than the previous head, but the eager form, which runs none of the changed code, moved by the same amount in this build (concat(q, upper(s))at 0% NULL: 92.5 to 99.2 µs eager). This commit only changes thecannot_failchecks, which run at planning. In the previous round the same rows moved the other way between builds.a * (b - c)is 1.2x to 2.2x faster than selecting rows at 10 to 70% NULL, while for the other shapes always speculating is 1.2x to 5x slower than selecting rows at 70 to 90% NULL, which is why only cheap arguments are always speculated.Commands run locally (macOS, default Spark profile), on aa9cb705b:
cargo test -p datafusion-comet-spark-expr --lib: 1409 passed.cargo clippy -p datafusion-comet-spark-expr --all-targets -- -D warnings: passed.cargo fmt --all -- --check: passed../dev/release/check-rat.sh HEAD: no unapproved licenses.cargo bench -p datafusion-comet-spark-expr --bench null_short_circuit --bench lazy_logical: run on a GitHub runner, numbers above.I did not run the Maven suites locally this round. Fork CI (Comet CI (fork run), default Spark profile) passed on aa9cb705b, after rerunning two Iceberg jobs that failed to download from Maven Central (HTTP 429).
I did not run the Spark SQL suite or the other Spark profiles locally. This changes the serde and native expressions, and the
run-all-spark-profilesandrun-benchmark-checklabels are on this PR.