[SPARK-XXXXX][SQL] Push the domains of filtered columns down to native data sources #59929
Blocking (P1): When values is empty, the NULL-in-list check is 0 < 0 and points is empty, so this branch also handles NOT (x IN ()). It returns every non-null value with nullAllowed = false. Under the default semantics, though, In.eval with an empty list is false for every row, null included (predicates.scala:513-517; legacyNullInEmptyBehavior defaults to !ansiEnabled). So NOT (x IN ()) is true for rows where x is null.
The DataFrame API builds that predicate from col("x").isin() or isInCollection(Seq.empty); SQL rejects an empty IN list. The default optimizer folds it away first. With spark.sql.optimizer.excludedRules set to OptimizeIn and NullPropagation, neither of which is non-excludable, it reaches pushPredicates. The library then gets null_allowed = false with ranges = NULL. A library that skips null-only files or row groups, as the description's may_match does, drops rows that match, and Spark's post-scan filter never sees them.
Handling an empty list before the other branches fixes it: no value when not negated, and no constraint when negated. That is correct under both the current and the legacy semantics, without reading the legacy flag. ParquetFilters likewise builds an IN filter only when values.nonEmpty.
Verification:
Non-blocking (P2): This defines null_allowed only as whether null is in the domain. For a struct-field path, neither the header nor the Filter Pushdown docs say what the field's value is in a row whose struct, or an enclosing struct, is null. Spark derives the domain as Spark SQL evaluates it, so the value is null there: st.y IS NULL gives st.y: NULL.
Arrow allows a child array to hold valid values in slots where the struct is null (the header already notes a related validity trap for batches). A library that computes statistics from the child array of y can then find null_count = 0 in a block whose rows all have a null st. For st.y IS NULL it sees no null and no range, skips the block, and loses every row in it. Only null-allowing domains are affected. Readers whose statistics already count those rows as null are fine, as with Parquet's definition levels.
One sentence here and in the docs closes it: a field is null in every row where it or an enclosing struct is null, and statistics compared with null_allowed must count those rows as null. The alternative is for Spark to withhold null-allowing domains for struct fields.
Verification:
Non-blocking (P2): Every range sequence that reaches this loop is a List: Seq(...) in compare and startsWith, the point and gap lists of in, the result of unionRanges, and result.toSeq on the ArrayBuffer below. List.length and List.apply are linear, so each iteration re-walks both inputs, and the sweep is quadratic in the number of ranges.
This runs on the driver during optimization, by default for every native batch scan, whenever two pushed predicates constrain the same column with ranges. Take col("id").isin(ids: _*) && col("id") > 0 with 10^5 ids: OptimizeIn turns the list into an InSet, which is pushed as one IN carrying every literal. That makes about 10^10 list-node visits, tens of seconds of planning, and around 3 x 10^4 literals it already takes seconds. A NOT IN list, or two IN lists on one column, behaves the same.
Converting both inputs once with toIndexedSeq, or walking them with buffered iterators, restores the linear sweep without changing any domain.
Verification:
Nit (P3): TestRangePlanner.pushDomains keeps only the hull of the ranges. For (-inf, 3L), (3L, +inf) it plans [0, 5) and [5, 10), so it reads id 3 too, and the unpushed id % 2 = 0 also rejects that row. In the first case the planner reads exactly [40, 50). No row that the planner reads is rejected only by a pushed predicate, so if pushPredicates stopped returning the pushed predicates for post-scan evaluation, both checkAnswer calls would still pass. Only the native tests would catch it, and they are skipped without a C++ compiler and Java 22 or later.
A filter like id <> 3 AND id < 8 would make this regression-sensitive. Its hull plans [0, 4) and [4, 8), so id 3 is read and only the pushed id <> 3 rejects it. Assert the partitions and the answer, and fix this comment.
Verification:
Nit (P3): Every received() line in this test has - for null and at most one range. No native filter here uses IS NULL, <=>, <>, NOT IN or a same-column OR. So if NativeLibrary.pushDomains lost the null_allowed byte, or NativeArrow.exportDomains exported only the first range, everything here would still pass. Those are the encodings that tell a library which null or between-value rows it must keep, and the test library already prints null and every range.
Separately, the collated-column assertion added at line 355 checks PushedFilters == "[]". That holds even if Spark pushed a byte-wise domain for the UTF8_LCASE column, because the library marks only the id domain used unless use_domains is all.
Separate cases such as NOT (id <=> 5) (null plus two ranges), name IS NULL and id NOT IN (5, 20) would cover the encodings. A collated case with domains_path or use_domains = all would cover the exclusion. Combining a null check with NOT IN on the same column in one filter would not work: NOT IN excludes null, so that domain is empty.
Verification:
Nit (P3): For a null x and a non-null v, x <=> v is false, not null, so NOT (x <=> v) is true. That is why NULL is in the expected domain, and it is what ColumnDomains.compare says. Read literally, this line says x <=> v is true for null.
// x <=> v is false, not null, when x is null, so NOT (x <=> v) is true for null.
Verification:
Review summary
The derivation rules handle NaN, -0.0, UTF-8 order, collations and three-valued logic carefully, and the property check against Spark's own evaluation backs them up. Six findings follow, plus one question for the author.
NOT (x IN ()) gets a domain without null, although it is true for null rows under the default IN semantics. The DataFrame API can build it, and once OptimizeIn and NullPropagation are excluded nothing folds it, so a library that skips all-null data can silently drop matching rows.intersectRanges indexes Lists by position. When another range constrains the same column, planning time grows quadratically with the literals of an IN or NOT IN list.- The JVM columnar test cannot detect a lost post-scan filter, and its comment misdescribes what the planner reads.
- The native tests never observe
null_allowed, multiple ranges or the collation exclusion at the library boundary.- A
ColumnDomainsSuite comment misstates null-safe equality.Cross-cutting observations
Separation: The three issues have different owners and fixes: a derivation rule in Spark, a sentence in the implementor contract, and native test cases. Each repair closes its own issue, so the shared theme does not change their grouping, scope or severity.
Findings
6 total: 0 P0, 1 P1, 2 P2, 3 P3.
Blocking (P1)
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnDomains.scala:278 — see inline.Non-blocking (P2)
sql/core/src/main/resources/org/apache/spark/sql/datasource/spark_datasource.h:386 — see inline.sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnDomains.scala:449 — see inline.Nit (P3)
sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnarDataSourceSuite.scala:100 — see inline.sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/ffi/NativeDataSourceSuite.scala:419 — see inline.sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnDomainsSuite.scala:70 — see inline.PR description suggestions
Decision challenges
Release target of push_domains and its config: 4.4.0, or master-only 5.0.0?
Verified in the checkout:
.version("5.0.0"), which is master's version (5.0.0-SNAPSHOT).branch-4.x is 4.4.0-SNAPSHOT, and its spark_datasource.h has no push_domains.spark.sql.dataSource.native.paths declares 4.4.0. The header says the interface exists since 4.4.0, with ABI version 1 in every Spark 4 release from 4.4.0.The repository's versioning guidance uses the branch-4.x version for changes that are also merged there. It keeps master's version for breaking changes and for dependency upgrades. This change is additive within ABI version 1, so by that rule it would normally go to branch-4.x as well and document 4.4.0. The description's note that a library built against the 4.4 header has a smaller table suggests instead that 4.4.0 is meant to ship without push_domains.
Could you confirm the release target? If this lands in 4.4.0, the config should declare 4.4.0, and the 4.4-header note in the description no longer holds. If it is master-only, 5.0.0 is consistent, and it would help to say why in the description, since the guidance does not list this case.
Generated by Omnigent on Databricks
<!-- SPARK_OSS_REVIEW_REQUEST 34618627224 -->
<!-- SPARK_DEV_REVIEW_CODE {"findings":[{"delivery":"inline","fingerprint":"ffe366c95628a3eb2d1c","id":"pass-a:negated-empty-in-excludes-null"},{"delivery":"inline","fingerprint":"13e64bb5eb914bb42645","id":"pass-a:struct-field-null-semantics-unspecified"},{"delivery":"inline","fingerprint":"ab092e3e2325c068594c","id":"pass-b:intersect-ranges-quadratic-list-indexing"},{"delivery":"inline","fingerprint":"b79ee396420c6511ef20","id":"pass-b:columnar-domain-test-cannot-observe-post-scan-filter"},{"delivery":"inline","fingerprint":"9693ec0c91577524ba5c","id":"pass-b:native-domain-tests-miss-null-and-multi-range"},{"delivery":"inline","fingerprint":"26998e39aef3609a2672","id":"pass-b:null-safe-negation-test-comment"}],"head_sha":"fc0ef28e8ee1456880283b715ec835aa7b5e17a5","verdict_sha256":"7255ea9c6472ab0b5de93e19a6002a5bfd818c5eaf80eb6c9f7190c2dbe04c66"} -->
[P2] Keep range intersection linear for IN-derived lists
For filters combining a large IN or NOT IN list with a range predicate on the same column, in() produces ranges as a List. Both length and indexed access traverse that list on every iteration here, making the intended linear sweep quadratic and potentially stalling driver-side query planning. Use iterators or convert the inputs to indexed collections before the loop.
Done in daba613: in now handles an empty list first. x IN () gets an empty domain, since it is never true, and NOT (x IN ()) constrains no column, which holds with and without spark.sql.legacy.nullInEmptyListBehavior. ColumnDomainsSuite checks both with the DataFrame API (isin() and isInCollection(Nil)), and the property check now also evaluates filters with empty IN lists, under the default and the legacy behavior.
Done in daba613, with the alternative: Spark no longer passes a domain that has null for a field of a struct. It is the safer option, since a library that computes its statistics from the Arrow child arrays, which is the natural way with Arrow, would otherwise skip the rows of a null struct, and Spark cannot detect that. A domain without null is safe either way: the rows of a null struct never match it, and the values that a child array holds under a null struct only make a library read more. Only filters such as st.y IS NULL or NOT (st.y <=> v) lose their domain.
The header (null_allowed and push_domains) and the Filter Pushdown section of the guide now say that a field is null where the struct, or a struct that contains it, is null, and that Spark only passes domains without null for the fields of structs. The property check now has a struct column with null structs and null fields.
Done in daba613: intersectRanges sweeps indexed copies of both inputs (toIndexedSeq), so each step is constant work. A new test derives the domains of an IN list of 100,000 values and of its NOT IN, each combined with a range of the same column, and checks the 99,949 points and the 99,950 gaps under a limit of 20 seconds. Here it takes about 0.2 seconds, while with the previous sweep it did not finish within a minute (91 seconds).
Done in daba613: intersectRanges sweeps indexed copies of both inputs (toIndexedSeq), so it is linear again. The new test "the domains of long IN lists" combines IN and NOT IN lists of 100,000 values with a range of the same column, and takes about 0.2 seconds, against 91 seconds before.
Done in daba613: the test now reads id <> 3 AND id < 8. It asserts the partitions [0, 4) and [4, 8), which include 3, and an answer without 3, so it fails if Spark stops evaluating the pushed predicates after the scan. The comment of the id % 2 = 0 case now says that the data source reads all the ids, and the case checks that only NOT (id = 3) is pushed.
Done in daba613: the native test now also reads with NOT (id <=> 5) (null and two ranges), name IS NULL (null without ranges), id NOT IN (5, 20) (three ranges) and id < 3 OR (id > 22 AND id < 25), whose two ranges make the library skip three of its five blocks. Each case asserts the null flag and all the ranges that the library receives, and the rows. The collated case now reads with use_domains = all and domains_path, and checks that the library only gets the domain of id, and that the filter on the collated column is not shown as pushed.
Done in daba613, with the suggested wording.
The AI review requested by @HyukjinKwon did not finish. A committer can add the ai-review-requested label again to retry.
<!-- SPARK_OSS_REVIEW_REQUEST 34684729586 -->
Nit (P3): When x equals a listed value, x IN (..., NULL) is true, so NOT (x IN (..., NULL)) is false, not null. The expression is false or null and never true. That is why NONE is the right domain, and it is what the comment in ColumnDomains.in says. As written, this comment teaches the wrong rule for exactly the NOT IN-with-NULL case.
// Comparisons with null are null, and NOT (x IN (..., NULL)) is false or null: never true.
Verification:
Nit (P3): In SQL, -0.0 is a decimal literal, and a decimal zero has no sign: literals.sql.out records select -0.0 as decimal(1,1) with the value 0.0. So both filters here reach ColumnDomains with +0.0 and pass whether or not normalize runs. The property check's -0.0D cases do carry a negative zero, but they only go through ColumnDomain.contains, whose ordering treats -0.0 as equal to 0.0, and no native test filters on -0.0. The derivation itself is right. But if the normalization regressed, PushedDomains and the bounds that libraries get would show -0.0, and every test would still pass.
A double literal and a cast from a string carry the sign, and the expected strings stay the same:
assert(domains("d = -0.0D") == Seq("d: 0.0D"))
assert(domains("f > CAST('-0.0' AS FLOAT)") == Seq("f: NaN, (CAST('0.0' AS FLOAT), +inf)"))
Verification:
Nit (P3): NativeArrow.exportDomains must release the ranges it exports for this call unless the library moved them, after a successful call and after a failing one. No test would notice if it stopped doing so, or if NativeLibrary.pushDomains stopped checking the status. This function never fails on request and never moves the ranges. report the errors of native code has no push_domains case, and no test reads the Arrow allocator.
push_limit and prune_columns have no failure injection either, but they only pass an int and strings. push_domains is the first push step that hands the library Arrow memory, and that memory grows with the filters, such as one range for each value of an IN list. A leak would grow driver off-heap memory on every filtered native scan, and the native tests would not show it.
A maybeFail step for push_domains, a case for it in report the errors of native code, and an allocator check around a filtered scan would cover both, as InProcessPythonRuntimeSuite does for a call that fails.
Verification:
Review summary
All six findings of the previous review are fixed in daba613. NOT (x IN ()) now constrains no column. Fields of structs only get domains without null, and the header and guide say why. intersectRanges sweeps indexed copies, and a 100,000-value test guards it. The tests now observe a lost post-scan filter, null-allowing and multi-range domains, and the collation exclusion at the library boundary. The null-safe equality comment has the corrected wording.
This round found three small test issues. None of them changes what a query returns:
ColumnDomainsSuite comment says that NOT (x IN (..., NULL)) is null, but it is false when x is in the list.-0.0, which SQL parses as a decimal zero without a sign, so they never exercise the normalization they describe.push_domains or checks that Spark releases the Arrow ranges it exports for it.The release-target question from the previous review is still open. It follows below, with one more consequence.
Findings
3 total: 0 P0, 0 P1, 0 P2, 3 P3.
Nit (P3)
sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnDomainsSuite.scala:90 — see inline.sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnDomainsSuite.scala:151 — see inline.sql/core/src/test/resources/native-datasource/test_native_datasource.cc:1145 — see inline.Re-review status
Prior AI findings: 6 addressed, 0 still present; additional unresolved findings in this review: 3.
New attribution: 0 newly introduced, 3 late catch, 0 previously raised, 0 unattributed.
Remaining prior AI findings
No prior AI findings remain.
PR description suggestions
Decision challenges
Release line of push_domains: 4.4.0, or master-only 5.0.0 with a v1 table slot that branch-4.x could reuse?
The previous review asked which release first ships this, and the question is still open: the config still declares 5.0.0, and the description still says that a library built against the 4.4 header has a smaller table. This review adds what a master-only target would mean for the function table.
Verified in the checkout:
origin/branch-4.x is 4.4.0-SNAPSHOT. The spark_datasource.h of branch-4.x is identical to the merge base, so its SparkDsLibrary ends at close_data_writer. The sibling spark.sql.dataSource.native.paths declares 4.4.0.push_domains takes the slot after close_data_writer, and SPARK_DS_ABI_VERSION stays 1. NativeLibrary binds each function at its fixed offset whenever it fits in the size of the table (NativeLibrary.java:231).Suppose push_domains ships only from 5.0.0. Then the next function appended to the v1 table on branch-4.x takes the same offset. Spark 5.0 would call that function of a library built against the 4.x header as push_domains. A 4.x release would call the push_domains of a library built against the 5.0 header with the other function's signature. Neither the size of the table nor the ABI version tells the two apart.
The code is consistent within each line, so this depends only on the release plan, which the code cannot settle:
branch-4.x, the config should declare 4.4.0, and the description's statement about the 4.4 header changes.branch-4.x could reserve or backport the push_domains slot before any other addition there.Generated by Omnigent on Databricks
<!-- SPARK_OSS_REVIEW_REQUEST 34701305274 -->
<!-- SPARK_DEV_REVIEW_CODE {"findings":[{"delivery":"inline","fingerprint":"9ad3755bd83976ac0b42","id":"pass-b:test-comment-not-in-with-null"},{"delivery":"inline","fingerprint":"bf857a1c4a3eb8f94013","id":"pass-b:test-negative-zero-never-reaches-derivation"},{"delivery":"inline","fingerprint":"2d7b710de355234bb63f","id":"pass-b:test-push-domains-error-and-release-paths-untested"}],"head_sha":"87fe709f8826e509ede33f1bcf1a9f92c8e7071c","verdict_sha256":"e750570905ff507d07c3f0ac46c7f88d6fb28e26340ed1fb73a19f361cfcd9d2"} -->
Done in 9fc11f6, as suggested.
Done in 9fc11f6: the cases now use d = -0.0D and f > CAST('-0.0' AS FLOAT), with the same expected strings, and a comment says why. With normalize removed, the double case now fails with List("d: -0.0D") did not equal List("d: 0.0D").
Done in 9fc11f6: the test library fails push_domains with the option fail set to push_domains. "report the errors of native code" checks that the query fails with NATIVE_DATA_SOURCE_ERROR and the message of the library. It also checks that ArrowUtils.rootAllocator gets back all its memory after the failure, and after a scan with an IN filter whose domains the library takes. With the release of the ranges removed from NativeArrow.exportDomains, the check fails with 68202 bytes still allocated.
Non-blocking (P2): Because this mixes in SupportsPushDownV2Filters unconditionally, every filtered native batch scan now takes the V2 branch of PushDownUtils.pushFilters. That branch rebuilds the conjuncts that Spark evaluates after the scan as the translatable deterministic ones, then the untranslatable ones, then the nondeterministic ones (prioritizeFilters). On the base branch this builder implemented no filter interface, so pushFilters kept the conjuncts in their order. FilterExec evaluates them in that order and drops a row at the first false one.
Take rand() < 0.01 AND lower(name) LIKE '%n1%'. LikeSimplification turns the LIKE into Contains(Lower(name), 'n1'), which V2 translates. So LOWER and CONTAINS now run on every scanned row instead of on the 1% of rows that rand() keeps, and the seeded rand() now runs only on their survivors, so it samples other rows. array_contains(tags, 'x') AND upper(name) = 'X' behaves the same, since array_contains is not translated. Such expensive conjuncts derive no domain, so skipping offsets the cost only when another conjunct gives the library a domain that it uses.
Returning every predicate from pushPredicates does not keep the order. With spark.sql.dataSource.native.filterPushdown.enabled=false the builder still implements the interface, so turning the pushdown off does not restore the base branch's plan either. The reordering is Spark's heuristic for other V2 sources and helps the opposite shape, but here it also applies to filters that gain nothing from the pushdown.
Recommended change: Keep the written conjunct order of the post-scan filter for native scans. Add an internal capability, declared by the columnar scan builder, meaning that every pushed predicate is also returned for evaluation after the scan; when a builder has it, the filter pushdown helper uses the conjuncts in their written order, nondeterministic ones included, as the post-scan filters instead of reordering them. Other Data Source V2 builders keep the current order.
Why this works: The native builder still receives the translated deterministic predicates and derives domains from them, but the post-scan filter is the original conjunct list, so the base branch's evaluation order, and with it the work FilterExec does for each conjunct, stays the same whether or not domains are pushed and whatever the flag is set to.
Scope: Post-scan filter construction for native batch scans
Compatibility: Every pushed predicate is still evaluated after the scan, and the domains passed to libraries are unchanged.
Risks: Native scans that push domains no longer get the translatable-first order either, so a filter that writes an expensive untranslatable conjunct first keeps running it first, as on the base branch; this returns to the base branch's behavior rather than adding a regression, and it is limited to native scans.
Constraints: The capability stays internal, and only the columnar scan builder declares it, so the post-scan order of other V2 sources does not change. Nondeterministic conjuncts are still never pushed to the builder.
Exclusions:
Success: For a native batch scan, the post-scan Filter keeps its conjuncts in the order they had above the scan, nondeterministic ones included, except that the conjuncts with subqueries still come last, as on the base branch, whether or not domains are pushed and whatever spark.sql.dataSource.native.filterPushdown.enabled is set to. With the flag off, the optimized plan of a native scan matches the base branch. Domains are still derived, pushed and reported as before, and results do not change. Other Data Source V2 sources keep their current post-scan order.
Verification:
Nit (P3): (l.keySet ++ r.keySet).map { ... } builds a Set of (Column, Values) pairs before .toMap. From the fifth element on, Scala 2.13's Set builder switches to a HashSet and hashes every pair, and the case-class hash of Values walks its whole list of ranges; a Decimal bound even builds a BigDecimal to hash. derive folds every pushed predicate through and, so once five columns are constrained, each further predicate rehashes all the ranges of an earlier IN list. An example is d IN (<10,000 decimals>) AND a > 1 AND b > 1 AND c > 1 AND e > 1 with its inferred IS NOT NULL filters.
Mapping through an iterator, (l.keySet ++ r.keySet).iterator.map { ... }.toMap, or folding r into l, gives the same map and hashes only the columns. or builds its map the same way.
Verification:
Review summary
All three findings of the previous review are fixed in 9fc11f6. The comment on NOT (x IN (..., NULL)) now says that it is false or null. The -0.0 cases use literals that keep the sign of the zero. The test library can fail push_domains, and allocator checks confirm that Spark releases the exported ranges after a failure and after a success.
This round found six more issues. None of them makes a query return wrong results:
ColumnarScanBuilder now implements SupportsPushDownV2Filters, so Spark reorders the conjuncts that it evaluates after every filtered native scan, translatable ones first, also with spark.sql.dataSource.native.filterPushdown.enabled off. Filters that put a cheap, selective conjunct before an expensive translatable one get slower than on the base branch.and rehashes every range of earlier IN lists once five columns are constrained, and left-deep OR chains re-sort the accumulated ranges at every node.PushedFilters and PushedDomains, but only the formatted plan and the SQL UI do.tinyint, smallint or timestamp_ntz domains.Two questions for the author follow: the release-line question of the previous review, which is still open, and a new one.
Cross-cutting observations
The two derivation fixes do not depend on the answer to the domain-size question, because any cap on the number of ranges would only apply once the derivation has run.
Findings
6 total: 0 P0, 0 P1, 1 P2, 5 P3.
Non-blocking (P2)
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnarTable.scala:88 — see inline.Nit (P3)
and rehashes all accumulated ranges once five columns are constrained — sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnDomains.scala:375 — see inline.sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnDomains.scala:488 — see inline.docs/sql-native-data-sources.md:221 — see inline.sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/ffi/NativeDataSourceSuite.scala:997 — see inline.sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnDomainsSuite.scala:44 — see inline.Re-review status
Prior AI findings: 3 no longer raised, 0 still raised; additional unresolved findings in this review: 6.
New attribution: 0 newly introduced, 6 late catch, 0 previously raised, 0 unattributed.
PR description suggestions
Decision challenges
Release line of push_domains and its config: 4.4.0, or master-only 5.0.0?
The previous two reviews asked this, and it is still open: the config still declares 5.0.0, and the description still says that a library built against the 4.4 header has a smaller table.
Verified again at this head:
spark.sql.dataSource.native.filterPushdown.enabled declares .version("5.0.0"), master's version, while spark.sql.dataSource.native.enabled and spark.sql.dataSource.native.paths declare 4.4.0.branch-4.x was set to 4.4.0 and already has native data sources. Its spark_datasource.h is identical to the base of this PR, without push_domains.push_domains takes the table slot after close_data_writer, and SPARK_DS_ABI_VERSION stays 1. NativeLibrary binds each function at its fixed offset whenever the library's table is large enough.So if push_domains ships only from 5.0.0, the next function that branch-4.x appends to version 1 gets the same offset, and neither the table size nor the ABI version tells the two apart. If it also ships in 4.4.0, the config declares the wrong version.
Could you confirm which release first ships push_domains? If it is 4.4.0, the config should declare 4.4.0. If it is master-only, how will branch-4.x keep version 1 aligned? For example, it could reserve the slot before any other addition there. Either way, the header and the guide could say from which release Spark calls push_domains.
Should Spark bound the domains of long IN and NOT IN lists?
Verified in the checkout:
ColumnDomains.in turns an IN list into one point range per distinct value, and a NOT IN list into n+1 gaps, with no bound or compaction.NativeArrow.exportDomains exports every range. For a used domain, ColumnarScan.getMetaData renders all of them in PushedDomains, next to the whole predicate in PushedFilters. Formatted explain prints both without abbreviation, and the SQL UI shows the formatted plan by default.So with id IN (<100,000 values>) and a library that uses the domain, Spark exports 100,000 ranges, and every formatted plan of the query lists the values twice. A library that follows the examples over 10,000 files makes about 10^9 comparisons on the driver while planning. The base branch does none of this work, but it also skips no data.
What this review cannot settle is which trade-off fits the workloads you expect. Spark could compact a domain beyond some number of ranges, for example to its hull, which is still a superset. The header could tell libraries that the ranges are sorted, so that they can binary-search them. Or the cost may be acceptable for the list sizes you expect. Which do you intend?
Generated by Omnigent on Databricks
<!-- SPARK_OSS_REVIEW_REQUEST 35078364469 -->
<!-- SPARK_DEV_REVIEW_CODE {"findings":[{"delivery":"inline","fingerprint":"bdc6adc0ccfe588717cf","id":"pass-b:post-scan-conjunct-reorder"},{"delivery":"inline","fingerprint":"6c2751ccf63e466dbf6d","id":"pass-b:and-rehashes-accumulated-ranges"},{"delivery":"inline","fingerprint":"5a31a3d881d1a253a1dc","id":"pass-b:or-chains-quadratic-union"},{"delivery":"inline","fingerprint":"7bd52b1615d682f93bff","id":"pass-b:pushed-metadata-only-in-formatted-plan"},{"delivery":"inline","fingerprint":"13d0e0f9ca2c07f4eb02","id":"pass-b:moved-domain-ranges-untested"},{"delivery":"inline","fingerprint":"4944fc78d5d1dfa704d7","id":"pass-b:narrow-integral-and-ntz-domains-untested"}],"head_sha":"d204cbc31f382eaea8aa2cf0b338ad6323354469","verdict_sha256":"81c2cae7f12d3a9c486289dc6a393cb5f23eac58dfb96d52b73a52cab9e6a173"} -->
Nit (P3): Each OR node calls unionRanges with the ranges of its two sides, and this line concatenates them, sorts the result and folds it into a new list. A disjunction built with the DataFrame API, such as ids.map(v => col("id") === v).reduce(_ || _), is a left-deep tree. So the i-th OR node copies, sorts and rebuilds the i ranges accumulated so far, and no optimizer rule turns such a chain of equalities into IN. With 10,000 ids that is on the order of 10^8 range operations on the driver while planning, about a second by estimate, where one sort of the whole chain would do.
Collecting the disjuncts of nested ORs, and of ANDs under NOT, before a single union per column would make it O(k log k). It needs to keep the current rules for disjuncts that match no row and for columns that only some disjuncts constrain.
Verification:
Nit (P3): ColumnarScan exposes PushedFilters and PushedDomains only through getMetaData, which only DataSourceV2ScanExecBase.verboseStringWithOperatorId prints. BatchScanExec.simpleString, which df.explain(), EXPLAIN and EXPLAIN EXTENDED print, shows the output, the scan's description and RuntimeFilters, and here the description is just the short name of the data source. So a library author who checks with df.explain() whether Spark pushed a domain sees neither entry and would conclude that nothing was pushed. They only appear with EXPLAIN FORMATTED, df.explain("formatted") and in the SQL UI.
The push_domains comment in spark_datasource.h makes the same claim. Naming the formatted plan and the SQL UI in both places fixes it.
Verification:
Nit (P3): These checks cover a failing push_domains and a successful one, but in both cases Spark releases the ranges itself, since the test library only reads domain->ranges in place. The header also lets a library move the ranges and their schema to take ownership, and both examples in the description do so (arrow-rs from_ffi, Arrow C++ ImportArray). NativeArrow.exportDomains relies on that when it calls release and close on both structs and then closes the root. If that cleanup ever freed the exported buffers whatever the library did, a library that keeps the moved ranges in its reader for partitions would read freed memory, and every test here would still pass.
A test library option could cover that path: move the ranges in push_domains, read them when planning the partitions, and release them in close_reader, with allocator checks before and after the reader is closed.
This extends an existing discussion.
Verification:
Nit (P3): The header promises domains for tinyint, smallint and timestamp_ntz columns, and isComparable accepts ByteType, ShortType and TimestampNTZType. But none of these schemas has such a column, and neither does ColumnarDataSourceSuite or the native test library. The gap is wider for tinyint and smallint: t = 1 compares CAST(t AS INT) in the analyzed plan that predicates reads, so the column only gets a domain after the optimizer's UnwrapCastInBinaryComparison. Dropping one of these types from isComparable, or a change that keeps the cast, would silently stop data skipping on such columns, and every suite would still pass.
Cases for these types here would cover the derivation. An end-to-end case in which t = 1 on a tinyint column gets its domain after optimization would cover the cast unwrapping. For that case, the JVM test planner would have to report the column's domain, since today it only reads bigint bounds of the first column.
Verification:
Done in ad6187b, as recommended: the new internal mix-in EvaluatesAllPushedPredicates (in org.apache.spark.sql.internal.connector) tells PushDownUtils.pushFilters that a SupportsPushDownV2Filters builder returns all the predicates that it gets, and then the post-scan filters are the filters in the order of the query, nondeterministic ones included, instead of the translated ones first. ColumnarScanBuilder declares it, so this only changes native scans, with the flag on and off; other V2 sources keep their order. New test in ColumnarDataSourceSuite, "keep the order of the filters that Spark evaluates after a scan": rand(0) < 0.5 AND lower(name) LIKE '%e1%' keeps rand before the Contains with the flag on and off, and it fails without the mix-in.
Done in ad6187b: and builds its map through an iterator, so only the columns are hashed. or became a single merge of all the disjuncts (see the next comment), which builds its map the same way. The new test "the domains of long chains of ORs, and of IN lists with other columns" also combines an IN list of 20,000 values with predicates on five other columns.
Done in ad6187b: constraint collects the disjuncts of a chain of ORs, and of ANDs under NOT, with nested NOTs, using a stack of its own (a chain of 20,000 ORs is deeper than the stack of the thread), and orAll merges them at once: the columns that all the disjuncts constrain, with one sort of all their ranges. It keeps the rules of the pairwise version: a disjunct that matches no row adds no row, and a column that only some disjuncts constrain is not constrained. New test: a left-deep chain of 20,000 equalities, as reduce(_ || _) builds it, gives the domain of the IN list of the same values, and NOT of a chain of <> gives the points.
Fixed in ad6187b: the guide now says that the formatted plan (EXPLAIN FORMATTED, or df.explain("formatted")) and the SQL tab of the Spark UI show PushedFilters and PushedDomains, and the comment of used in spark_datasource.h says the same.
spark-test
HyukjinKwon
What changes were proposed in this pull request?
This PR adds filter pushdown to native data sources (SPARK-60101), as a follow-up of #59424, which left predicate pushdown out. Instead of passing filters to a library as expression trees, Spark passes the domains of the columns that the filters constrain: for each column, the values that it can have in the rows that match. A library compares them with the statistics of its data to skip what cannot match, such as files, row groups or blocks.
C interface.
spark_datasource.hgets a new struct,SparkDsDomain, and a new optional function,push_domains. The function is appended at the end ofSparkDsLibrary, afterclose_data_writer. A library built against the 4.4 header has a smaller table, so Spark never calls it there, andSPARK_DS_ABI_VERSIONstays 1. A domain has:path: the index of the column in the schema to read, then the index of the field in each struct, for a field of a struct;null_allowedandnan_allowed;ranges: a struct array oflow,high,low_inclusiveandhigh_inclusive, withNULLfor any other value. The bounds have the Arrow type of the column in the schema to read, and a null bound means no bound. The ranges are sorted and do not overlap, and a single value is a range whose bounds are equal and inclusive.The library sets
usedfor the domains that it uses, and the plan shows the filters of those domains asPushedFilters, and the domains asPushedDomains.Deriving domains.
ColumnDomainsderives the domains from the V2 predicates that Data Source V2 pushes:=,<>,<=>,<,<=,>,>=),IN,IS NULL,IS NOT NULLandSTARTS_WITH;AND,ORandNOT.NOTis pushed to the leaves, and anORkeeps only the columns that both sides constrain.The semantics are Spark's:
NOT (x IN (1, NULL))matches no row;x IN (), which the DataFrame API can build, is never true, andNOT (x IN ())constrains no column, with or withoutspark.sql.legacy.nullInEmptyListBehavior;nan_allowed) rather than a bound;A domain is a superset of the values of the matching rows. Spark keeps evaluating all the filters after the scan, which is the second kind of
SupportsPushDownV2Filters.pushedPredicates(), as for Parquet row-group filters. So a library can only read less, never return wrong results by over-filtering. The existingpush_limitandprune_columnssemantics don't change: Spark still doesn't push a limit with a filter, and still reads the filtered columns.Other changes:
ColumnarScanBuilderimplementsSupportsPushDownV2Filters.spark.sql.dataSource.native.filterPushdown.enabled(default true) turns the pushdown off, for example to check whether a library skips data that matches.Example: a downstream implementation. A Rust reader with arrow-rs that keeps the domain of a
bigintcolumnidand plans only the files whose min/max statistics may match. The same check works for row groups or pages. It was compiled and tested against arrow-rs 58.3.0, with the ranges exported as Spark exports them.The library sets
push_domains: Some(push_domains)in itsSparkDsLibrary. Becausepush_domainsis the last function of the table, the struct must declare all the functions of the header, as bindgen generates them. Some points for real libraries:doubleorfloatcolumn also needs a NaN count: a file that has NaN, or may have, can only be skipped whennan_allowedis false.<,>=), nottotal_cmp, so that -0.0 equals 0.0.serialize_reader.<details>
<summary>The same in C++, with Arrow C++ (compiled and tested against Arrow C++ 24)</summary>
</details>
Why are the changes needed?
Without filter pushdown, a native scan reads all of its data even for selective queries. The predicate design dropped from #59424 passed JSON expression trees. That made every library implement Spark's expression semantics: three-valued logic, partial use only under AND/OR, NaN order, literal encodings. Each of these was easy to get wrong silently, as the review threads on #59424 showed.
Domains move all of that into Spark, where it is implemented once and tested. A library only checks ranges against its statistics, as Presto/Trino (
TupleDomain), DuckDB (TableFilterSet) and Velox (per-column filters) do for their scans. Expression-tree pushdown, for example with Substrait, can be added later as another function, for sources that evaluate whole expressions.Does this PR introduce _any_ user-facing change?
Yes, for native data sources, which are unreleased (4.4.0):
push_domainsand structSparkDsDomaininspark_datasource.h;PushedFiltersandPushedDomainsin the plan of a native scan;spark.sql.dataSource.native.filterPushdown.enabled.How was this patch tested?
ColumnDomainsSuite(new):- The domains of comparisons,
IN(also with an empty list, from the DataFrame API), null checks,AND/OR/NOT, NaN and -0.0, strings, prefixes (including U+10FFFF and the surrogate gap), collations, binary values, nested fields (only without null) and other types.- A check against Spark's own evaluation. For about 450 filters, a fixed list of edge cases plus random combinations of comparisons over rows with NULL, NaN, infinities, -0.0, extreme integers, non-BMP strings, U+FFFD, high-byte binary values, and null structs and fields, every row for which Spark finds the filter true must be in the domains. The filters with empty
INlists are also checked withspark.sql.legacy.nullInEmptyListBehavior.- The domains of an
INlist of 100,000 values, and of itsNOT IN, combined with a range of the same column: they take a fraction of a second, within a limit of 20 seconds.NativeDataSourceSuite, end to end with the C++ test library:- The test library uses the domain of
idto skip blocks of rows, and records the domains that it gets.- Checks the domains of ranges, of other columns, unused domains, NaN,
LIKE 'n1%', a nested field, timestamps and an empty domain, domains with null (NOT (id <=> 5),name IS NULL), and domains of several ranges (id NOT IN (5, 20), and anORwhose two ranges make the library skip blocks).- Checks that filters on functions are not pushed, that a collated column gets no domain, also for a library that uses all the domains, a read-only library, and the configuration turned off.
- A library built against a header without
push_domains: Spark must not call it, although it is set in the table past its end.- The existing layout test covers the offsets of
SparkDsDomain.ColumnarDataSourceSuite: the same plumbing with a JVM data source, including a filter whose domain makes the data source read a row that only Spark's evaluation of a pushed predicate drops.Was this patch authored or co-authored using generative AI tooling?
Yes.
This pull request and its description were written by Isaac.