viirya commented on code in PR #56928:
URL: https://github.com/apache/spark/pull/56928#discussion_r3511100216


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/DataSourceScanExec.scala:
##########
@@ -320,6 +320,33 @@ trait FileSourceScanLike extends DataSourceScanExec with 
SessionStateHelper {
   def requiredSchema: StructType
   // Identifier for the table in the metastore.
   def tableIdentifier: Option[TableIdentifier]
+  // When true, the `MarkSingleTaskExecution` optimizer rule has marked this 
scan's plan shape as a
+  // candidate for single-task execution. The scan is only actually executed 
in a single task when
+  // it additionally passes the file count and size thresholds (see 
`useSingleTaskExecution`).
+  def markedForSingleTaskExecution: Boolean
+
+  /**
+   * Whether this file scan should run in a single task, reporting a 
`SinglePartition` output
+   * partitioning so that a following shuffle can be elided. This is true when 
the plan shape was
+   * marked eligible by the optimizer and the statically-selected files fall 
within the configured
+   * count and size bounds. It relies on `selectedPartitions`, so it must not 
be evaluated before
+   * the scan's file listing is available.
+   */
+  lazy val useSingleTaskExecution: Boolean = {
+    if (!markedForSingleTaskExecution) {
+      false
+    } else {
+      val sqlConf = getSqlConf(relation.sparkSession)
+      val minNumFiles = 
sqlConf.getConf(SQLConf.SINGLE_TASK_EXECUTION_MIN_NUM_FILES)
+      val maxNumFiles = 
sqlConf.getConf(SQLConf.SINGLE_TASK_EXECUTION_MAX_NUM_FILES)
+      val minNumBytes = 
sqlConf.getConf(SQLConf.SINGLE_TASK_EXECUTION_MIN_NUM_BYTES)
+      val maxPartitionBytes = 
sqlConf.getConf(SQLConf.FILES_MAX_PARTITION_BYTES)
+      val numFiles = selectedPartitions.totalNumberOfFiles
+      val numBytes = selectedPartitions.totalFileSize
+      numFiles >= minNumFiles && numFiles <= maxNumFiles &&
+        numBytes >= minNumBytes && numBytes <= maxPartitionBytes

Review Comment:
   Right, file scans should respect it too. Moved the check up to `apply()` so 
the whole rule is skipped when a leaf-node parallelism override is set.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/ExpandExec.scala:
##########
@@ -43,8 +43,17 @@ case class ExpandExec(
     "numOutputRows" -> SQLMetrics.createMetric(sparkContext, "number of output 
rows"))
 
   // The GroupExpressions can output data with arbitrary partitioning, so set 
it
-  // as UNKNOWN partitioning
-  override def outputPartitioning: Partitioning = UnknownPartitioning(0)
+  // as UNKNOWN partitioning. Expand only replicates rows within a partition 
and never moves rows
+  // across partitions, so when the single-task optimization is enabled and 
the child produces a
+  // single partition, we can forward the `SinglePartition` property to avoid 
an unneeded shuffle.
+  override def outputPartitioning: Partitioning = {
+    if (conf.getConf(SQLConf.SINGLE_TASK_EXECUTION_EXPAND) &&

Review Comment:
   Addressed both points: the decision is now made at optimization time — 
`MarkSingleTaskExecution` also tags the `Expand` in a marked plan, and the 
planner passes it into `ExpandExec` as a constructor field — so 
`outputPartitioning` no longer reads the session conf at execution time, and 
the forwarding only applies within marked plans.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/DataSourceScanExec.scala:
##########
@@ -744,10 +774,28 @@ case class FileSourceScanExec(
     inputRDD :: Nil
   }
 
+  /**
+   * The input RDD, coalesced to a single partition when this scan runs in 
single-task mode. This
+   * enforces the `SinglePartition` output partitioning reported by 
`outputPartitioning`, which is
+   * estimated from the statically-selected files and may not correspond 
exactly to the number of
+   * partitions the input RDD produces after dynamic pruning. Coalescing here 
keeps the query
+   * correct in either case.
+   */
+  private[spark] lazy val maybeCoalesceInputRDD: RDD[InternalRow] = {
+    if (useSingleTaskExecution && inputRDD.getNumPartitions > 1) {
+      inputRDD.coalesce(1)

Review Comment:
   Good catch — the combination was inconsistent: a marked bucketed scan would 
advertise `HashPartitioning` while `maybeCoalesceInputRDD` coalesced it to one 
partition. `useSingleTaskExecution` now returns false for bucketed scans, which 
keeps both code paths consistent by construction. Added a test.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/DataSourceScanExec.scala:
##########


Review Comment:
   Added.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/MarkSingleTaskExecution.scala:
##########
@@ -0,0 +1,161 @@
+/*
+ * 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.execution.datasources
+
+import org.apache.spark.sql.catalyst.plans.logical._
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreeNodeTag
+import org.apache.spark.sql.catalyst.trees.TreePattern._
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * This optimizer rule marks eligible query plans for single-task execution. 
The optimization
+ * targets a conservative, specific query shape to ensure predictable and 
efficient behavior.
+ *
+ * The rule matches simple query plans with a single small file scan or a 
single small in-memory
+ * relation, optionally with a shuffle-inducing operator (sort, aggregation, 
window, expand, or
+ * limit/offset) on top. When it detects such a shape, it marks the underlying 
scan:
+ *
+ *  - a [[LogicalRelation]] or [[LocalRelation]] is marked with the
+ *    [[MarkSingleTaskExecution.markTag]] tag.
+ *
+ * The physical scan then reports a `SinglePartition` output partitioning, 
which allows
+ * [[org.apache.spark.sql.execution.exchange.EnsureRequirements]] to elide the 
shuffle that would
+ * otherwise be inserted before the operator on top. This shuffle is not 
required for correctness
+ * of the query, so removing it reduces scheduling overhead for small, 
low-latency queries.
+ *
+ * The matching is deliberately strict and conservative to minimize the risk 
of unintended
+ * performance regressions. It can be broadened in the future as needed.
+ *
+ * This rule is controlled by [[SQLConf.SINGLE_TASK_EXECUTION_ENABLED]] and 
the per-operator
+ * sub-flags in [[SQLConf]].
+ */
+object MarkSingleTaskExecution extends Rule[LogicalPlan] {
+
+  /**
+   * Tag placed on a [[LogicalRelation]] or [[LocalRelation]] that has been 
marked eligible for
+   * single-task execution. The planning strategies read this tag to propagate 
the decision to the
+   * physical [[org.apache.spark.sql.execution.FileSourceScanExec]] /
+   * [[org.apache.spark.sql.execution.LocalTableScanExec]].
+   */
+  val markTag: TreeNodeTag[Boolean] = 
TreeNodeTag[Boolean]("__single_task_execution")
+
+  private def get[T](entry: org.apache.spark.internal.config.ConfigEntry[T]): 
T =
+    SQLConf.get.getConf(entry)

Review Comment:
   Done, removed the helper.



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