← Back to Pull requests

feat: run filter and exists lambdas natively with DataFusion's higher-order functions #7322

Closed
unknown closed this pull request without merging on Nov 20, 2026 01:04 UTC
View on GitHub
unknown unknown commented on Oct 29, 2026 20:12 UTC
Author

Which issue does this PR close?

Closes #7321.

Rationale for this change

filter(arr, x -> ...) ran natively only for x IS NOT NULL, and exists(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 for filter, with array_filter, and for exists, with array_any_match, which returns what Spark's exists returns 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 |

exists over 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 as array_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 as array_compact, against 0.220 s on Spark.

What changes are included in this PR?

  • A HigherOrderFunc and a LambdaVariable expression in the protobuf, and a planner arm that builds DataFusion's HigherOrderFunctionExpr with a LambdaExpr. The lambda body is planned against the input schema plus the lambda parameter, so captured columns keep their indexes.

  • CometArrayFilter and CometArrayExists share the code that serializes a lambda (the NativeLambdaSerde trait). 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, COALESCE or 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.

  • exists has three more conditions. spark.sql.legacy.followThreeValuedLogicInArrayExists must be true (the default): with it false Spark returns false where array_any_match returns NULL, so exists stays 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, while array_any_match evaluates it on every element, so with ANSI on exists(array(1, 0), x -> 100 / x > 1) would raise where Spark returns true. It is the same check as the IN rule 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.

  • The JVM codegen dispatcher now declines a tree that reads a lambda parameter bound outside the tree. Its kernel is fed only columns, so such a parameter would read as NULL. A body that needs the dispatcher therefore fails to convert natively and the whole filter stays on the dispatcher.

  • DataFusion copies each column the lambda captures once per element of the array before it evaluates the body, and those copies are not reserved with the memory pool. A body that reads a captured string, binary, array, struct or map column stays on the dispatcher. Numeric, boolean, date, timestamp and decimal captures run natively.

  • A filter body that uses IN stays 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 native IN evaluates 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, and element_at raises for the index 0 in any mode, so an expression that is not known to be safe counts as able to raise. AND and OR are lazy natively (LazyLogical, from #7326), as are CASE, IF and COALESCE, so they are not restricted. is_deterministic in lazy_logical.rs accepts a LambdaVariable, so a LazyLogical in a lambda body can still try the whole batch.

  • NullShortCircuit evaluates the later arguments of functions such as array_contains on a projection of just the columns they read. It now projects and re-indexes a LambdaVariable like a Column, which filter(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 of AND or OR, or an argument of array_contains, failed with project index N out of bounds. case_when.rs treats a LambdaVariable like a Column when it decides whether an expression can fail.

  • filter(arr, x -> nvl(x, '') != '') on an array of integers, floats, decimals, dates or timestamps runs as array_compact, the way x IS NOT NULL does. Spark plans it as NOT (coalesce(CAST(x AS STRING), '') = ''), in either operand order. No such cast is empty, so the predicate holds exactly when x is 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.

  • A new "Expression Tuning" page in the user guide covers lambdas: which forms run natively, the equivalent built-in array functions, and how nvl(x, '') != '' on a numeric array is handled. The filter and exists rows of the Supported Expressions page link to it. CometArrayExists calls the dispatcher itself, as CometArrayFilter does, so the generated Implementation column says Native for both. CometHigherOrderFunctionBenchmark produces the numbers above, filter and exists.
  • Not included: transform and forall still use the dispatcher. DataFusion 55.2 has array_transform but no all-match function.

    How are these changes tested?

  • array_filter_native_lambda.sql runs 42 queries against Spark with ANSI mode off: every supported element type including tinyint and smallint, 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 with expect_native(filter) or expect_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 of AND and OR.

  • array_filter_native_lambda_ansi.sql covers the short-circuit queries under ANSI mode, and array_filter_native_lambda_captured.sql covers 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.sql pins the bodies with a null-map-key cast, a date or timestamp cast, or a date function such as year or last_day to the dispatcher, for filter and exists, with a widening map cast date comparisons and a timestamp to number cast on the native path. array_filter_native_lambda_disabled.sql checks that spark.comet.exec.nativeLambda.enabled=false runs every lambda on the dispatcher.

  • array_filter_numeric_nvl.sql covers the array_compact rewrite: every numeric, date and timestamp element type, both operand orders, <> and coalesce, NULL, empty and all-NULL arrays, NaN and -0.0, the result inside size and array_max, and the string, other-default, = and extra-condition shapes that must keep their lambda semantics. Spark refuses coalesce(boolean, ''), so there is no boolean query.

  • array_exists_native_lambda.sql runs 19 queries against Spark with ANSI mode off, 15 of them pinned with expect_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, flatten as the argument, and exists as the right operand of OR and inside an argument of array_contains. Two bodies can raise on an element Spark never reaches and are pinned with expect_dispatch(exists): element_at with the index 0, and timestamp_seconds of 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.sql runs 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 inside CASE) and are pinned with expect_dispatch(exists). Two that cannot raise are pinned with expect_native(exists). Without the condition on exists, the division query raised DIVIDE_BY_ZERO natively, and the element_at query in the non-ANSI file raised INVALID_INDEX_OF_ZERO, where Spark returns true for both.

  • array_exists_native_lambda_two_valued.sql checks that exists stays on the dispatcher with three-valued logic off. codegen_dispatch_null_map_key.sql pins the exists with 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.

  • Rust unit tests cover the planner arm (the array_filter result, a non-array argument, an unknown function), array_any_match as the right operand of OR and AND, and NullShortCircuit with a lambda variable in a masked argument. Without the NullShortCircuit change, the last one fails with LambdaVariable references column … but batch only has 0 columns.

  • A one-off comparison against Spark on 300k rows, with 25 lambda bodies and ANSI on and off, matched in every case where Spark does not raise.

  • CI passes on this commit: the Comet suites on every Spark profile, the Rust tests and clippy, and the Spark 4.1 SQL suite through the run-spark-4.1-tests label. Locally, the lambda, exists and codegen_dispatch SQL files, CometCodegenHOFSuite, CometArrayExpressionSuite and GenerateDocsSuite pass on Spark 4.1, and the SQL files and CometCodegenHOFSuite pass on Spark 3.5.
  • Diff: 650 lines (+487 / -163) across 8 files Reviewer: rich7420 Review duration: 30531m
    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 #7322"
    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%