← Back to Pull requests

fix: fall back TopK whose later sort key can fail under ANSI #7457

Closed
unknown closed this pull request without merging on Nov 24, 2026 21:39 UTC
View on GitHub
unknown unknown commented on Nov 03, 2026 08:23 UTC
Author

Which issue does this PR close?

Part of https://github.com/apache/datafusion-comet/issues/7246 (the TopK case). The OR/AND/IN cases were fixed by https://github.com/apache/datafusion-comet/pull/7326; the arithmetic and concat cases are handled in a separate PR.

Rationale for this change

With spark.sql.ansi.enabled=true, SELECT a, b FROM topk ORDER BY a, b + 1 LIMIT 2 over (1, MaxInt), (2, 5), (3, MaxInt), (4, 7), (5, 9) returns (1, 2147483647), (2, 5) in Spark but fails with ARITHMETIC_OVERFLOW in Comet.

Spark's TakeOrderedAndProjectExec compares rows with LazilyGeneratedOrdering, whose generated comparator (GenerateOrdering.genComparisons) evaluates sort key i for a pair of rows only when keys 0..i-1 tie. Comet's TopK (DataFusion SortExec with fetch) evaluates every sort key over the whole batch, so a later key that can fail raises on rows Spark never evaluates it for.

Making Comet's TopK evaluate later keys lazily was considered and rejected for this PR: which row pairs Spark compares depends on Guava's Ordering.leastOf, and DataFusion's TopK keeps a heap across batches, so per-batch masking cannot reproduce Spark's evaluation set without a custom operator. A scoped fallback is correct and small, in line with https://github.com/apache/datafusion-comet/issues/6006.

