fix: fall back TopK whose later sort key can fail under ANSI #7457
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
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.17 · 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.289
Real PR Conversation Timeline
1 comments
"Review active on #7457"
general
weight: 0.35
rich7420
Which issue does this PR close?
Part of https://github.com/apache/datafusion-comet/issues/7246 (the TopK case). The
OR/AND/INcases were fixed by https://github.com/apache/datafusion-comet/pull/7326; the arithmetic andconcatcases 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 2over(1, MaxInt), (2, 5), (3, MaxInt), (4, 7), (5, 9)returns(1, 2147483647), (2, 5)in Spark but fails withARITHMETIC_OVERFLOWin Comet.Spark's
TakeOrderedAndProjectExeccompares rows withLazilyGeneratedOrdering, whose generated comparator (GenerateOrdering.genComparisons) evaluates sort key i for a pair of rows only when keys 0..i-1 tie. Comet's TopK (DataFusionSortExecwithfetch) 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.getSupportLevelreturnsIncompatiblewhen any sort key after the first can fail. What "can fail" means depends onspark.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=truestill 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
cannotFailallow-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
raisesInAnyModeholds:raise_erroror a user-defined function,element_aton an array unless the index is a nonzero constant,rlikewith a non-constant pattern,sliceunless the start is a nonzero constant and the length a non-negative constant,array_insertunless the position is a nonzero constant, andsequencewith 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
cannotFailrejects (hasAnsiEvalMode), such asb + 1in 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 functioncannot_failincase_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 andabsin any mode, other numeric arithmetic / negation /absoutside 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/broundfor float/double, and for integral types only with ANSI off (never decimal)- hash:
hash,xxhash64,md5,sha1,sha2,crc32Under ANSI anything else, including
lpad/rpad/repeat,element_at,date_addandto_date, is treated as able to fail.arrays.scalastill has its own narrowercannotThrowforarray_append; moving it ontocannotFailis 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 thatkeyCastCannotFailalready 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 ignoressafeand raises for such years in every mode. Both are checked at any depth inside arrays, structs and maps withSupportLevel.containsType(privateCometCast.failsInAnyMode), since a nested cast applies the same kernels to each element, field, key and value.docs/source/user-guide/latest/compatibility/operators.mddocuments the fallback under ANSI and the narrower ANSI-off fallback, saysallowIncompatibleapplies in either mode, and notes that a sort without a LIMIT and with no exchange beneath it (such asSORT BY) still runs in Comet.expressions/array/array_null_short_circuit.sql: its two-key TopK query has a later keyarray_position(ai, CAST(s AS INT)), whose ANSI cast can fail, so it now falls back; the query is wrapped withspark.comet.operator.TakeOrderedAndProjectExec.allowIncompatible=trueto 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 BYand window ordering are not affected in Spark either (the range exchange or window pre-projection evaluates every key); the plain-sort divergence forSORT BYand 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):expect_fallback),query),ARITHMETIC_OVERFLOW(expect_error),substring/upper/lower/length) stay in Comet. Without this, TPC-DS q79 plan stability changed on Spark 4.x,coalesce(b + 1, 0),IF(a > 3, b + 1, 0)) andround(b, -1)under ANSI fall back;try_caststays in Comet, timestamp casts (including TRY) fall back,topk_typestable with NULL, NaN, -0.0, int/long bounds, empty strings and boundary dates runs the string, datetime, math and hash keys in Comet,,+,-, negation andabsstay in Comet, andCAST(dt AS STRING)falls back,s.xstays in Comet with ANSI on and off,topk_nestedtable with out-of-range values (timestamp_micros(9000000000000000000),date_from_unix_date(100000000)):try_castover nested timestamps and dates (array, struct, map, andarray<struct<timestamp>>) falls back under ANSI. The file writes timestamps asTIMESTAMP_MICROS.-
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)andlpad(s, 5)stay in Comet,- timestamp-cast keys
date_add(ts, 1)andconcat(s, ts)stay in Comet,- on a
topk_arraystable,element_at(arr, 1),slice(arr, 1, 1)andarray_insert(arr, 1, 0)stay in Comet, whileelement_at(arr, 0),slice(arr, a - 1, 1),array_insert(arr, a - 1, 0)andsequence(a, 1, 1)fall back,- a temporary view created with ANSI on as
SELECT a, b FROM topk ORDER BY a, b + 1 LIMIT 2falls back when queried.CometCodegenSuiteadds "a ScalaUDF later sort key runs a TopK on Spark with ANSI off". A SQL file test cannot cover this withraise_error: Comet has no serde forRaiseError, 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=truewithout the fix: failed withARITHMETIC_OVERFLOWonORDER BY a, b + 1 LIMIT 2, as expected.topk_later_key array_null_short_circuitand four other related SQL files after the second commit: passed (6 succeeded, 0 failed).topk_later_key(1 succeeded) andarray_null_short_circuit(5 succeeded): passed.topk_later_key(1 succeeded) andarray_null_short_circuit(5 succeeded): passed.topk_later_key(1 succeeded, 0 failed): passed.slice/array_insert/sequence, docs):make format PROFILES="-Dmaven.gitcommitid.skip=true"(formats and compiles main and test code, Spark 4.1): passed. ThefailOnError/ansiEnabledfields used byhasAnsiEvalModewere 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 HEADpassed ("No unapproved licenses"),prettier --check "/.md"and thedev/ciscripts 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 aNumericEvalContext; the follow-up commit readsevalModeby class,make formatpassed and RAT passed.topk_regexqueries totopk_later_key_ansi.sql, anexpect_fallbackquery with the pattern in a col and a plainquerywith a constant pattern.make format PROFILES="-Dmaven.gitcommitid.skip=true": passed. RAT,prettier --check "*/.md"and thedev/ciscripts: 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-testsandrun-all-spark-profileslabels run the Spark SQL suites and the other Spark profiles.