← Back to Pull requests

fix: skip arithmetic and concat operands that Spark skips under ANSI mode #7456

Open
unknown opened this pull request with 650 lines diff across 8 files
View on GitHub
unknown unknown commented on Nov 03, 2026 08:05 UTC
Author

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 #123 indicates that this PR will close issue #123.
-->

Part of https://github.com/apache/datafusion-comet/issues/7246. It fixes the arithmetic and concat rows of that issue. OR, AND and IN were 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:

  • +, - and evaluate the right operand only where the left one is not NULL (BinaryExpression.nullSafeCodeGen).

  • /, DIV and % 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).

  • concat evaluates 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 t returns NULL in Spark wherever n is NULL, whatever txt holds, but fails in Comet when such a row has a malformed txt.

    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_order evaluates the arguments in a given order, so that the divisor of a division comes first. wrap keeps the order of the children.

  • MathExpr gains null_short_circuit. The serde sets it when the operand that Spark may skip can be skipped (canSkipEvaluation), which is the right operand of +, - and and the left one of /, DIV and %. The planner then wraps the arithmetic, including the checked ANSI functions, decimal arithmetic and the Decimal256 remainder (create_modulo_expr gains a null_short_circuit flag), keeping CheckedBinaryExpr outermost so errors still carry the query context. skippable is a required argument of createMathExpression, so a new MathExpr serde cannot leave it out.

  • The rebalanced LEGACY integer add and multiply chains set the flag on each node from the operands of its right half, so each operand is evaluated on the same rows as in Spark's left-deep chain.

  • CometConcat wraps the native concat with withNullShortCircuit when it has more than one argument.

  • A masked argument that is deterministic may first be evaluated over the whole batch, selecting the rows only if that fails, as LazyLogical does 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_cheap is a list of what has been measured: columns, literals, integer and floating point +, - and
    (including the ANSI checked_add, checked_sub and checked_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 by NullShortCircuit and LazyLogical, holds a masked argument: its projection, built lazily on the first evaluate so that planning nested wrappers stays linear, and whether speculation still holds. Both speculate a costly argument when at least half the rows need it; LazyLogical used to require more than half.

  • Cast::cannot_fail_at_any_cost accepts what Cast::cannot_fail does, 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 outside chrono's range, which Spark can hold, and so are binary and nested types. NullShortCircuit does not wrap such arguments at all. Cast::cannot_fail and Cast::is_infallible are unchanged.

  • case_when.rs gains cannot_fail_at_any_cost, which NullShortCircuit uses instead of cannot_fail, so these operands are not wrapped at all. Beyond cannot_fail it accepts the casts above; a CheckOverflow that returns NULL on overflow (LEGACY and TRY), with CheckedBinaryExpr, which only adds the query context; decimal +, - and narrow enough that the planner builds a BinaryExpr rather than a WideDecimalBinaryExpr, whose exact result fits in an i128; the string functions upper, lower, trim, ltrim, rtrim and substring, whose kernels only fail on arity or type, which planning catches; and the widening integer casts the planner adds to their arguments. In ANSI the CheckOverflow fails on overflow, so the decimal shape is still wrapped there.

  • cannot_fail stays as on main, because LazyLogical and lazy_in_list use it for AND, OR and IN. Masking a costlier operand that cannot fail, such as substring, saves them evaluating it on the rows the earlier operand decides, while for NullShortCircuit masking it would only add the cost of selecting rows. So each consumer picks its check by cost, as CASE WHEN already does with is_infallible.

  • The speculate field explains why speculation is not tried again after it fails once.

  • is_deterministic moves from private to pub(super), accepts CheckOverflow, and judges a nested NullShortCircuit by its inner expression alone, so decimal and nested operands speculate too, and the check stays linear in the size of the tree.

  • unwrap_checked in the planner also looks through NullShortCircuit, so the redundant CheckOverflow over a wide decimal add, subtract or multiply is still dropped.

  • The NullShortCircuit and withNullShortCircuit docs 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_expr lost its last caller and is removed. Its tests call create_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 has NullShortCircuit but 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.sql and spark/src/test/resources/sql-tests/expressions/string/concat_ansi_skipped_arguments.sql run 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 over mostly_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_add and try_divide (including try_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 raises CAST_INVALID_INPUT before 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 first query in each file fails with CAST_INVALID_INPUT.

  • Rust unit tests in null_short_circuit.rs, lazy_logical.rs and modulo_expr.rs: the divisor is evaluated first, it still fails where the dividend is NULL, order must be a permutation, the order survives with_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_deterministic checks 64 nested wrappers in linear time, 64 nested wrappers that each read a different column are planned in linear time in both null_short_circuit.rs and lazy_logical.rs, and an argument needed by exactly half the rows is speculated. test_check_overflow_skipped_over_short_circuited_wide_decimal in planner.rs checks that the redundant CheckOverflow is still dropped over a wrapped wide decimal add.

  • spark/src/test/resources/sql-tests/expressions/math/arithmetic_legacy_skipped_operands.sql runs LEGACY integer + and chains of 2 to 5 operands, including one that starts with a BIGINT cast, whose last operand element_at(arr, i) fails on the rows Spark skips, so Comet must return NULL there. It still raises INVALID_INDEX_OF_ZERO where Spark evaluates that operand, and where it comes first. concat_ansi_skipped_arguments.sql also 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_mode casts the extreme values of each type that cannot_fail_at_any_cost accepts beyond cannot_fail in LEGACY, TRY and ANSI mode, including decimals of scale 38 and -2, and checks that cannot_fail rejects them. test_casts_that_can_fail_are_not_claimed checks that one integral digit fewer, a negative scale, dates, timestamps, binary, Decimal256 and lists are accepted by neither.

  • infallible_expressions in case_when.rs checks that cannot_fail_at_any_cost, and not cannot_fail, accepts a non-failing CheckOverflow over decimal +, - and below a width of 38, CheckedBinaryExpr, the six string functions and the widening casts on their arguments, and that it rejects a failing CheckOverflow, 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_lazily in lazy_logical.rs checks that AND with a substring, an int to decimal(12,2) cast or an int to string cast on the right is still planned as LazyLogical and gives the right result, and that lazy_in_list still masks a substring candidate. It fails on the previous head.

  • native/spark-expr/benches/null_short_circuit.rs compares the eager form with the wrapped one at 0, 10, 50, 70 and 90% NULL, for a + CAST(s AS BIGINT), a (b - c), the decimal p CheckOverflow(1.00 - d) in ANSI and LEGACY mode, a WideDecimalBinaryExpr multiply, a multiply by a rescaling decimal cast, concat(q, upper(s)), and concat(q, CAST(b AS STRING)) over a long b. make_batch makes 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)) and concat(q, CAST(b AS STRING)) are not. Anyone can rerun it with cd native && cargo bench -p datafusion-comet-spark-expr --bench null_short_circuit.

  • native/spark-expr/benches/lazy_logical.rs adds x AND substring(s, 2, 4) = '2345', the shape measured in https://github.com/apache/datafusion-comet/pull/7456#discussion_r4704557732 . Rerun it with cd 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_logical on the source of main f67d51d24). "eager" is the unwrapped expression, which gives wrong errors.

    x AND substring(s, 2, 4) = '2345' with 10% of x NULL, where "pending" is the share of rows where x is 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 to main: 29.5 against 29.2 µs at 0% pending, where the previous head took 172.9. Every other lazy_logical and lazy_in shape is within noise of main or faster.

  • No null_short_circuit shape 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 for a + 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.

  • The two concat shapes 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 the cannot_fail checks, which run at planning. In the previous round the same rows moved the other way between builds.

  • An earlier run that forced always or never speculating (run, branch https://github.com/tlfua/datafusion-comet/tree/bench/7246 ) showed that always speculating 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-profiles and run-benchmark-check labels are on this PR.

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: sunchao Review duration: 40001m
    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
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    46%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    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
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 46.7% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 46.7% · Lower = rushed or shallow review
    46.7%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 27.7% · Safe to merge
    27.7%