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


##########
sql/core/src/main/scala/org/apache/spark/sql/internal/SharedState.scala:
##########
@@ -128,6 +128,16 @@ private[sql] class SharedState(
     statusStore
   }
 
+  /**
+   * The listener that enforces `spark.sql.execution.maxScanBytes`. It is 
created, and starts to
+   * receive events, when the first query with a limit runs.
+   */
+  private[sql] lazy val scanLimitListener: ScanLimitListener = {
+    val listener = new ScanLimitListener(sparkContext.cancelJobsWithTag(_, _))
+    sparkContext.listenerBus.addToStatusQueue(listener)

Review Comment:
   The app status queue is the one most likely to drop events under load. If 
`onStageSubmitted` is dropped, the stage is never tracked and none of its bytes 
count, so the limit silently stops applying. In the other direction, this 
listener adds work to the queue the UI listeners depend on. Since the listener 
is created lazily, would a dedicated queue (`listenerBus.addToQueue(listener, 
"scanLimit")`) be better? If not, the doc should say that dropped events weaken 
the limit.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -2690,6 +2690,25 @@ object SQLConf {
     .booleanConf
     .createWithDefault(true)
 
+  val MAX_SCAN_BYTES = buildConf("spark.sql.execution.maxScanBytes")
+    .doc("The maximum number of bytes a query may read from its data sources, 
including in " +
+      "its subqueries. A query that reads more is cancelled and fails with " +
+      "SCAN_BYTES_LIMIT_EXCEEDED. This is a best-effort guard rather than a 
hard cap. Spark " +
+      "learns how much the tasks of a query have read from the executor 
heartbeats " +
+      "(spark.executor.heartbeatInterval) and when a task ends, so a query can 
read more " +
+      "than the limit before it is cancelled. Only data sources that report 
the bytes they " +
+      "read are limited: file-based sources report the bytes they read from 
storage, while " +
+      "sources such as JDBC report none. Reading cached data counts the size 
of the cached " +
+      "blocks. Jobs that run outside the execution of a query are not limited, 
such as the " +
+      "jobs that infer the schema of a file source while the query is 
analyzed, and the jobs " +
+      "that Dataset.toLocalIterator runs as the iterator it returns is 
consumed. Streaming " +

Review Comment:
   `Dataset.rdd` only wraps the creation of the RDD in an execution, so jobs 
that run on it later (`df.rdd.map(...).count()`, which is common in PySpark) 
are not limited either. Maybe state the general rule: jobs that run on an RDD 
obtained from a Dataset are not limited, with `toLocalIterator` as one example.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -2690,6 +2690,25 @@ object SQLConf {
     .booleanConf
     .createWithDefault(true)
 
+  val MAX_SCAN_BYTES = buildConf("spark.sql.execution.maxScanBytes")
+    .doc("The maximum number of bytes a query may read from its data sources, 
including in " +
+      "its subqueries. A query that reads more is cancelled and fails with " +
+      "SCAN_BYTES_LIMIT_EXCEEDED. This is a best-effort guard rather than a 
hard cap. Spark " +
+      "learns how much the tasks of a query have read from the executor 
heartbeats " +
+      "(spark.executor.heartbeatInterval) and when a task ends, so a query can 
read more " +
+      "than the limit before it is cancelled. Only data sources that report 
the bytes they " +
+      "read are limited: file-based sources report the bytes they read from 
storage, while " +
+      "sources such as JDBC report none. Reading cached data counts the size 
of the cached " +

Review Comment:
   Two notes on this sentence:
   - `bytesRead` comes from Hadoop FileSystem thread statistics on the task 
thread. File-based readers that bypass Hadoop FS (e.g. Iceberg's S3FileIO) 
report 0, and reads issued from other threads can be missed, so "file-based 
sources report the bytes they read from storage" overstates it.
   - Is counting cache hits intended? A query on a cached 50 GB table fails a 
10 GB limit without reading storage, which seems to work against the 
motivation. The error message ("read ... from its data sources") also reads 
oddly in that case.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/ScanLimitListener.scala:
##########
@@ -0,0 +1,223 @@
+/*
+ * 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
+
+import java.util.Properties
+import java.util.concurrent.ConcurrentHashMap
+
+import scala.collection.mutable
+
+import org.apache.spark.InternalAccumulator
+import org.apache.spark.internal.Logging
+import org.apache.spark.internal.LogKeys.{CONFIG, EXECUTION_ID, NUM_BYTES, 
NUM_BYTES_MAX}
+import org.apache.spark.scheduler._
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.util.Utils
+import org.apache.spark.util.collection.OpenHashMap
+
+/**
+ * Enforces `spark.sql.execution.maxScanBytes`. It adds up the bytes read by 
the tasks of every
+ * root SQL execution registered with it, and cancels the jobs of an execution 
once the total is
+ * over the limit of that execution.
+ *
+ * The bytes are the task input metric `bytesRead`. It arrives with the 
executor heartbeats while
+ * a task runs and with the task end event, so an execution is cancelled some 
time after it went
+ * over its limit, not at that point.
+ *
+ * A task retry, a speculative task and a new attempt of a stage read the data 
of a partition
+ * again. To keep that from counting against the limit, the listener keeps one 
value per
+ * partition of a stage, the largest that any attempt reported.
+ *
+ * A job can depend on a stage that a job of another execution is already 
running, and that stage
+ * is not submitted again. So the listener learns from the start of each job 
which stages it
+ * depends on, and counts what a stage reads against every execution that 
depends on it.
+ *
+ * @param cancelJobsWithTag cancels the active jobs that have the given tag, 
for the given reason
+ */
+private[sql] class ScanLimitListener(cancelJobsWithTag: (String, String) => 
Unit)
+  extends SparkListener with Logging {
+
+  // The registered executions by root execution ID. The event handlers read 
it without the lock,
+  // to return early when no execution has a limit.
+  private val executions = new ConcurrentHashMap[Long, ExecutionScanState]()
+
+  // The stages of the registered executions by stage ID. Guarded by `this`, 
as is all the state
+  // of the executions and the stages.
+  private val stages = new mutable.HashMap[Int, StageScanState]()
+
+  /**
+   * Starts to track a root execution. All its jobs, including the ones of its 
nested executions,
+   * must have `jobTag`.
+   */
+  def register(rootExecutionId: Long, maxScanBytes: Long, jobTag: String): 
Unit = {
+    executions.put(rootExecutionId, new ExecutionScanState(rootExecutionId, 
maxScanBytes, jobTag))
+  }
+
+  /** Stops tracking a root execution. */
+  def unregister(rootExecutionId: Long): Unit = synchronized {
+    val execution = executions.remove(rootExecutionId)
+    stages.filterInPlace { (_, stage) =>
+      stage.executions -= execution
+      stage.executions.nonEmpty
+    }
+  }
+
+  /** The bytes that an execution had read when it went over its limit, if it 
did. */
+  def bytesReadOverLimit(rootExecutionId: Long): Option[Long] = synchronized {
+    Option(executions.get(rootExecutionId)).flatMap(_.bytesReadOverLimit)
+  }
+
+  /** The registered execution of a job with the given properties, if any. */
+  private def executionOf(properties: Properties): Option[ExecutionScanState] 
= {
+    Option(properties)
+      .flatMap(p => Option(p.getProperty(SQLExecution.EXECUTION_ROOT_ID_KEY)))
+      .flatMap(rootExecutionId => 
Option(executions.get(rootExecutionId.toLong)))
+  }
+
+  override def onJobStart(event: SparkListenerJobStart): Unit = {

Review Comment:
   Is shared-stage tracking worth its complexity? It only matters when two 
executions depend on the same running stage at the same time. Without it, the 
second execution undercounts, which is consistent with a best-effort guard. It 
is also partial: if the stage was submitted by an execution that has no limit, 
`bytesReadAccumIds` stays empty and earlier tasks are missing from 
`runningTasks`, so only task-end updates count. Either drop it, or also record 
the accumulator IDs from `event.stageInfos` here.



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