feat: run filter and exists lambdas natively with DataFusion's higher-order functions #7322
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 #7322"
general
weight: 0.35
rich7420
Which issue does this PR close?
Closes #7321.
Rationale for this change
filter(arr, x -> ...)ran natively only forx IS NOT NULL, andexists(arr, x -> ...)never did. Any other lambda went through the JVM codegen dispatcher, which evaluates it one element at a time like Spark does, plus the transfer of each batch, so such queries ran at about Spark's speed. DataFusion 55 evaluates a lambda once over all the elements of a batch, so Comet can use it when the body is made of natively supported expressions. This PR does that forfilter, witharray_filter, and forexists, witharray_any_match, which returns what Spark'sexistsreturns under three-valued logic.Release build, Spark 4.1, 1M rows of ten-element arrays (every fifth element is NULL), best time:
| Query | Spark | Comet before | Comet now |
| --- | --- | --- | --- |
|
filter(strs, x -> nvl(x, '') != '')| 616 ms | 547 ms | 307 ms ||
array_remove(array_compact(strs), '')| 587 ms | 252 ms | 252 ms ||
filter(ints, x -> x IS NOT NULL)| 286 ms | 124 ms | 125 ms ||
filter(ints, x -> x > threshold)| 346 ms | 335 ms | 110 ms |existsover 1M rows of ten-element arrays (every fifth element is NULL), Spark 3.5, release build, best time:| Query | Spark | Comet before | Comet now |
| --- | --- | --- | --- |
|
exists(ints, x -> x > 90)| 266 ms | 234 ms | 108 ms ||
exists(dbls, x -> x IS NULL OR x < 0 OR x > 90 OR x = 0)| 266 ms | 225 ms | 94 ms ||
exists(ints, x -> x > threshold)| 251 ms | 196 ms | 105 ms ||
size(dbls) < 1 OR exists(dbls, x -> x > 90)| 355 ms | 403 ms | 110 ms ||
exists(strs, x -> x IS NULL OR x = '')| 357 ms | 183 ms | 168 ms |filter(ints, x -> nvl(x, '') != '')is not in the first table because it no longer takes the lambda path: Comet runs it asarray_compact(see the last change below). In a separate local run (Spark 3.5.5,local[4], 2M rows of ten-element int arrays with every fifth element NULL, best of 5) it took 0.453 s on the dispatcher, 0.281 s with the native lambda alone, and 0.086 s asarray_compact, against 0.220 s on Spark.What changes are included in this PR?
HigherOrderFuncand aLambdaVariableexpression in the protobuf, and a planner arm that builds DataFusion'sHigherOrderFunctionExprwith aLambdaExpr. The lambda body is planned against the input schema plus the lambda parameter, so captured columns keep their indexes.CometArrayFilterandCometArrayExistsshare the code that serializes a lambda (theNativeLambdaSerdetrait). They serialize the body natively when all of these hold: the lambda has one parameter, the array has a primitive, decimal, string, binary, date or timestamp element type, the body is deterministic, has no nested lambda and uses the default string collation, it reads no captured column that is not fixed-width, it holds no TRY cast that can make a null map key and no function applied to a date or timestamp other than a comparison, a NULL test,IF,CASE WHEN,COALESCEor a cast to a number (native date functions and casts return NULL or fail beyond chrono's year range, #6843 and #7471), and every subexpression of it converts natively. Otherwise they keep using the dispatcher, as before. The planner arm resolves the function by name through the session, which registers DataFusion's higher-order functions.existshas three more conditions.spark.sql.legacy.followThreeValuedLogicInArrayExistsmust be true (the default): with it false Spark returns false wherearray_any_matchreturns NULL, soexistsstays on the dispatcher. No expression in the body may raise, whatever operators it uses: Spark stops at the first element that matches and never evaluates the body on the elements after it, whilearray_any_matchevaluates it on every element, so with ANSI onexists(array(1, 0), x -> 100 / x > 1)would raise where Spark returns true. It is the same check as theINrule below. And the array argument must not contain a TRY cast whose map key cast can fail (CometCast.canProduceNullMapKey): it makes a null key, which Arrow cannot hold (#6172). The dispatcher runs such an argument in Spark's own code, where the map never reaches Arrow.filterstays on the dispatcher.filterbody that usesINstays on the dispatcher unless no expression in it can raise. Spark stops at the first candidate that matches and evaluates none for a NULL value, while the nativeINevaluates every candidate when one can fail. This is the per-row case in #6006. The check classifies each expression and fails closed, with the same rules as #7529: numeric arithmetic and casts between plain types raise only in the ANSI eval mode they carry, andelement_atraises for the index 0 in any mode, so an expression that is not known to be safe counts as able to raise.ANDandORare lazy natively (LazyLogical, from #7326), as areCASE,IFandCOALESCE, so they are not restricted.is_deterministicinlazy_logical.rsaccepts aLambdaVariable, so aLazyLogicalin a lambda body can still try the whole batch.NullShortCircuitevaluates the later arguments of functions such asarray_containson a projection of just the columns they read. It now projects and re-indexes aLambdaVariablelike aColumn, whichfilter(ints, x -> array_contains(other, x))needs. A lambda inside the projected expression binds its own parameters, so those are not columns of the batch and are left alone. Without that, a higher-order function inside an expression that is evaluated for only some rows, such as the right operand ofANDorOR, or an argument ofarray_contains, failed withproject index N out of bounds.case_when.rstreats aLambdaVariablelike aColumnwhen it decides whether an expression can fail.filter(arr, x -> nvl(x, '') != '')on an array of integers, floats, decimals, dates or timestamps runs asarray_compact, the wayx IS NOT NULLdoes. Spark plans it asNOT (coalesce(CAST(x AS STRING), '') = ''), in either operand order. No such cast is empty, so the predicate holds exactly whenxis not NULL, and the native lambda would otherwise cast every element to a string first. A string element has no cast and stays on the lambda, as does any other default value, comparison or extra condition.spark.comet.exec.nativeLambda.enabled(default true) turns the native path off.nvl(x, '') != ''on a numeric array is handled. Thefilterandexistsrows of the Supported Expressions page link to it.CometArrayExistscalls the dispatcher itself, asCometArrayFilterdoes, so the generated Implementation column says Native for both.CometHigherOrderFunctionBenchmarkproduces the numbers above,filterandexists.Not included:
transformandforallstill use the dispatcher. DataFusion 55.2 hasarray_transformbut no all-match function.How are these changes tested?
array_filter_native_lambda.sqlruns 42 queries against Spark with ANSI mode off: every supported element type includingtinyintandsmallint, NULL, empty and all-NULL arrays and batches, literal arrays, NaN and -0.0, captured columns, a parameter that shadows a column, nested filters, and bodies that must stay on the dispatcher. Each query pins its path withexpect_native(filter)orexpect_dispatch(filter). It also has queries with a lambda inside an argument evaluated for only some rows (array_contains(ints, size(filter(ints, x -> x > 1)))) and as the right operand ofANDandOR.array_filter_native_lambda_ansi.sqlcovers the short-circuit queries under ANSI mode, andarray_filter_native_lambda_captured.sqlcovers bodies that read captured columns of each kind and array functions that take the lambda parameter, with ANSI on and off.array_filter_native_lambda_unsupported_body.sqlpins the bodies with a null-map-key cast, a date or timestamp cast, or a date function such asyearorlast_dayto the dispatcher, forfilterandexists, with a widening map cast date comparisons and a timestamp to number cast on the native path.array_filter_native_lambda_disabled.sqlchecks thatspark.comet.exec.nativeLambda.enabled=falseruns every lambda on the dispatcher.array_filter_numeric_nvl.sqlcovers thearray_compactrewrite: every numeric, date and timestamp element type, both operand orders,<>andcoalesce, NULL, empty and all-NULL arrays, NaN and -0.0, the result insidesizeandarray_max, and the string, other-default,=and extra-condition shapes that must keep their lambda semantics. Spark refusescoalesce(boolean, ''), so there is no boolean query.array_exists_native_lambda.sqlruns 19 queries against Spark with ANSI mode off, 15 of them pinned withexpect_native(exists): string, integer, double and float arrays, NULL, empty and all-NULL arrays, predicates that are NULL for some elements and false for the rest, captured columns,flattenas the argument, andexistsas the right operand ofORand inside an argument ofarray_contains. Two bodies can raise on an element Spark never reaches and are pinned withexpect_dispatch(exists):element_atwith the index 0, andtimestamp_secondsof a BIGINT, which raises on overflow. Two aggregate queries only compare with Spark, because the harness counts an expression inside an aggregate as dispatched as well as native.array_exists_native_lambda_ansi.sqlruns six queries under ANSI mode. Four bodies raise only on an element after the first match (a division, an addition, a cast of a string, and a division insideCASE) and are pinned withexpect_dispatch(exists). Two that cannot raise are pinned withexpect_native(exists). Without the condition onexists, the division query raisedDIVIDE_BY_ZEROnatively, and theelement_atquery in the non-ANSI file raisedINVALID_INDEX_OF_ZERO, where Spark returns true for both.array_exists_native_lambda_two_valued.sqlchecks thatexistsstays on the dispatcher with three-valued logic off.codegen_dispatch_null_map_key.sqlpins theexistswith a TRY map cast whose key cast can fail to the dispatcher, and the same query with a widening key cast to the native path.array_filterresult, a non-array argument, an unknown function),array_any_matchas the right operand ofORandAND, andNullShortCircuitwith a lambda variable in a masked argument. Without theNullShortCircuitchange, the last one fails withLambdaVariable references column … but batch only has 0 columns.run-spark-4.1-testslabel. Locally, the lambda,existsandcodegen_dispatchSQL files,CometCodegenHOFSuite,CometArrayExpressionSuiteandGenerateDocsSuitepass on Spark 4.1, and the SQL files andCometCodegenHOFSuitepass on Spark 3.5.