This is an automated email from the ASF dual-hosted git repository.

cloud-fan pushed a commit to branch branch-4.x
in repository https://gitbox.apache.org/repos/asf/spark.git


The following commit(s) were added to refs/heads/branch-4.x by this push:
     new 8a472a5308c4 [SPARK-61248][SQL] Close the spill readers of the 
sort-merge ASOF join's buffered scan
8a472a5308c4 is described below

commit 8a472a5308c4144051cc5cd7346de39a1dafb3f9
Author: Luka Zdravić <[email protected]>
AuthorDate: Tue Nov 10 00:10:23 2026 +0000

    [SPARK-61248][SQL] Close the spill readers of the sort-merge ASOF join's 
buffered scan
    
    ### What changes were proposed in this pull request?
    `findLastBackward`, `findFirstForward` and `findNearest` in 
`SortMergeAsOfJoinScanner` make a new iterator over the right-side group for 
each left row, and usually return before it ends. Once the group has spilled, 
that iterator holds a reader open on every spill file until it ends or is 
closed. This PR closes the iterator in a `finally` block. A match the scan 
keeps is already a copy once the group has spilled, so closing the iterator 
does not change it.
    
    The fix uses the `close()` that SPARK-58201 added to the spill iterator of 
`ExternalAppendOnlyUnsafeRowArray`. That change is only on master, so a 
backport to branch-4.x needs it too. Without it, the code compiles but closes 
nothing, and the new test fails.
    
    ### Why are the changes needed?
    The open files stayed open until the task ended. With L left rows in a 
group spilled to S files, a task kept up to L * S files open, which can fail it 
with "Too many open files". Each reader's 1 MB heap buffer still stays until 
the task ends, because a task-completion listener keeps the reader. This PR 
does not change that.
    
    ### Does this PR introduce _any_ user-facing change?
    No.
    
    ### How was this patch tested?
    A new `SortMergeAsOfJoinScannerSuite` test runs a backward, a forward and a 
nearest buffered scan, each in its own task, of 16 left rows over a 50-row 
right group that spills every 10 rows. It checks the matched rows, and that the 
JVM's open file count does not grow with the left rows. Without the fix, each 
scan left 55 or 56 more files open. With it, none. The ASOF join suites, 
`PlannerSuite` and `SQLMetricsSuite` pass.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    Generated-by: Claude Code
    
    This pull request and its description were written by Isaac.
    
    Closes #60240 from LukaZdravic/asof-close-spill-readers.
    
    Authored-by: Luka Zdravić <[email protected]>
    Signed-off-by: Wenchen Fan <[email protected]>
    
    (cherry picked from commit 71e0de6c03b18fd0c0536909398086d0b567b41b)
    Signed-off-by: Wenchen Fan <[email protected]>
    
    
    skip-checks: true
---
 .../execution/joins/SortMergeAsOfJoinExec.scala    | 118 +++++++++++++--------
 .../joins/SortMergeAsOfJoinScannerSuite.scala      |  66 +++++++++++-
 2 files changed, 134 insertions(+), 50 deletions(-)

diff --git 
a/sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeAsOfJoinExec.scala
 
b/sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeAsOfJoinExec.scala
index 448a31dfcb09..be6da428f3a3 100644
--- 
a/sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeAsOfJoinExec.scala
+++ 
b/sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeAsOfJoinExec.scala
@@ -17,6 +17,7 @@
 
 package org.apache.spark.sql.execution.joins
 
+import java.io.Closeable
 import java.math.{BigDecimal => JavaBigDecimal}
 
 import org.apache.spark.{SparkException, TaskContext}
@@ -413,6 +414,17 @@ private[joins] class SortMergeAsOfJoinScanner(
     if (needsCopy) rightRow.copy() else rightRow
   }
 
