dongjoon-hyun commented on code in PR #60447:
URL: https://github.com/apache/spark/pull/60447#discussion_r4565831379


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/BatchScanExec.scala:
##########
@@ -69,7 +68,17 @@ case class BatchScanExec(
   private def scanOutput: Seq[AttributeReference] =
     if (appendsCheckedColumn) output.init else output
 
-  override def scan: Scan = if (plannedScan == null) null else plannedScan.scan
+  // What this node plans from `scan`, see [[PlannedScan]]. It is kept in a 
tag, set when the node
+  // first asks for its `Batch` or partitions. `makeCopy`, `clone` and the 
tree transforms carry the
+  // tag over to the copies made after that, so they share it. A copy over 
another `Scan`, and one
+  // the case-class `copy` makes, plan their own.
+  private def plannedScan: PlannedScan = synchronized {
+    getTagValue(PlannedScan.TAG).filter(_.scan eq scan).getOrElse {
+      val planned = new PlannedScan(scan)
+      setTagValue(PlannedScan.TAG, planned)

Review Comment:
   **[1] `equals` tags a fresh copy before `transformDown` copies the 
original's tags, so the copy loses all of them.**
   
   `equals` and `hashCode` reach this line through `batch`, so comparing a node 
that has no tag yet installs a new `PlannedScan` on it. 
`TreeNode.transformDownWithPruning` compares the rule's result with the 
original before it carries the tags over:
   
   ```scala
   if (this fastEquals afterRule) {
     ...
   } else {
     afterRule.copyTagsFrom(this) // copies only into a node that has no tags
   ```
   
   Take a rule `plan.transform { case b: BatchScanExec => b.copy(runtimeFilters 
= newFilters) }`:
   
   1. `fastEquals` calls `BatchScanExec.equals`. Its `other.batch` installs a 
new `PlannedScan` on the copy and calls `scan.toBatch` again.
   2. The runtime filters differ, so the nodes are not equal and 
`afterRule.copyTagsFrom(this)` runs. The copy already has a tag, so nothing is 
copied.
   
   The copy then:
   - has none of the original's tags, including the logical link. In 4.3.0, 
where `batch` is a lazy val of the node, the same rule keeps them.
   - plans its partitions again from the `Scan`. If a DPP build side has pruned 
the shared `Scan` by then, this is the SPARK-60752 failure again.
   
   So "the tree transforms carry it over" holds for `transformUp`, but not for 
`transform`, which most rules use. No rule in Spark rebuilds the node this way 
today, so this affects extensions and tests. Keeping `equals` and `hashCode` 
from installing the tag on a node that has none would avoid it. [4] has a test 
that shows it.



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/KeyGroupedPartitioningSuite.scala:
##########
@@ -2616,12 +2616,11 @@ class KeyGroupedPartitioningSuite
           }
         }
         try {
-          // A new `PlannedScan` makes the copy plan the connector's 
replacement partitions, and a
-          // rewritten runtime filter makes it distinct for tree replacement, 
while the true literal
-          // leaves those partitions unchanged.
+          // A case-class copy plans the connector's replacement partitions, 
and a rewritten runtime
+          // filter makes it distinct for tree replacement, while the true 
literal leaves those
+          // partitions unchanged.
           inMemoryScan.data = newData
-          val rebuilt = leftScan.copy(plannedScan = new 
PlannedScan(leftScan.scan),
-            runtimeFilters = Seq(Literal.TrueLiteral))
+          val rebuilt = leftScan.copy(runtimeFilters = 
Seq(Literal.TrueLiteral))
           assert(rebuilt.outputPartitioning.numPartitions == 
replacementKeys.size)

Review Comment:
   **[3] The test plans the replacement partitions only because these 
assertions ask first.**
   
   `rebuilt` gets its own `PlannedScan` because L2624-L2625 ask for 
`outputPartitioning` before the `transformUp` at L2627. Without them, `rebuilt` 
has no tags when the transform returns it, so `newNode.copyTagsFrom(leftScan)` 
hands it the original `PlannedScan`. It then reads the old `[1, 2]` partitions 
instead of `newData`. The `Seq(2, 3)` and `Seq(1, 2, 3)` runs then fail, for a 
reason unrelated to the guard the test checks.
   
   Could the comment above say that the copy has to plan before the transform? 
Or could the test force it explicitly, for example with 
`rebuilt.inputPartitions`, rather than through an assertion?



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/SparkPlanSuite.scala:
##########
@@ -333,17 +333,22 @@ class SparkPlanSuite extends SharedSparkSession {
           throw new UnsupportedOperationException()
       }
     }
-    val scan = BatchScanExec(Seq.empty, new PlannedScan(new NewBatchScan), 
Seq.empty, table = null)
+    val scan = BatchScanExec(Seq.empty, new NewBatchScan, Seq.empty, table = 
null)
     def sharesPlanning(copy: SparkPlan): Boolean = copy match {
       case c: BatchScanExec =>
         (c.batch eq scan.batch) && (c.inputPartitions eq scan.inputPartitions)
       case _ => false
     }
+    val args = scan.productIterator.map(_.asInstanceOf[AnyRef]).toArray
+    // The node plans first, as in `EnsureRequirements`, and later rules copy 
it.
+    scan.inputPartitions
 
-    // Copies through `makeCopy`, `clone` or `copy` share what the node 
planned.
-    
assert(sharesPlanning(scan.makeCopy(scan.productIterator.map(_.asInstanceOf[AnyRef]).toArray)))
+    // Copies through `makeCopy` or `clone` share what the node planned, but 
not over another
+    // `Scan`. So does the canonical form, whose `equals` compares the planned 
`Batch`.
+    assert(sharesPlanning(scan.makeCopy(args)))
     assert(sharesPlanning(scan.clone()))
-    assert(sharesPlanning(scan.copy(runtimeFilters = Nil)))
+    assert(!sharesPlanning(scan.makeCopy(args.updated(1, new NewBatchScan))))
+    assert(sharesPlanning(scan.canonicalized))

Review Comment:
   **[4] The test covers neither `copy` nor the transforms.**
   
   The description names two more cases: a case-class `copy` plans its own, and 
the tree transforms carry the tag over. The test checks neither, and the `copy` 
assertion was removed without its negative. Something like this would pin both. 
The last line fails today ([1]):
   
   ```scala
   val rule: PartialFunction[SparkPlan, SparkPlan] = {
     case b: BatchScanExec => b.copy(runtimeFilters = Seq(Literal.TrueLiteral))
   }
   assert(!sharesPlanning(scan.copy(runtimeFilters = Nil)))
   assert(sharesPlanning(scan.transformUp(rule)))
   assert(sharesPlanning(scan.transform(rule)))
   ```
   
   Setting a logical link on `scan` first and checking it on both results would 
also catch the lost tags.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/BatchScanExec.scala:
##########
@@ -192,22 +204,19 @@ case class BatchScanExec(
 
 /**
  * A `Scan`, with the `Batch` and the input partitions a [[BatchScanExec]] 
plans from it once, when
- * a node first asks for them. The copies later rules make of the node share 
it, so they read the
- * partitions the first node planned, with a reader factory from the `Batch` 
that planned them.
- * The partitions have to be the planned ones, because the `Scan` can be 
shared with another node
- * whose runtime filter prunes it first, e.g. the build side of a DPP subquery 
(SPARK-60752). A
- * runtime filter replans them, through 
`planInputPartitionsWithRuntimeFilters` or from a new
- * `Batch` after a pushed `filter`, but keeps the planned `Batch`'s reader 
factory.
- *
- * A rule that rebuilds a node over the same `Scan` passes on its 
`plannedScan`, or uses `copy`. A
- * new `PlannedScan` is for a node that is planned again, or one over another 
`Scan`.
+ * a node first asks for them. The node keeps it in a tag, so the copies later 
rules make of it

Review Comment:
   **[5] The guidance for a rule that rebuilds the node is gone.**
   
   This replaces "A rule that rebuilds a node over the same `Scan` passes on 
its `plannedScan`, or uses `copy`", which #60030 added for [this 
comment](https://github.com/apache/spark/pull/60030#discussion_r4462999322). 
Now `copy` plans again and the tag is private, so a rule outside this package 
has no documented way to keep the planned partitions. A rule that runs after 
`EnsureRequirements` and rebuilds a keyed scan with `copy` hits SPARK-60752 
again.
   
   As far as I can see, the ways that work are `makeCopy`, or `copy` followed 
by `copyTagsFrom(node)` before anything asks the copy or sets a tag on it. 
Could the doc say which one to use?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/BatchScanExec.scala:
##########
@@ -69,7 +68,17 @@ case class BatchScanExec(
   private def scanOutput: Seq[AttributeReference] =
     if (appendsCheckedColumn) output.init else output
 
-  override def scan: Scan = if (plannedScan == null) null else plannedScan.scan
+  // What this node plans from `scan`, see [[PlannedScan]]. It is kept in a 
tag, set when the node
+  // first asks for its `Batch` or partitions. `makeCopy`, `clone` and the 
tree transforms carry the
+  // tag over to the copies made after that, so they share it. A copy over 
another `Scan`, and one
+  // the case-class `copy` makes, plan their own.
+  private def plannedScan: PlannedScan = synchronized {

Review Comment:
   **[6] Nit: a `lazy val` would do, as in `FileSourceScanExec`.**
   
   `FileSourceScanExec.supportsColumnar` (SPARK-61574), which the description 
cites, reads or sets its tag once in a `lazy val`. Here `plannedScan` is a 
`def` that takes the node's lock and looks up the tag on every `batch`, 
`inputPartitions` and `readerFactory` call. That is three times per `equals`, 
and several times per `supportsColumnar` in `PARTITION_DEFINED` mode.
   
   A `@transient private lazy val` gets the same synchronization from the lazy 
val. It also pins the `PlannedScan` to the instance, so `inputPartitions` stays 
stable for the instance even if the tag changes later, as 
`DataSourceV2ScanExecBase.scala:63` asks.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/BatchScanExec.scala:
##########
@@ -69,7 +68,17 @@ case class BatchScanExec(
   private def scanOutput: Seq[AttributeReference] =
     if (appendsCheckedColumn) output.init else output
 
-  override def scan: Scan = if (plannedScan == null) null else plannedScan.scan
+  // What this node plans from `scan`, see [[PlannedScan]]. It is kept in a 
tag, set when the node
+  // first asks for its `Batch` or partitions. `makeCopy`, `clone` and the 
tree transforms carry the
+  // tag over to the copies made after that, so they share it. A copy over 
another `Scan`, and one
+  // the case-class `copy` makes, plan their own.

Review Comment:
   **[2] Whether a case-class `copy` plans its own partitions depends on the 
transform and on call order.**
   
   This says that a copy made by the case-class `copy` plans its own. That 
holds for a bare `copy`, but inside a transform it depends:
   - `transformUp`, `transformUpWithBeforeAndAfterRuleOnChildren` and 
`transformDownWithReferenceEquality` run `copyTagsFrom(this)` without comparing 
first. A copy that nothing has asked yet takes the original's `PlannedScan` and 
reads the partitions the original planned.
   - `transform` compares first, so the copy plans its own and loses the other 
tags ([1]).
   - If anything asks the copy before the transform returns it, such as 
`outputPartitioning`, `supportsColumnar` or a hash lookup, it plans its own 
under `transformUp` too.
   
   Also, copies that `makeCopy` or `clone` make before the node first asks get 
no tag, so they do not share with each other, unlike the field in #60030. I 
could not find such a pair among Spark's own rules, since a keyed scan plans in 
`EnsureRequirements` before the copies that matter. Still, "Queries behave as 
with #60030" depends on that order.
   
   Could the comment state the rule as it is (a node shares when it gets the 
tag through `makeCopy`, `clone` or a transform before anything asks it), or 
could the behavior be made independent of the transform?



-- 
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