Repository navigation
[SPARK-60448][SQL] Apply filter conditions on a storage filter's key columns in the Parquet reader - #59486
[SPARK-60448][SQL] Apply filter conditions on a storage filter's key columns in the Parquet reader#59486ForVic wants to merge 2 commits into
Conversation
a9b7065 to
f6e1c49
Compare
|
cc @peter-toth, this implements one of the follow-ups listed in #58895 Also cc @dongjoon-hyun @cloud-fan, who reviewed #58895 |
cloud-fan
left a comment
There was a problem hiding this comment.
Review summary
The review found no correctness problem in how the reader now combines the bloom with the new key conjuncts. If(blooms, keyConjuncts, false) keeps exactly the rows an And would. The post-scan skip trusts only rows the whole predicate accepted. IsNotNull stays bare, so FilterExec nullability is unchanged.
All four findings are P3 and concern coverage and documentation:
- The new tests do not cover a conjunct over both the key and another column.
- No test has several key conjuncts that each reject bloom-kept rows.
- The internal
FileFormatreader doc does not say how a reader finds the key conjuncts instorageFilters. - A test-helper comment still describes a bloom holding a single key.
One question for the author follows, about which key conjuncts the reader should accept.
Cross-cutting observations
- The new tests leave two rules of the key-conjunct offer unpinned, although the post-scan Filter skips every offered conjunct on rows the reader marks checked and so relies on both. No test plans a conjunct that references a non-key column alongside the key, and the only test with two key conjuncts has no bloom-kept row that either one rejects, so nothing checks that the reader enforces all of them together.
Separation: The two rules live in different components, the planner's eligibility check and the reader's predicate construction, and each test addition closes only its own gap, so the shared context does not create a common repair owner or change either repair's scope.
Findings
4 total: 0 P0, 0 P1, 0 P2, 4 P3.
Nit (P3)
- Test helper comment still says the bloom holds one key —
sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/parquet/ParquetStorageFilterSuite.scala:559-561— see inline. - Reader doc does not say how to find the key conjuncts in storageFilters —
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/FileFormat.scala:235— see inline. - Planner test lacks a conjunct over both the key and another column —
sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/parquet/ParquetStorageFilterSuite.scala:2299— see inline. - No test checks that several key conjuncts are all enforced —
sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/parquet/ParquetStorageFilterSuite.scala:2350— see inline.
Decision challenges
Should the reader accept expensive key-only conjuncts such as UDFs and regexes?
isSupportedFilterOnKeys accepts any key-only conjunct that has no subquery and no unevaluable node. So ScalaUDFs, Hive UDFs, LIKE/RLIKE, regexp_extract/regexp_replace, from_json and Invoke-based expressions over the bloom's key are now offered. They run in phase 1 on every bloom-kept row, before any conjunct on another column. Before this PR, the reader evaluated only XxHash64 of a key that InjectRuntimeFilter had already restricted to cheap expressions; its isSimpleExpression rejects exactly those UDF, regex, JSON and Invoke patterns. The post-scan Filter then ran the remaining conjuncts in plan order.
Take a bloom on f.k with WHERE f.status = 'active' AND my_udf(f.k). The UDF used to run only on active bloom-kept rows. Now it runs on all bloom-kept rows, so its cost grows by the inverse selectivity of status = 'active'. When the scan gets no checked column (whole-stage codegen off, or more output fields than spark.sql.codegen.maxFields), the post-scan Filter evaluates the UDF again on the survivors. Fatal errors change too. rethrowIfMustPropagate rethrows them rather than falling back, so a regex StackOverflowError on a row that another conjunct would have dropped first now fails the task. Spark promises no conjunct evaluation order, so none of this changes answers. Still, the extension has no switch of its own, so the only way to avoid it is to turn off the whole feature.
The benchmark uses only k % 50 = 0. That is the case where the description's "the only extra cost is checking one more condition on each row the bloom filter kept" holds. Should isSupportedFilterOnKeys reuse the runtime-filter injector's cheap-expression exclusions, or add another cost guard or an internal sub-conf? Or are the reordering cost and the error exposure for expensive key conjuncts intended?
There was a problem hiding this comment.
Thanks for the PR, @ForVic!
This hands the Parquet reader the scan's other conjuncts over a runtime bloom's key columns. The reader evaluates them under an If on the bloom, so they run only on the rows the bloom keeps. The post-scan Filter then skips them on the rows the reader marks as checked. It is one of the follow-ups #58895 lists, and it adds no column to the read.
The new tests fail without the change, and every path I traced returns the right rows. What is open is that these conjuncts are arbitrary expressions, which the reader now runs ahead of the query's other conditions. The bloom alone never did that, and findings 1 and 2 come from it.
Blocking
- 1. A fatal error in a key conjunct fails a query the plain plan answers: a regex or a UDF that fails fatally on a row another condition drops now takes the task and its JVM down. Which expressions can do that is hard to list, so I'd put the key conjuncts behind their own conf, off by default, and keep the bloom alone under the existing one. inline:
ParquetStorageFilter.scala:233
Non-blocking
- 2. Evaluated twice where the scan gets no checked column: with whole-stage codegen off, or too many fields, the
Filterevaluates the key conjuncts again on every row the reader returns. inline:FileSourceStrategy.scala:212 - 3.
IsNotNullcould go to the reader too: null keys pass the bloom when its build side has one, and offering it while keeping it bare after the scan would drop them in phase 1. inline:FileSourceStrategy.scala:210 - 4. The promised fallback has no test: no test has a key conjunct throw on a row the bloom keeps. inline:
ParquetStorageFilterSuite.scala:2343
Minor
- 5.
create's scaladoc still says "combined with AND". inline:ParquetStorageFilter.scala:146 - 6.
create'srequiremessages now name the filterif. inline:ParquetStorageFilter.scala:150 - 7.
bloomLiteralOf's comment still says "one long key". inline:ParquetStorageFilterSuite.scala:559 - 8. Scalar subqueries could be offered too (optional, fine as a follow-up). inline:
ParquetStorageFilter.scala:234
|
Thanks @cloud-fan and @peter-toth for the reviews. I've addressed them in 07d5f8d. @cloud-fan, on whether the reader should accept expensive key-only conjuncts such as UDFs and regexes: I went with Peter's suggestion. They're now behind their own conf, |
There was a problem hiding this comment.
Re-checked through 07d5f8d. Findings 1-3 and 5-7 are resolved, 8 moved to SPARK-60500, and nothing regressed. Finding 4 is still open, because the new fallback test passes without a fallback. The suite passes at the head (140 tests). Turning the If back into an And fails the ANSI test, and wrapping IsNotNull fails the planner test. What's left is mostly about the IsNotNull and fallback paths this push added.
Non-blocking
- 4. The fallback test passes without a fallback (round 1): with only
IsNotNulloffered, the throwing conjunct never reaches the reader, and the test still passes. Counting the give-up withwithLogged(evaluationGivenUp)tells the two apart. inline - 9. Key conditions run before the offered
IsNotNull(new): the reader evaluates them in conjunct order, whileFilterExecchecksIsNotNullfirst. So a condition that throws on null sees the null keys. In a probe every row group was given up (0 of 999 rows excluded), and movingIsNotNullfirst excludes all 999. inline
Minor
- 10.
buildReaderWithStorageFilters's contract is stale (new): it says a reader must not fail the query, and that every storage filter becomesIF(checked, true, filter). A key condition's fatal error now fails the query, andIsNotNullstays bare. inline - 11. The description says the existing conf's doc "no longer mentions these conditions" (new): against master that doc is unchanged. The sentence describes the previous revision, and it would end up in the commit message.
- 12. The LEFT OUTER test's bare-
IsNotNullcheck passes on the other side's Filter (new):bf2's ownisnotnull(v)satisfies it, so it stays green with theIsNotNullexception removed. inline - 13. The new conf's doc names a conf as the exception (new): "with the exceptions of spark.sql.parquet.storageFilterPushdown.enabled and one more". inline
- 14.
checkedColumnandmarksCheckedare now built for every file scan (new): before this push they were built only when a scan had storage filters. inline
…uet reader When a scan is offered a storage filter, also offer the other conjuncts that reference only its key columns. The reader reads those columns anyway, so they narrow the surviving rows at no extra read.
07d5f8d to
d67c52a
Compare
|
Thanks @peter-toth for the thorough re-check! I've addressed all the remaining findings and updated the description. I also rebased onto master to pick up SPARK-60465, so the PR now uses |
There was a problem hiding this comment.
Re-checked through d67c52a. Findings 4 and 9-14 are resolved, and nothing regressed. The suite passes at the head (150 tests). Each of these fails a test: dropping the IsNotNull ordering, an And instead of the If, offering only IsNotNull, and wrapping IsNotNull after the scan. What's left is small. Finding 15 is a gap in the sort I suggested for finding 9.
Non-blocking
- 15. The
IsNotNull-first sort also moves anIsNotNullover an expression (new):FilterExechoists only one over a column. So under ANSI,k <> 0 AND isnotnull(100 % k)makes the reader give up the row group holdingk = 0(900 of 999 rows excluded). Sorting onlyIsNotNull(_: BoundReference)first excludes 999. inline - 16.
readKeysUnder's guard is met by the inferredisnotnull(k)(late catch): with onlyIsNotNulloffered, theIftest and theIsNotNull-order test still pass. Asserting that every key-only conjunct of the condition is offered fails both. inline - 17. The new conf's doc says a fatal error "fails the query" (late catch): it also exits the executor, as finding 1's probe showed, and each retry does the same. inline
- 18. The key-condition selection repeats
offeredConjuncts(late catch): it skips that helper'sdeterministiccheck and builds a secondExpressionSet. CallingofferedConjunctswith the blooms' key columns is a drop-in, and the suite passes with it (150 tests). inline
Alternatives
- 19. Offer only the key conditions the
Filterevaluates before any condition on another column (late catch): the reader then evaluates a key condition only on rows the plain plan evaluates it on, so its errors are the plain plan's errors. The fatal-error exception in the conf's doc goes, and with it finding 17. A prototype keeps the PR's motivating cases, and 149 of 150 tests pass. inline
Minor
- 20. The conf's doc omits the field-count limit (late catch): the checked column is also left out when the output has too many fields for whole-stage codegen, and then only the bloom is offered. inline
| // `IsNotNull` first, as `FilterExec` checks it before the conjuncts over its column, so a | ||
| // conjunct that throws on null never sees the null keys the blooms keep. | ||
| val onKeys = conditions.sortBy(e => if (e.isInstanceOf[IsNotNull]) 0 else 1) |
There was a problem hiding this comment.
Finding 15. The sort I suggested for finding 9 is too broad. FilterExec hoists only an IsNotNull over a column:
splitNotNullPredstakesIsNotNull(a)only for a null-intoleranta(basicPhysicalOperators.scala:163). One over another expression, such as a UDF, stays in plan order.- It checks one over a null-intolerant expression only before a conjunct that contains the expression (
nestedNullChecks, L370), or else after all the others (L388).
This sort moves every IsNotNull first. So the reader can evaluate an expression the plain plan never evaluates on that row.
I ran this on this head with readKeysUnder, under ANSI, with a bloom holding 0 and 42 and the condition k <> 0 AND isnotnull(100 % k):
- At the head, the rows equal a plain read's (
[42]). But the reader computes100 % 0, gives up the row group holdingk = 0(oneevaluationGivenUplogged), and excludes 900 rows instead of 999. - With the change below, it gives nothing up and excludes 999. The key-condition tests still pass.
A fatal error inside such an IsNotNull, for example a UDF that overflows the stack, would fail the query instead. The condition that guards it is on the same column there, so this falls outside the one exception the new conf's doc lists.
| // `IsNotNull` first, as `FilterExec` checks it before the conjuncts over its column, so a | |
| // conjunct that throws on null never sees the null keys the blooms keep. | |
| val onKeys = conditions.sortBy(e => if (e.isInstanceOf[IsNotNull]) 0 else 1) | |
| // An `IsNotNull` over a key column first, as `FilterExec` checks one before the conjuncts | |
| // over its column, so a conjunct that throws on null never sees the null keys the blooms | |
| // keep. One over an expression keeps its place, since `FilterExec` checks it only before a | |
| // conjunct that contains the expression, or after the others. | |
| val onKeys = conditions.sortBy { | |
| case IsNotNull(_: BoundReference) => 0 | |
| case _ => 1 | |
| } |
The description's "IS NOT NULL goes first among them, as FilterExec checks it first" would then say "an IS NOT NULL on the key".
| assert(scanOf(plan).storageFilters.length > 1, | ||
| s"the key conjuncts must be offered with the bloom.\nPlan:\n$plan") |
There was a problem hiding this comment.
Finding 16. This is met by the isnotnull(k) that the optimizer infers from any null-intolerant condition on k, as noted under finding 4. The fallback test now counts its give-up. But two others still pass when the conjunct they test never reaches the reader. With supportsStorageFilterOnKeys patched to accept only IsNotNull:
a conjunct over the key columns is evaluated only on the rows the bloom keepspasses. Its bloom holds only 42, so it excludes 999 rows on its own.an IsNotNull over the key columns is evaluated before the other conjuncts over thempasses.assert_not_null(k) > 0is never evaluated, so nothing is given up.
Asserting that every key-only conjunct of the condition is offered fails both under that patch, and all six tests that use the helper pass at the head:
| assert(scanOf(plan).storageFilters.length > 1, | |
| s"the key conjuncts must be offered with the bloom.\nPlan:\n$plan") | |
| val k = columnOf(relation, "k") | |
| val offered = scanOf(plan).storageFilters | |
| val onKey = splitConjunctivePredicates(filtered.condition) | |
| .filter(_.references.forall(_.semanticEquals(k))) | |
| assert(onKey.forall(c => offered.exists(_.semanticEquals(c))), | |
| s"every conjunct over the key must be offered; got $offered.\nPlan:\n$plan") |
| "fatal error, such as a regular expression or a UDF overflowing the stack, on a row that " + | ||
| "a condition on another column would have dropped first fails the query.") |
There was a problem hiding this comment.
Finding 17. A fatal error does more than fail the query. The task's Executor.isFatalError check hands it to SparkUncaughtExceptionHandler, which calls System.exit. Finding 1's probe saw exactly that: the regex overflowed the stack and took the JVM down with the task. Each retry takes down the executor it runs on. So the stage aborts only after spark.task.maxFailures attempts, each costing an executor. That is the case worth warning about:
| "fatal error, such as a regular expression or a UDF overflowing the stack, on a row that " + | |
| "a condition on another column would have dropped first fails the query.") | |
| "fatal error, such as a regular expression or a UDF overflowing the stack, on a row that " + | |
| "a condition on another column would have dropped first exits the executor. The query " + | |
| "fails once the task's retries have done the same.") |
The description's "If the error is fatal, ... the query fails" would say the same.
| val onKeys = ExpressionSet(normalizedFilters).toSeq.filter { expr => | ||
| val refs = expr.references | ||
| refs.nonEmpty && refs.subsetOf(storageKeyAttrs) && !offered.contains(expr) && | ||
| fsRelation.fileFormat.supportsStorageFilterOnKeys(sparkSession, expr) | ||
| } |
There was a problem hiding this comment.
Finding 18. This repeats the per-conjunct filter of StorageFilterPlanning.offeredConjuncts (StorageFilterPlanning.scala:43), minus its expr.deterministic check. That check is the one whose reason is "the post-scan Filter takes the reader's word on the rows it checked". It holds here only because apply passes filters.filter(_.deterministic). This also builds a second ExpressionSet of normalizedFilters, and it excludes the blooms with a structural Seq.contains. The rebase note says the PR now uses StorageFilterPlanning instead of its own copies, and this is the one copy left.
The helper can take the blooms' key columns as its key candidates. Passing dataAttrs as its read columns keeps its "nothing if they cover every read column" check a no-op here, since the blooms already don't cover them. The whole suite passes with this change (150 tests):
| val onKeys = ExpressionSet(normalizedFilters).toSeq.filter { expr => | |
| val refs = expr.references | |
| refs.nonEmpty && refs.subsetOf(storageKeyAttrs) && !offered.contains(expr) && | |
| fsRelation.fileFormat.supportsStorageFilterOnKeys(sparkSession, expr) | |
| } | |
| val offeredSet = ExpressionSet(offered) | |
| val onKeys = StorageFilterPlanning.offeredConjuncts(normalizedFilters, storageKeyAttrs, | |
| dataAttrs, expr => !offeredSet.contains(expr) && | |
| fsRelation.fileFormat.supportsStorageFilterOnKeys(sparkSession, expr)) |
| sparkSession.sessionState.conf, offered, scanOutput) | ||
| if (checked.isEmpty) return (offered, None) | ||
| // A conjunct over the key columns alone adds no column to the read. | ||
| val storageKeyAttrs = AttributeSet.fromAttributeSets(offered.map(_.references)) |
There was a problem hiding this comment.
Finding 19. An alternative to the new conf's fatal-error exception, not a request to block on. The reader evaluates the key conditions ahead of the query's conditions on other columns. Findings 1, 15 and 17 all come from that reordering, and so does the exception in the conf's doc. Offering a key condition only when the post-scan Filter evaluates no conjunct over another column before it removes the reordering:
- The reader then evaluates a key condition only on rows that the plain plan evaluates it on too, after the same conditions. The blooms only narrow those rows.
- So an error the reader meets, fatal or not, the plain plan meets on the same row. Nothing is lost when the reader gives a row group up, since the query fails anyway. The doc's "one more" exception goes, and with it finding 17.
- An expensive condition no longer runs ahead of a cheaper one written before it.
What it gives up are key conditions written after a condition on another column. The PR's motivating cases keep theirs, since every condition on the fact side is on the key there, in the LEFT OUTER JOIN test and in the benchmark.
I prototyped it on this head. The rule is computed over normalizedFilters, whose order the post-scan Filter keeps. An IsNotNull does not count as a conjunct over another column, since FilterExec checks one only before a conjunct that reads its column:
val firstOther = normalizedFilters.indexWhere { e =>
!e.isInstanceOf[IsNotNull] && e.references.exists(a => dataAttrs.contains(a) &&
!storageKeyAttrs.contains(a))
}
val prefix = if (firstOther < 0) normalizedFilters else normalizedFilters.take(firstOther)
val onKeys = ExpressionSet(prefix).toSeq.filter { expr =>149 of the suite's 150 tests pass. The one that fails is a conjunct over the key columns that throws on a row the bloom keeps gives the row group up. Its key condition comes after v <> '0', so it is no longer offered, which is the point. That test would then assert that instead.
One case needs care. Once a conjunct that can be NULL is generated, FilterExec checks the IsNotNulls written before a later conjunct ahead of it, when that conjunct can raise (SPARK-60315). So an IsNotNull over another column, written before a key condition, can drop a row first there. Counting such an IsNotNull as a stop when the key condition can raise (ExprUtils.canEvaluateUnconditionally is false) would close that.
| "the reader also applies the query's other filter conditions that reference only the " + | ||
| "bloom filter's columns, on the rows the bloom filter keeps. They then run before the " + | ||
| "query's conditions on other columns. Only scans that return columnar batches with whole-" + | ||
| "stage codegen take them. The answer does not change, with the same exceptions as " + |
There was a problem hiding this comment.
Finding 20. StorageFilterPlanning.checkedColumn also leaves the checked column out when the output with it has too many fields for whole-stage codegen (isTooManyFields), and then only the bloom is offered. Parquet's supportBatch has no such limit, so a wide scan gets the bloom but not the key conditions. The description names that case, but the doc doesn't:
| "stage codegen take them. The answer does not change, with the same exceptions as " + | |
| "stage codegen, and few enough fields for it, take them. The answer does not change, " + | |
| "with the same exceptions as " + |
What changes were proposed in this pull request?
A follow-up to SPARK-59620.
With
spark.sql.parquet.storageFilterPushdown.enabledon, the Parquet reader first reads the join key column. It checks each row against the join's runtime bloom filter, and reads the other columns only for the rows that pass. Any other condition on that same key column, likek % 50 = 0, is still checked only after the scan. So the reader fetches the other columns for rows that get dropped right afterwards.This PR hands those conditions to the reader too. The reader already has the key column, so checking one more condition on it costs no extra I/O, and the rows it rejects never have their other columns read.
spark.sql.parquet.storageFilterPushdown.keyConditions.enabled, off by default. It takes effect only whenspark.sql.parquet.storageFilterPushdown.enabledis on too. With it off, only the bloom filter is handed to the reader, as before.FileFormat.supportsStorageFilterOnKeys(sparkSession, expr),falseby default. While the new conf is on, Parquet accepts any condition it can evaluate as it is, meaning no subqueries and no unevaluable expressions such as Python UDFs.FileSourceStrategypasses these conditions to the scan after the bloom filter, but only where the scan gets the column that marks the rows the reader checked. That column needs whole-stage codegen and not too many fields. Without it, the Filter after the scan would evaluate the conditions a second time.IS NOT NULLon the key is passed too. The Filter after the scan keeps it as it is, so it still marks the key column non-nullable.ParquetStorageFilterevaluates them under anIfon the bloom filter, so they only run on rows the bloom filter keeps. In a singleAndwith the bloom, subexpression elimination would compute what they share on every row.IS NOT NULLgoes first among them, asFilterExecchecks it first, so a condition that throws on null never sees the null keys the bloom filter keeps.Why are the changes needed?
It lets the reader skip more of the wide columns when the bloom filter alone keeps a lot of rows.
It doesn't help in the most common case, though. For an inner join, Spark already copies a condition like
k % 50 = 0to the other side of the join before it builds the bloom filter, so the bloom filter already leaves those keys out. The gain shows up when that doesn't happen, for example:Does this PR introduce any user-facing change?
Only when both
spark.sql.parquet.storageFilterPushdown.enabledand the newspark.sql.parquet.storageFilterPushdown.keyConditions.enabledare on. Both are off by default.StorageFiltersin the scan and are applied while reading.IS NOT NULL, which it keeps.How was this patch tested?
Eight tests in
ParquetStorageFilterSuite:IS NOT NULLafter the bloom filter, and the Filter keepsIS NOT NULLas it is. It doesn't offer a condition on another column, a condition over the key and another column, or anything without a bloom filter. It offers only the bloom filter with the new conf off or with whole-stage codegen off;If);IS NOT NULLdrops them in the reader;IS NOT NULLon the key is checked before a condition on the key that throws on null, so the reader doesn't fall back;IS NOT NULLto the reader. It returns the same rows as a plain read, while the reader drops more rows than the bloom filter alone can.ParquetStorageFilterSuitepasses (150 tests).Benchmark (code not included in this PR)
The benchmark scans a ~100 MB table with a bloom filter on
kplus the conditionk % 50 = 0. It compares three setups: the feature off, the feature on without this PR, and the feature on with this PR (withspark.sql.parquet.storageFilterPushdown.keyConditions.enabledon).longkey and a 2 kB value.longkey and eightlongvalues.Parquet reads whole pages, so a page is skipped only when none of its rows match. That's why this helps with wide rows in small pages, and does nothing when every page still has at least one match. When it doesn't help, the only extra cost is checking one more condition on each row the bloom filter kept, which is within noise here.
Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Code (Claude Opus 5.5)