spark-test commented on code in PR #60147:
URL: https://github.com/apache/spark/pull/60147#discussion_r4505158644


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/V2ScanRelationPushDown.scala:
##########
@@ -147,6 +147,9 @@ object V2ScanRelationPushDown extends Rule[LogicalPlan] 
with PredicateHelper {
       // future use in constraint propagation, and are read by a Spark-side 
scan merge (see
       // TableCapability.SCAN_MERGING) to compare and re-enforce a scan's 
filters.
       val postScanFilterSet = ExpressionSet(postScanFiltersWithoutSubquery)
+      sHolder.postScanFilterExpressions = normalizedFiltersWithoutSubquery

Review Comment:
   **Nit (P3):** Intersecting the returned residuals with the received 
conjuncts here is what keeps a residual the builder derived or rewrote, and 
therefore never received, out of the removal candidates. No test fails if that 
intersection is lost:
   
   - `InMemoryCatalystFilterScanBuilder.pushFilters` returns `filters` verbatim.
   - `CatalystFilterScanBuilder` returns `filters` or `Nil`.
   - The strategy tests set `filterRemovalCandidates` by hand.
   
   If this were simplified to record the returned expressions, a residual over 
declared fields that the builder derived or rewrote would be recorded too. The 
source never received it and is not obliged to enforce it, yet it would be 
omitted from `FilterExec` once an inferred filter survives, and rows failing it 
would be returned with every test still passing.
   
   Suggest a planner test whose guarantee-table builder returns both an 
unchanged residual and a derived one. It should check that the derived residual 
stays in `FilterExec` while the unchanged one is omitted.
   
   **Verification:**
   - **Regression:** If pushdown records the builder's returned expressions 
instead of only the received conjuncts it returned, the new test fails, because 
the derived residual disappears from FilterExec.
   - **Behavior:** With the current recording rule the test passes, and the 
unchanged residual over a declared field is omitted.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/connector/SupportsCatalystFilterGuarantees.scala:
##########
@@ -0,0 +1,43 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.internal.connector
+
+import org.apache.spark.sql.connector.catalog.Table
+import org.apache.spark.sql.connector.expressions.NamedReference
+
+/** A table that declares when its scans fully evaluate Catalyst predicates. */
+trait SupportsCatalystFilterGuarantees extends Table {
+
+  /**
+   * Returns attributes for which this table's scans fully evaluate Catalyst 
filters.
+   *
+   * For scans reporting inferred filters, Spark may omit static conjuncts 
over these attributes
+   * that are unchanged from returned residuals or adjustment predicates 
recorded during pushdown.
+   * Eligible conjuncts must be deterministic and contain no subqueries or 
Python UDFs. The source
+   * must fully enforce the query filters it receives over these attributes, 
including residuals
+   * returned to Spark, and reflect their enforcement in scan equality for 
scan reuse.

Review Comment:
   **Nit (P3):** Once the `FilterExec` is omitted, nothing in the physical plan 
records these conjuncts, so source equality alone keeps differently filtered 
reads apart when Spark reuses an exchange. The equality Spark compares there is 
not the `Scan`'s:
   
   - `BatchScanExec.equals` and `hashCode` compare `batch`, the `Batch` 
returned by `scan.toBatch`, plus fields Spark adds such as runtime and storage 
filters.
   - A V1-fallback `RowDataSourceScanExec` compares the relation built by 
`toV1TableScan`.
   
   Take a connector whose `toBatch` returns a separate `Batch` whose equality 
covers only the read schema and pushed predicates. It can follow this sentence, 
reflect the residuals it enforces only in `Scan.equals`, and still have `SELECT 
i, j, count(*) FROM t WHERE i > 7 GROUP BY i, j UNION ALL SELECT i, j, count(*) 
FROM t GROUP BY i, j` served from one read, returning wrong rows. On the base 
branch, the residual or adjustment `FilterExec` kept the two branches apart. 
Where `toBatch` returns the scan itself, as `FileScan` does, the wording is 
accurate. Logical subplan merging is also already protected, by the candidates 
in the scan relation's canonical form. The `pushFilters` doc has the same 
sentence.
   
   The PR's own guarantee source cannot catch this either: 
`GuaranteedCatalystFilterDataSourceV2` builds `CatalystFilterScanBuilder`, 
whose inherited `SimpleScanBuilder.equals` compares only `readSchema()`.
   
   Suggest naming, in both docs, the `Batch` returned by `Scan.toBatch` and, 
for V1-fallback scans, the relation returned by `toV1TableScan`. Also make the 
guarantee test source include the filters it received in that equality, and add 
an end-to-end test that reads the table twice with different filters.
   
   **Verification:**
   - **Inspection:** The trait and pushFilters documentation name what must 
reflect enforced filters for scan reuse: equality of the Batch returned by 
Scan.toBatch, and of the V1 relation for V1-fallback scans.
   - **Regression:** A query that combines a filtered and an unfiltered 
aggregate over the guarantee test source returns the same rows with exchange 
reuse enabled and disabled. With reuse enabled, its executed plan does not 
reuse one branch's exchange for the other.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/execution/datasources/v2/DataSourceV2Relation.scala:
##########
@@ -215,6 +221,37 @@ case class DataSourceV2ScanRelation(
   // skip adding IsNotNull when the scan already implies it, or infer new 
filters across
   // joins), so plan stability testing is needed first.
 
+  /** Resolved table fields whose static Catalyst filters the source fully 
evaluates. */
+  lazy val fullyPushedFilterAttrs: ExpressionSet = relation.table match {
+    case table: SupportsCatalystFilterGuarantees =>
+      val refs = table.fullyPushedFilterAttributes().toImmutableArraySeq
+      val tableSchema = fromAttributes(relation.output)

Review Comment:
   **Nit (P3):** `relation.output` includes the table's metadata columns only 
after `AddMetadataColumns` calls `withMetadataColumns()`, which it does only 
for a query that references a metadata column. `removeFullyPushedFilters` 
forces this validation for every batch, V1-fallback and local scan, before its 
inference gate.
   
   Take a table that implements `SupportsMetadataColumns` and 
`SupportsCatalystFilterGuarantees` and declares `_partition`, a metadata column 
it enforces exactly. The trait admits top-level columns and does not exclude 
metadata columns. Then:
   
   - `SELECT id FROM t WHERE id > 1` fails with 
`DATA_SOURCE_INVALID_FULLY_PUSHED_FILTER_ATTRIBUTE`, even when the scan reports 
no inferred filters and nothing could be omitted. The error's `<tableSchema>` 
omits `_partition`, so it does not explain the failure.
   - `SELECT id FROM t WHERE _partition = 'p1'` passes with the same 
declaration.
   
   So whether a fixed declaration is valid depends on the query, although the 
PR states that invalid declarations fail consistently. Suggest validating 
against the relation's full column set (its output plus the `metadataOutput` 
columns it does not expose yet), rendering that schema in the error, and 
stating on the trait that metadata columns may be declared. A declared metadata 
column that a query does not read is then ignored like any pruned field.
   
   **Verification:**
   - **Behavior:** Take a table that implements the guarantee trait, exposes 
metadata columns and declares one of them. A batch query on it that references 
no metadata column plans and runs without error, both with and without inferred 
filters.
   - **Regression:** A query on the same table that filters on the declared 
metadata column still passes validation. When the scan reports inferred 
filters, the eligible conjunct over that column is omitted.
   - **Compatibility:** A declared name that is neither a data column nor a 
metadata column still fails with the connector-specific error, whether or not 
the query references metadata columns.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to