What changes are included in this PR?

  • CometTakeOrderedAndProjectExec.getSupportLevel returns Incompatible when any sort key after the first can fail. What "can fail" means depends on spark.sql.ansi.enabled (see the next bullets). The first key is evaluated for every row in Spark too when the input has at least two rows, so it is not restricted; the single-row case is tracked in https://github.com/apache/datafusion-comet/issues/7527 . In either mode, spark.comet.operator.TakeOrderedAndProjectExec.allowIncompatible=true still runs such a TopK in Comet.

  • QueryPlanSerde.laterSortKeyThatCanFail(sortOrder) returns the first key after the leading one that can fail:

  • - Under ANSI, any key that the cannotFail allow-list below does not accept.
    - With ANSI off (as suggested by @coderfender, after @andygrove pointed out that 1.2 ran these TopKs in Comet), a key for which raisesInAnyMode holds: raise_error or a user-defined function, element_at on an array unless the index is a nonzero constant, rlike with a non-constant pattern, slice unless the start is a nonzero constant and the length a non-negative constant, array_insert unless the position is a nonzero constant, and sequence with bounds that are not all constants. Spark raises for each of these in every mode.
    - Also with ANSI off, a key that holds a node still in ANSI eval mode that cannotFail rejects (hasAnsiEvalMode), such as b + 1 in the ordering of a view created with ANSI on: a view keeps the configs it was created with.
    - A cast to or from a timestamp does not make an ANSI-off TopK fall back: Spark does not raise there, and the Comet kernel failure on extreme years also happens in a projection, so it is left to https://github.com/apache/datafusion-comet/issues/7471 .
    - Both ANSI-off checks are best-effort; the expressions they do not cover yet are tracked in https://github.com/apache/datafusion-comet/issues/7585 . The plain sort follow-up ( https://github.com/apache/datafusion-comet/issues/7470 ) can reuse them.
  • QueryPlanSerde.cannotFail(expr) (the ANSI check): a conservative allow-list judged from Spark semantics (read for 3.4.3, 3.5.8, 4.0.1 and 4.1.1), independent of the Rust function cannot_fail in case_when.rs, with each Rust implementation also checked for data-dependent errors: columns, literals, comparisons, IN, boolean logic, null checks, If/CaseWhen/Coalesce, float normalization, struct field access (s.x), float/double +/-/, negation and abs in any mode, other numeric arithmetic / negation / abs outside ANSI mode, casts that cannot fail, and:

  • - string: substring, upper, lower, length, octet_length, bit_length, trim/ltrim/rtrim, replace, initcap, concat_ws, concat (string, at least one argument), reverse (string)
    - datetime: year, quarter, month, day, dayofweek, weekday, dayofyear, hour, minute, second
    - math: floor, ceil, sqrt, exp, log, signum, greatest, least, isnan, nanvl; round/bround for float/double, and for integral types only with ANSI off (never decimal)
    - hash: hash, xxhash64, md5, sha1, sha2, crc32

    Under ANSI anything else, including lpad/rpad/repeat, element_at, date_add and to_date, is treated as able to fail. arrays.scala still has its own narrower cannotThrow for array_append; moving it onto cannotFail is tracked in https://github.com/apache/datafusion-comet/issues/7585 .

  • CometCast.cannotFail(cast): TRY casts, LEGACY casts between atomic types, string to binary, and ANSI casts that keyCastCannotFail already proves exact. A cast to or from a timestamp never qualifies: the Rust kernels go through chrono, which rejects years Spark accepts, and raise even for TRY ( https://github.com/apache/datafusion-comet/issues/7471 ). Nor does a cast from a date to a string: arrow-cast's formatter ignores safe and raises for such years in every mode. Both are checked at any depth inside arrays, structs and maps with SupportLevel.containsType (private CometCast.failsInAnyMode), since a nested cast applies the same kernels to each element, field, key and value.

  • docs/source/user-guide/latest/compatibility/operators.md documents the fallback under ANSI and the narrower ANSI-off fallback, says allowIncompatible applies in either mode, and notes that a sort without a LIMIT and with no exchange beneath it (such as SORT BY) still runs in Comet.

  • expressions/array/array_null_short_circuit.sql: its two-key TopK query has a later key array_position(ai, CAST(s AS INT)), whose ANSI cast can fail, so it now falls back; the query is wrapped with spark.comet.operator.TakeOrderedAndProjectExec.allowIncompatible=true to keep testing the Rust array kernels.
  • Known trade-off: under ANSI the allow-list is conservative, so a later key built from a function outside it also falls back even though it may not fail. With ANSI off only the keys listed above fall back, so every other TopK runs in Comet as in 1.2. Global ORDER BY and window ordering are not affected in Spark either (the range exchange or window pre-projection evaluates every key); the plain-sort divergence for SORT BY and single-partition sorts is tracked in https://github.com/apache/datafusion-comet/issues/7470 .

    How are these changes tested?

    New SQL file test spark/src/test/resources/sql-tests/operators/topk_later_key_ansi.sql (ANSI on, AQE off):

  • the reproduction from the issue and two more fallible later keys (expect_fallback),

  • later keys that cannot fail, and a fallible first key, stay in Comet (query),

  • rows that tie on the first key still raise ARITHMETIC_OVERFLOW (expect_error),

  • string later keys (substring/upper/lower/length) stay in Comet. Without this, TPC-DS q79 plan stability changed on Spark 4.x,

  • a fallible key nested under an allowed one (coalesce(b + 1, 0), IF(a > 3, b + 1, 0)) and round(b, -1) under ANSI fall back; try_cast stays in Comet, timestamp casts (including TRY) fall back,

  • a topk_types table with NULL, NaN, -0.0, int/long bounds, empty strings and boundary dates runs the string, datetime, math and hash keys in Comet,

  • under ANSI, float/double , +, -, negation and abs stay in Comet, and CAST(dt AS STRING) falls back,

  • a struct field key s.x stays in Comet with ANSI on and off,

  • a topk_nested table with out-of-range values (timestamp_micros(9000000000000000000), date_from_unix_date(100000000)): try_cast over nested timestamps and dates (array, struct, map, and array<struct<timestamp>>) falls back under ANSI. The file writes timestamps as TIMESTAMP_MICROS.

  • with ANSI off:

  • - b + 1, -b, abs(b), a LEGACY string-to-int cast, round(b, -1), b / 0, b % 0, b DIV 0, l + 1, l 2, date_add(dt, 1) and lpad(s, 5) stay in Comet,
    - timestamp-cast keys date_add(ts, 1) and concat(s, ts) stay in Comet,
    - on a topk_arrays table, element_at(arr, 1), slice(arr, 1, 1) and array_insert(arr, 1, 0) stay in Comet, while element_at(arr, 0), slice(arr, a - 1, 1), array_insert(arr, a - 1, 0) and sequence(a, 1, 1) fall back,
    - a temporary view created with ANSI on as SELECT a, b FROM topk ORDER BY a, b + 1 LIMIT 2 falls back when queried.

    CometCodegenSuite adds "a ScalaUDF later sort key runs a TopK on Spark with ANSI off". A SQL file test cannot cover this with raise_error: Comet has no serde for RaiseError, so that TopK falls back for an unsupported expression before the later-key check runs.

    Commands run locally (Spark 4.1 default profile, macOS):

  • ./mvnw test -Dsuites="org.apache.comet.CometSqlFileTestSuite topk_later_key" -Dtest=none -Dmaven.gitcommitid.skip=true without the fix: failed with ARITHMETIC_OVERFLOW on ORDER BY a, b + 1 LIMIT 2, as expected.

  • Same command with the fix: passed (1 succeeded, 0 failed).

  • Same command for topk_later_key array_null_short_circuit and four other related SQL files after the second commit: passed (6 succeeded, 0 failed).

  • After the review changes, topk_later_key (1 succeeded) and array_null_short_circuit (5 succeeded): passed.

  • After coderfender's review, merged with the latest main: topk_later_key (1 succeeded) and array_null_short_circuit (5 succeeded): passed.

  • After rich7420's review (nested types): topk_later_key (1 succeeded, 0 failed): passed.

  • After andygrove's latest review (timestamp casts, views, slice/array_insert/sequence, docs): make format PROFILES="-Dmaven.gitcommitid.skip=true" (formats and compiles main and test code, Spark 4.1): passed. The failOnError/ansiEnabled fields used by hasAnsiEvalMode were checked in the Spark 3.5.8 and 4.0.1 sources. Preflight: JAVA_TOOL_OPTIONS=-Dfile.encoding=ANSI_X3.4-1968 ./dev/release/check-rat.sh HEAD passed ("No unapproved licenses"), prettier --check "/.md" and the dev/ci scripts passed; the mermaid check was not run locally. The SQL file and Scala tests for this commit were not run locally; fork CI ran them. Fork CI then failed the view test on Spark 4.1, because Spark 4.1 keeps the arithmetic eval mode inside a NumericEvalContext; the follow-up commit reads evalMode by class, make format passed and RAT passed.

  • After andygrove's rlike comment: added topk_regex queries to topk_later_key_ansi.sql, an expect_fallback query with the pattern in a col and a plain query with a constant pattern. make format PROFILES="-Dmaven.gitcommitid.skip=true": passed. RAT, prettier --check "*/.md" and the dev/ci scripts: passed. The SQL file tests were not run locally; fork CI ran them.
  • Fork CI ( https://github.com/tlfua/datafusion-comet/actions/runs/44472467670 ): All jobs passed on 1650696bf (some jobs were rerun after Maven Central download failures). Since this touches the serde, the run-spark-3.5-tests, run-spark-4.1-tests and run-all-spark-profiles labels run the Spark SQL suites and the other Spark profiles.

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: rich7420 Review duration: 31036m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). 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.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    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.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #7457"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% 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: 60.5% · Lower = rushed or shallow review
    60.5%
    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: 20.5% · Safe to merge
    20.5%