+  /**
+   * Closes a right-group iterator, which the scans below often leave before 
its end. Once the
+   * group has spilled, the iterator holds a reader open on every spill file 
until it ends or is
+   * closed, so an unclosed one per left row would keep them all open until 
the task ends. A kept
+   * match is already a copy then, so closing the iterator does not change it.
+   */
+  private def closeIterator(iter: Iterator[UnsafeRow]): Unit = iter match {
+    case closeable: Closeable => closeable.close()
+    case _ =>
+  }
+
   /** Whether `cond` is TRUE on the current joined row. FALSE and NULL both 
fail. */
   private def holds(cond: BasePredicate): Boolean = cond.eval(joinedRow)
 
@@ -435,22 +447,26 @@ private[joins] class SortMergeAsOfJoinScanner(
     var asOfSeen = false
 
     joinedRow.withLeft(leftRow)
-    while (iter.hasNext) {
-      val rightRow = iter.next()
-      joinedRow.withRight(rightRow)
-
-      if (holds(boundAsOfCond)) {
-        asOfSeen = true
-        if (residualHolds) {
-          // Last match wins (closest right.t to left.t)
-          bestMatch = retainMatch(rightRow, needsCopy)
+    try {
+      while (iter.hasNext) {
+        val rightRow = iter.next()
+        joinedRow.withRight(rightRow)
+
+        if (holds(boundAsOfCond)) {
+          asOfSeen = true
+          if (residualHolds) {
+            // Last match wins (closest right.t to left.t)
+            bestMatch = retainMatch(rightRow, needsCopy)
+          }
+        } else if (asOfSeen) {
+          // At or past left.t, so no later row passes the as-of condition.
+          return bestMatch
         }
-      } else if (asOfSeen) {
-        // At or past left.t, so no later row passes the as-of condition.
-        return bestMatch
       }
+      bestMatch
+    } finally {
+      closeIterator(iter)
     }
-    bestMatch
   }
 
   /**
@@ -464,21 +480,25 @@ private[joins] class SortMergeAsOfJoinScanner(
     var asOfSeen = false
 
     joinedRow.withLeft(leftRow)
-    while (iter.hasNext) {
-      val rightRow = iter.next()
-      joinedRow.withRight(rightRow)
-
-      if (holds(boundAsOfCond)) {
-        asOfSeen = true
-        if (residualHolds) {
-          return retainMatch(rightRow, needsCopy)
+    try {
+      while (iter.hasNext) {
+        val rightRow = iter.next()
+        joinedRow.withRight(rightRow)
+
+        if (holds(boundAsOfCond)) {
+          asOfSeen = true
+          if (residualHolds) {
+            return retainMatch(rightRow, needsCopy)
+          }
+        } else if (asOfSeen) {
+          // Past the tolerance bound, so no later row passes the as-of 
condition.
+          return null
         }
-      } else if (asOfSeen) {
-        // Past the tolerance bound, so no later row passes the as-of 
condition.
-        return null
       }
+      null
+    } finally {
+      closeIterator(iter)
     }
-    null
   }
 
   /**
@@ -578,33 +598,37 @@ private[joins] class SortMergeAsOfJoinScanner(
     val needsCopy = rightGroupBuffer.isSpillBacked
 
     joinedRow.withLeft(leftRow)
-    while (iter.hasNext) {
-      val rightRow = iter.next()
-      joinedRow.withRight(rightRow)
-
-      if (holds(boundAsOfCond) && residualHolds) {
-        val rightKey = rightKeyExpr.eval(rightRow)
-        if (rightKey != null) {
-          if (keyOrdering.lt(rightKey, leftKey)) {
-            // Keep the first eligible row at each key so equal-distance ties 
stay stable.
-            if (bestBefore == null || keyOrdering.lt(bestBeforeKey, rightKey)) 
{
-              bestBefore = retainMatch(rightRow, needsCopy)
-              bestBeforeKey = InternalRow.copyValue(rightKey)
+    try {
+      while (iter.hasNext) {
+        val rightRow = iter.next()
+        joinedRow.withRight(rightRow)
+
+        if (holds(boundAsOfCond) && residualHolds) {
+          val rightKey = rightKeyExpr.eval(rightRow)
+          if (rightKey != null) {
+            if (keyOrdering.lt(rightKey, leftKey)) {
+              // Keep the first eligible row at each key so equal-distance 
ties stay stable.
+              if (bestBefore == null || keyOrdering.lt(bestBeforeKey, 
rightKey)) {
+                bestBefore = retainMatch(rightRow, needsCopy)
+                bestBeforeKey = InternalRow.copyValue(rightKey)
+              }
+            } else if (keyOrdering.equiv(rightKey, leftKey)) {
+              // An exact match is the nearest row, even for an infinite key 
(Inf - Inf is NaN).
+              return retainMatch(rightRow, needsCopy)
+            } else if (bestBefore == null ||
+                isAfterCloser(bestBeforeKey, leftKey, rightKey, 
leftKeyExpr.dataType)) {
+              return retainMatch(rightRow, needsCopy)
+            } else {
+              return bestBefore
             }
-          } else if (keyOrdering.equiv(rightKey, leftKey)) {
-            // An exact match is the nearest row, even for an infinite key 
(Inf - Inf is NaN).
-            return retainMatch(rightRow, needsCopy)
-          } else if (bestBefore == null ||
-              isAfterCloser(bestBeforeKey, leftKey, rightKey, 
leftKeyExpr.dataType)) {
-            return retainMatch(rightRow, needsCopy)
-          } else {
-            return bestBefore
           }
         }
       }
-    }
 
-    bestBefore
+      bestBefore
+    } finally {
+      closeIterator(iter)
+    }
   }
 
   /** The exact value of a nearest key, or None for a NaN or infinite 
floating-point key. */
diff --git 
a/sql/core/src/test/scala/org/apache/spark/sql/execution/joins/SortMergeAsOfJoinScannerSuite.scala
 
b/sql/core/src/test/scala/org/apache/spark/sql/execution/joins/SortMergeAsOfJoinScannerSuite.scala
index 73c67fafef24..0542a834652b 100644
--- 
a/sql/core/src/test/scala/org/apache/spark/sql/execution/joins/SortMergeAsOfJoinScannerSuite.scala
+++ 
b/sql/core/src/test/scala/org/apache/spark/sql/execution/joins/SortMergeAsOfJoinScannerSuite.scala
@@ -17,9 +17,13 @@
 
 package org.apache.spark.sql.execution.joins
 
+import java.lang.management.ManagementFactory
 import java.util.concurrent.atomic.AtomicInteger
 
+import com.sun.management.UnixOperatingSystemMXBean
+
 import org.apache.spark.{LocalSparkContext, SparkConf, SparkContext, 
SparkFunSuite}
+import org.apache.spark.internal.config.UNSAFE_SORTER_SPILL_READ_AHEAD_ENABLED
 import org.apache.spark.sql.YearUDT
 import org.apache.spark.sql.catalyst.InternalRow
 import org.apache.spark.sql.catalyst.expressions._
@@ -95,6 +99,27 @@ class SortMergeAsOfJoinScannerSuite extends SparkFunSuite 
with LocalSparkContext
     assert(evaluations == 0, s"evaluated the repeated part $evaluations times")
   }
 
+  test("buffered scan closes the spill readers of a group it leaves early") {
+    assume(openFileCount().isDefined, "needs a JVM that counts its open files")
+    // Without read-ahead, each spill reader holds one open file and no extra 
thread.
+    sc = new SparkContext("local", "SortMergeAsOfJoinScannerSuite",
+      new SparkConf(false).set(UNSAFE_SORTER_SPILL_READ_AHEAD_ENABLED, false))
+    // One task per direction, since a task keeps each spill reader's buffer 
until it ends.
+    Seq(Backward, Forward, Nearest).foreach { direction =>
+      withClue(s"$direction: ") {
+        val (matchedKeys, openedFiles) = sc.parallelize(Seq(0), 1)
+          .mapPartitions(_ => Iterator.single(spilledScan(direction)))
+          .collect().head
+        // Each left key k matches the right key k.
+        assert(matchedKeys == spilledScanLeftKeys.toList)
+        // Every left row leaves the scan early, with the later spill files of 
the group still
+        // unread. Readers left open would keep those files open until the 
task ended.
+        assert(openedFiles < spilledScanLeftKeys.size / 2,
+          s"the scan left $openedFiles more files open")
+      }
+    }
+  }
+
   test("conditions are built only when a scan checks a right row") {
     sc = new SparkContext("local", "SortMergeAsOfJoinScannerSuite", new 
SparkConf(false))
     val compiled = sc.parallelize(Seq(0), 1)
@@ -384,7 +409,9 @@ private object SortMergeAsOfJoinScannerSuite {
       rightKeys: Seq[Int],
       asOfCondition: Expression,
       residualCondition: Option[Expression] = None,
-      direction: AsOfJoinDirection = Backward): SortMergeAsOfJoinScanner = {
+      direction: AsOfJoinDirection = Backward,
+      inMemoryThreshold: Int = 256,
+      spillThreshold: Int = 256): SortMergeAsOfJoinScanner = {
     new SortMergeAsOfJoinScanner(
       leftIter = leftKeys.iterator.map(k => InternalRow(k)),
       rightIter = rightKeys.iterator.map(k => InternalRow(k)),
@@ -400,13 +427,46 @@ private object SortMergeAsOfJoinScannerSuite {
       numOutputRows = new SQLMetric("sum"),
       spillSize = new SQLMetric("sum"),
       direction = direction,
-      inMemoryThreshold = 256,
+      inMemoryThreshold = inMemoryThreshold,
       sizeInBytesSpillThreshold = Long.MaxValue,
-      spillThreshold = 256,
+      spillThreshold = spillThreshold,
       useCursorScan = false,
       numAsOfCursorTasks = new SQLMetric("sum"))
   }
 
+  /** Left keys of `spilledScan`: each one is near the start of the right 
keys. */
+  val spilledScanLeftKeys: Seq[Int] = 1 to 16
+
+  /** The number of files this JVM has open, if it can tell. */
+  def openFileCount(): Option[Long] = 
ManagementFactory.getOperatingSystemMXBean match {
+    case unix: UnixOperatingSystemMXBean => 
Some(unix.getOpenFileDescriptorCount)
+    case _ => None
+  }
+
+  /**
+   * Runs a buffered scan in `direction` over a right group of 50 rows that 
spills every 10 rows.
+   * Returns the right key of each output row, and how many more files the JVM 
has open after the
+   * scan than before it, while the task still runs.
+   */
+  def spilledScan(direction: AsOfJoinDirection): (List[Int], Long) = {
+    val leftKey = AttributeReference("leftKey", IntegerType)()
+    val rightKey = AttributeReference("rightKey", IntegerType)()
+    val asOfCondition = direction match {
+      case Backward => GreaterThanOrEqual(leftKey, rightKey)
+      case Forward => LessThanOrEqual(leftKey, rightKey)
+      case _ => Literal.TrueLiteral
+    }
+    val scanner = newScanner(leftKey, rightKey, spilledScanLeftKeys, 0 until 
50, asOfCondition,
+      direction = direction, inMemoryThreshold = 1, spillThreshold = 10)
+    val before = openFileCount().get
+    try {
+      val matchedKeys = scanner.iterator.map(_.getInt(1)).toList
+      (matchedKeys, openFileCount().get - before)
+    } finally {
+      scanner.close()
+    }
+  }
+
   /** Runs the scan to the end and returns the right key of each output row. */
   def matchedRightKeys(scanner: SortMergeAsOfJoinScanner): List[Int] = {
     try {


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

Reply via email to