You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@spark.apache.org by do...@apache.org on 2026/03/25 19:32:25 UTC

(spark) branch master updated: [SPARK-56203][SQL] Fix race condition in `SortExec.rowSorter`

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

dongjoon pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark.git


The following commit(s) were added to refs/heads/master by this push:
     new 1e52a02861c8 [SPARK-56203][SQL] Fix race condition in `SortExec.rowSorter`
1e52a02861c8 is described below

commit 1e52a02861c8232b0ba8b16cfeb3ad40563d0804
Author: Peter Toth <pe...@gmail.com>
AuthorDate: Wed Mar 25 12:32:14 2026 -0700

    [SPARK-56203][SQL] Fix race condition in `SortExec.rowSorter`
    
    ### What changes were proposed in this pull request?
    
    Replace `private[sql] var rowSorter: ThreadLocal[UnsafeExternalRowSorter]` with `transient private[sql] lazy val rowSorter: ThreadLocal[UnsafeExternalRowSorter]` in `SortExec`.
    
    Remove the `rowSorter = new ThreadLocal()` reassignment that was inside `createSorter()`.
    
    ### Why are the changes needed?
    
    `SortExec` is a shared plan object: the same instance is used by all tasks that execute different partitions of the same stage.  In the original code, `createSorter()` would write `rowSorter = new ThreadLocal()` — an unsynchronised write to a shared `var`.  If two tasks (threads T0 and T1) called `createSorter()` concurrently:
    
    1. T0 writes `rowSorter = ThreadLocal_0`, sets `ThreadLocal_0.set(sorter_0)`
    2. T1 writes `rowSorter = ThreadLocal_1`, sets `ThreadLocal_1.set(sorter_1)`
    3. T0's `cleanupResources()` reads `rowSorter` — now points to `ThreadLocal_1` — calls `ThreadLocal_1.get()` on thread T0 → `null` → `sorter_0` is leaked
    
    With a stable `lazy val`, the `ThreadLocal` object is created once (Scala lazy-val initialisation is thread-safe).  Every call to `createSorter()` just calls `rowSorter.set(newSorter)` on the same object.  Because `ThreadLocal` gives each thread an independent slot, T0's slot and T1's slot are completely separate; neither task can observe or clobber the other's sorter reference.
    
    `transient` is required because `ThreadLocal` is not `Serializable`; after deserialisation the lazy val re-initialises to a fresh `ThreadLocal` on first access, which is the correct behaviour on an executor.
    
    ### Does this PR introduce _any_ user-facing change?
    
    No.
    
    ### How was this patch tested?
    
    Existing `SortSuite` tests cover correct sort output and spill behaviour.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Sonnet 4.6
    
    Closes #55006 from peter-toth/SPARK-56203-fix-sortexec-rowsorter.
    
    Authored-by: Peter Toth <pe...@gmail.com>
    Signed-off-by: Dongjoon Hyun <do...@apache.org>
---
 .../org/apache/spark/sql/execution/SortExec.scala  | 22 ++++++++++++----------
 1 file changed, 12 insertions(+), 10 deletions(-)

diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/SortExec.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/SortExec.scala
index 11fde41aae9e..34ff34c26eb4 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/SortExec.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/SortExec.scala
@@ -62,9 +62,13 @@ case class SortExec(
     "peakMemory" -> SQLMetrics.createSizeMetric(sparkContext, "peak memory"),
     "spillSize" -> SQLMetrics.createSizeMetric(sparkContext, "spill size"))
 
-  // Each task has its own instance of UnsafeExternalRowSorter. It is created in the
-  // createSorter method and stored in a ThreadLocal variable.
-  private[sql] var rowSorter: ThreadLocal[UnsafeExternalRowSorter] = _
+  // Each task thread has its own UnsafeExternalRowSorter instance stored here.
+  // Using a stable lazy val (rather than a reassigned var) ensures that the ThreadLocal
+  // object itself is never replaced: concurrent tasks on different threads each get their
+  // own independent slot in the same ThreadLocal, so one task can never observe or clobber
+  // another task's sorter reference.
+  @transient private[sql] lazy val rowSorter: ThreadLocal[UnsafeExternalRowSorter] =
+    new ThreadLocal[UnsafeExternalRowSorter]()
 
   /**
    * This method gets invoked only once for each SortExec instance to initialize an
@@ -73,8 +77,6 @@ case class SortExec(
    * should make it public.
    */
   def createSorter(): UnsafeExternalRowSorter = {
-    rowSorter = new ThreadLocal[UnsafeExternalRowSorter]()
-
     val ordering = RowOrdering.create(sortOrder, output)
 
     // The comparator for comparing prefix
@@ -196,13 +198,13 @@ case class SortExec(
   }
 
   /**
-   * In SortExec, we overwrites cleanupResources to close UnsafeExternalRowSorter.
+   * In SortExec, we overwrite cleanupResources to close UnsafeExternalRowSorter.
+   * There's possible for rowSorter to be null here, for example, in the scenario of empty iterator
+   * in the current task, the downstream physical node (like SortMergeJoinExec) will trigger
+   * cleanupResources before rowSorter is initialized in createSorter.
    */
   override protected[sql] def cleanupResources(): Unit = {
-    if (rowSorter != null && rowSorter.get() != null) {
-      // There's possible for rowSorter is null here, for example, in the scenario of empty
-      // iterator in the current task, the downstream physical node(like SortMergeJoinExec) will
-      // trigger cleanupResources before rowSorter initialized in createSorter.
+    if (rowSorter.get() != null) {
       rowSorter.get().cleanupResources()
     }
     super.cleanupResources()


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@spark.apache.org
For additional commands, e-mail: commits-help@spark.apache.org