Copilot commented on code in PR #12433:
URL: https://github.com/apache/gluten/pull/12433#discussion_r3520091902


##########
gluten-substrait/src/main/scala/org/apache/gluten/extension/ApplyStageInputStatsRule.scala:
##########
@@ -0,0 +1,129 @@
+/*
+ * 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.gluten.extension
+
+import org.apache.gluten.execution.WholeStageTransformContext
+import org.apache.gluten.substrait.rel.{InputIteratorRelNode, ReadRelNode, 
RelNode}
+
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
+import org.apache.spark.sql.execution.{CoalescedMapperPartitionSpec, 
CoalescedPartitionSpec, PartialMapperPartitionSpec, 
PartialReducerPartitionSpec, ShufflePartitionSpec}
+import org.apache.spark.sql.execution.adaptive.{BroadcastStats, InputStats, 
ScanInputStats, ShuffleStats}
+import org.apache.spark.sql.execution.datasources.LogicalRelation
+
+import scala.collection.{mutable, Seq}
+
+object ApplyStageInputStatsRule extends Logging {
+  def setStageInputStatsToInputNode(
+      ws: WholeStageTransformContext,
+      index: Int,
+      partitionLength: Int): Unit = {
+    val relNodesQueue: mutable.Queue[RelNode] = mutable.Queue()
+    val nodes = ws.root.getRelNodes
+    if (nodes != null) {
+      nodes.forEach(relNodesQueue.enqueue(_))
+    }
+    while (relNodesQueue.nonEmpty) {
+      val node = relNodesQueue.dequeue()
+      node match {
+        case input: InputIteratorRelNode =>
+          val stats = input.getInputStats
+          if (null != stats) {
+            val totalBytes = Math.max(stats.bytesByPartitionId.sum, 1)
+            val estimatedRowCount =
+              if (stats.inputStatsKind == BroadcastStats) {
+                stats.rowCount.toLong
+              } else {
+                (1.0d * stats.rowCount.toLong / totalBytes * 
stats.bytesByPartitionId(index)).toLong
+              }
+            logInfo(s"pass input stats idx: $index with estimated row count 
$estimatedRowCount")
+            input.setRowSize(estimatedRowCount)
+          }

Review Comment:
   `bytesByPartitionId(index)` can throw `ArrayIndexOutOfBoundsException` when 
the Spark partition index doesn’t align with the stats array length (e.g., AQE 
partitioning changes, empty stats, etc.). Also, logging once per task at INFO 
level can generate very large executor logs when this feature is enabled.



##########
gluten-substrait/src/main/scala/org/apache/gluten/extension/ApplyStageInputStatsRule.scala:
##########
@@ -0,0 +1,129 @@
+/*
+ * 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.gluten.extension
+
+import org.apache.gluten.execution.WholeStageTransformContext
+import org.apache.gluten.substrait.rel.{InputIteratorRelNode, ReadRelNode, 
RelNode}
+
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
+import org.apache.spark.sql.execution.{CoalescedMapperPartitionSpec, 
CoalescedPartitionSpec, PartialMapperPartitionSpec, 
PartialReducerPartitionSpec, ShufflePartitionSpec}
+import org.apache.spark.sql.execution.adaptive.{BroadcastStats, InputStats, 
ScanInputStats, ShuffleStats}
+import org.apache.spark.sql.execution.datasources.LogicalRelation
+
+import scala.collection.{mutable, Seq}
+
+object ApplyStageInputStatsRule extends Logging {
+  def setStageInputStatsToInputNode(
+      ws: WholeStageTransformContext,
+      index: Int,
+      partitionLength: Int): Unit = {
+    val relNodesQueue: mutable.Queue[RelNode] = mutable.Queue()
+    val nodes = ws.root.getRelNodes
+    if (nodes != null) {
+      nodes.forEach(relNodesQueue.enqueue(_))
+    }
+    while (relNodesQueue.nonEmpty) {
+      val node = relNodesQueue.dequeue()
+      node match {
+        case input: InputIteratorRelNode =>
+          val stats = input.getInputStats
+          if (null != stats) {
+            val totalBytes = Math.max(stats.bytesByPartitionId.sum, 1)
+            val estimatedRowCount =
+              if (stats.inputStatsKind == BroadcastStats) {
+                stats.rowCount.toLong
+              } else {
+                (1.0d * stats.rowCount.toLong / totalBytes * 
stats.bytesByPartitionId(index)).toLong
+              }
+            logInfo(s"pass input stats idx: $index with estimated row count 
$estimatedRowCount")
+            input.setRowSize(estimatedRowCount)
+          }

Review Comment:
   The PR description says these are “estimated row-size hints”, but the value 
assigned to `rowSize` is derived from (estimated) *row counts* per partition. 
If the native side interprets `rowSize` as bytes/row, this will be semantically 
wrong; either the hint should be renamed (e.g., `rowCountHint`) or the 
computation should be adjusted to pass bytes-per-row.



##########
gluten-substrait/src/main/scala/org/apache/spark/sql/execution/ColumnarCollapseTransformStages.scala:
##########
@@ -76,6 +77,36 @@ case class InputIteratorTransformer(child: SparkPlan) 
extends UnaryTransformSupp
     assert(child.isInstanceOf[ColumnarInputAdapter])
     val operatorId = context.nextOperatorId(nodeName)
     val readRel = RelBuilder.makeReadRelForInputIterator(child.output.asJava, 
context, operatorId)
+    if (GlutenConfig.get.enablePassStageInputStats) {
+      val inputStatsOpt: Option[InputStats] = {
+        val inputAdapter = child.asInstanceOf[ColumnarInputAdapter]
+        inputAdapter.child match {
+          case shuffle @ ShuffleStageWrapper(stats) =>

Review Comment:
   The new `enablePassStageInputStats` path in `InputIteratorTransformer` 
introduces additional behavior (extract stage stats, handle AQE shuffle 
partition specs, and mutate the produced `InputIteratorRelNode`). There are 
existing Gluten UT suites that exercise 
`ColumnarCollapseTransformStages`/`InputIteratorTransformer`, but none appear 
to cover this flag-enabled path; adding a focused unit/integration test would 
help prevent regressions (especially around AQE shuffle reads and broadcast 
stages).



##########
gluten-substrait/src/main/scala/org/apache/gluten/extension/ApplyStageInputStatsRule.scala:
##########
@@ -0,0 +1,129 @@
+/*
+ * 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.gluten.extension
+
+import org.apache.gluten.execution.WholeStageTransformContext
+import org.apache.gluten.substrait.rel.{InputIteratorRelNode, ReadRelNode, 
RelNode}
+
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
+import org.apache.spark.sql.execution.{CoalescedMapperPartitionSpec, 
CoalescedPartitionSpec, PartialMapperPartitionSpec, 
PartialReducerPartitionSpec, ShufflePartitionSpec}
+import org.apache.spark.sql.execution.adaptive.{BroadcastStats, InputStats, 
ScanInputStats, ShuffleStats}
+import org.apache.spark.sql.execution.datasources.LogicalRelation
+
+import scala.collection.{mutable, Seq}
+
+object ApplyStageInputStatsRule extends Logging {
+  def setStageInputStatsToInputNode(
+      ws: WholeStageTransformContext,
+      index: Int,
+      partitionLength: Int): Unit = {
+    val relNodesQueue: mutable.Queue[RelNode] = mutable.Queue()
+    val nodes = ws.root.getRelNodes
+    if (nodes != null) {
+      nodes.forEach(relNodesQueue.enqueue(_))
+    }
+    while (relNodesQueue.nonEmpty) {
+      val node = relNodesQueue.dequeue()
+      node match {
+        case input: InputIteratorRelNode =>
+          val stats = input.getInputStats
+          if (null != stats) {
+            val totalBytes = Math.max(stats.bytesByPartitionId.sum, 1)
+            val estimatedRowCount =
+              if (stats.inputStatsKind == BroadcastStats) {
+                stats.rowCount.toLong
+              } else {
+                (1.0d * stats.rowCount.toLong / totalBytes * 
stats.bytesByPartitionId(index)).toLong
+              }
+            logInfo(s"pass input stats idx: $index with estimated row count 
$estimatedRowCount")
+            input.setRowSize(estimatedRowCount)
+          }
+        case scan: ReadRelNode =>
+          val stats = scan.getInputStats
+          if (null != stats) {
+            val estimatedRowCount = (1.0d * stats.rowCount.toLong / 
partitionLength).toLong
+            logInfo(s"pass scan stats idx: $index with estimated row count 
$estimatedRowCount")
+            scan.setRowSize(estimatedRowCount)
+          }

Review Comment:
   `partitionLength` can be 0, which would make the estimated row count 
computation divide by zero and potentially set a huge `rowSize` (or an invalid 
value) for scan nodes. This should be guarded so missing/unknown partition 
sizing doesn’t corrupt the hint.



##########
gluten-substrait/src/main/java/org/apache/gluten/substrait/rel/ReadRelNode.java:
##########
@@ -74,11 +100,40 @@ public Rel toProtobuf() {
     }
 
     if (extensionNode != null) {
-      readBuilder.setAdvancedExtension(extensionNode.toProtobuf());
+      if (null != rowSize) {
+        Any optimization = extensionNode.getOptimization();
+        Any enhancement = extensionNode.getEnhancement();
+        try {
+          Any any = Any.parseFrom(optimization.toByteArray());
+          String newOptimizationStr = any.getValue() + "rowSize=" + 
rowSize.toLong() + "\n";
+          Any newOptimization =
+              
Any.pack(StringValue.newBuilder().setValue(newOptimizationStr).build());
+          readBuilder.setAdvancedExtension(
+              new AdvancedExtensionNode(newOptimization, 
enhancement).toProtobuf());
+        } catch (InvalidProtocolBufferException e) {
+          throw new RuntimeException(e);
+        }

Review Comment:
   When `rowSize` is set and an existing `AdvancedExtensionNode` is present, 
the code appends `any.getValue()` (a serialized ByteString payload) to a Java 
`String`. This will not preserve the existing optimization string (and can also 
NPE if `optimization` is null). Unpack `StringValue` (when present) before 
appending, and handle non-StringValue/nullable optimizations safely.



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