You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@spark.apache.org by we...@apache.org on 2026/09/22 12:38:32 UTC

(spark) branch master updated: [SPARK-57547][SQL] Fix NPE in PartitionKeyedAccumulator during initialization race condition

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

cloud-fan 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 2a298dac4894 [SPARK-57547][SQL] Fix NPE in PartitionKeyedAccumulator during initialization race condition
2a298dac4894 is described below

commit 2a298dac48948328d3d6cf3c86084e4016fe1390
Author: Ziqi Liu <zi...@databricks.com>
AuthorDate: Tue Sep 22 12:38:18 2026 +0000

    [SPARK-57547][SQL] Fix NPE in PartitionKeyedAccumulator during initialization race condition
    
    ### What changes were proposed in this pull request?
    
    Make the backing map a lazily created `var` reached only through `getOrCreate`, which is the fix [SPARK-20977 ](https://github.com/apache/spark/pull/31540)applied to `CollectionAccumulator` for the same hazard.
    
    ### Why are the changes needed?
     A follow up for https://github.com/apache/spark/pull/56620, which introduced a NPE risk.
    
    It's pretty much the same issue as [SPARK-20977](https://github.com/apache/spark/pull/31540).
    
    the racing condition:
    - `PartitionKeyedAccumulator[T] extends AccumulatorV2` deserialized in executor
    - `AccumulatorV2.readObject` registers the accumulator with the `TaskContext`--> as this point, this accumulator is considered "published", i.e., accessible through other threads, however, the class is **not fully initialized**: only `AccumulatorV2` fields are properly init, but subclass's fields are not
    - Java deserialization then proceeds to read `PartitionKeyedAccumulator`'s own fields, **now it's fully initialized**
    
    So during the window between step 2 and step3, executor heartbeat polling comes in and access the not-initialized field, it would run into NPE
    
    ### Does this PR introduce _any_ user-facing change?
    NO
    
    ### How was this patch tested?
    Added UT case.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated by Claude with Opus5
    
    Closes #58960 from liuzqt/SPARK-57547-fix.
    
    Authored-by: Ziqi Liu <zi...@databricks.com>
    Signed-off-by: Wenchen Fan <we...@databricks.com>
---
 .../spark/sql/util/PartitionKeyedAccumulator.scala | 65 +++++++++++++++-------
 .../sql/util/PartitionKeyedAccumulatorSuite.scala  | 58 ++++++++++++++++++-
 2 files changed, 101 insertions(+), 22 deletions(-)

diff --git a/sql/core/src/main/scala/org/apache/spark/sql/util/PartitionKeyedAccumulator.scala b/sql/core/src/main/scala/org/apache/spark/sql/util/PartitionKeyedAccumulator.scala
index f56a6f882eda..5e2207021cab 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/util/PartitionKeyedAccumulator.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/util/PartitionKeyedAccumulator.scala
@@ -34,58 +34,81 @@ import org.apache.spark.util.AccumulatorV2
  * failed/interrupted tasks are dropped by the accumulator framework (it is not
  * `countFailedValues`), so only complete per-partition values are ever merged.
  *
- * Backed by a `ConcurrentHashMap`. Mutations and folds are synchronized so a caller can atomically
- * verify that every partition completed and read its statistics from the same stable snapshot.
+ * Backed by a `ConcurrentHashMap`. All access is synchronized so a caller can atomically verify
+ * that every partition completed and read its statistics from the same stable snapshot.
  * Framework-facing reads remain safe, weakly consistent views.
  *
  * @tparam T the per-partition value type. Must be non-null (`ConcurrentHashMap` forbids nulls).
  */
 class PartitionKeyedAccumulator[T] extends AccumulatorV2[(Int, T), java.util.Map[Int, T]] {
 
-  // partition id -> value.
-  private val byPartition = new ConcurrentHashMap[Int, T]()
+  // partition id -> value. Deliberately a lazily created `var` rather than a `val`: Java
+  // deserialization assigns a subclass's fields only AFTER `AccumulatorV2.readObject` has already
+  // registered `this` with the `TaskContext`, so another thread can reach this accumulator while
+  // the map is still unset -- in production the executor heartbeater, which calls `isZero` on every
+  // registered accumulator. A final field would additionally leave that thread no guarantee of ever
+  // seeing the post-publication reflective write (JLS 17.5.3). All access goes through
+  // `getOrCreate`; see SPARK-20977, which fixed the same hazard in `CollectionAccumulator`.
+  private var byPartition: ConcurrentHashMap[Int, T] = _
+
+  private def getOrCreate: ConcurrentHashMap[Int, T] = {
+    if (byPartition == null) {
+      byPartition = new ConcurrentHashMap[Int, T]()
+    }
+    byPartition
+  }
 
-  override def isZero: Boolean = byPartition.isEmpty
+  override def isZero: Boolean = synchronized {
+    getOrCreate.isEmpty
+  }
 
   override def copyAndReset(): PartitionKeyedAccumulator[T] = new PartitionKeyedAccumulator[T]
 
   override def copy(): PartitionKeyedAccumulator[T] = synchronized {
     val newAcc = new PartitionKeyedAccumulator[T]
-    newAcc.byPartition.putAll(byPartition)
+    newAcc.getOrCreate.putAll(getOrCreate)
     newAcc
   }
 
   override def reset(): Unit = synchronized {
-    byPartition.clear()
+    getOrCreate.clear()
   }
 
   override def add(v: (Int, T)): Unit = synchronized {
-    byPartition.put(v._1, v._2)
+    getOrCreate.put(v._1, v._2)
   }
 
-  override def merge(other: AccumulatorV2[(Int, T), java.util.Map[Int, T]]): Unit = synchronized {
-    other match {
-      case o: PartitionKeyedAccumulator[T] =>
-        // Last-write-wins per partition id: a partition recorded by more than one task replaces
-        // rather than accumulates, keeping any caller-derived aggregate exact.
-        byPartition.putAll(o.byPartition)
-      case _ => throw new UnsupportedOperationException(
-        s"Cannot merge ${this.getClass.getName} with ${other.getClass.getName}")
-    }
+  override def merge(other: AccumulatorV2[(Int, T), java.util.Map[Int, T]]): Unit = other match {
+    case o: PartitionKeyedAccumulator[T] =>
+      // Resolve the source map before taking our own monitor. Acquiring `o`'s monitor while
+      // holding ours would leave the two merge directions with opposite lock orders, so a
+      // concurrent `o.merge(this)` could deadlock against this call.
+      val source = o.value
+      // Last-write-wins per partition id: a partition recorded by more than one task replaces
+      // rather than accumulates, keeping any caller-derived aggregate exact.
+      synchronized {
+        getOrCreate.putAll(source)
+      }
+    case _ => throw new UnsupportedOperationException(
+      s"Cannot merge ${this.getClass.getName} with ${other.getClass.getName}")
   }
 
   // A read-only VIEW over the live map -- no copy. Only the accumulator framework calls `value`
   // (event log / `toInfo` / `toString`); our own code reads via `accumulatedNumPartitions` /
   // `foldValues`. The view is thread-safe (ConcurrentHashMap) and weakly consistent, which matches
   // this accumulator's eventual-consistency contract.
-  override def value: java.util.Map[Int, T] = java.util.Collections.unmodifiableMap(byPartition)
+  override def value: java.util.Map[Int, T] = synchronized {
+    java.util.Collections.unmodifiableMap(getOrCreate)
+  }
 
   /** Number of distinct partitions that have been recorded. */
-  def accumulatedNumPartitions: Long = byPartition.size().toLong
+  def accumulatedNumPartitions: Long = synchronized {
+    getOrCreate.size().toLong
+  }
 
   private def foldValuesUnsafe[A](zero: A)(op: (A, T) => A): A = {
     var result = zero
-    val it = byPartition.values().iterator()
+    val it = getOrCreate.values().iterator()
     while (it.hasNext) result = op(result, it.next())
     result
   }
@@ -100,7 +123,7 @@ class PartitionKeyedAccumulator[T] extends AccumulatorV2[(Int, T), java.util.Map
       expectedNumPartitions: Int,
       zero: A)(
       op: (A, T) => A): Option[A] = synchronized {
-    if (byPartition.size() == expectedNumPartitions) {
+    if (getOrCreate.size() == expectedNumPartitions) {
       Some(foldValuesUnsafe(zero)(op))
     } else {
       None
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/util/PartitionKeyedAccumulatorSuite.scala b/sql/core/src/test/scala/org/apache/spark/sql/util/PartitionKeyedAccumulatorSuite.scala
index 17aa7de7f86d..6a06ce462836 100644
--- a/sql/core/src/test/scala/org/apache/spark/sql/util/PartitionKeyedAccumulatorSuite.scala
+++ b/sql/core/src/test/scala/org/apache/spark/sql/util/PartitionKeyedAccumulatorSuite.scala
@@ -17,7 +17,11 @@
 
 package org.apache.spark.sql.util
 
-import org.apache.spark.SparkFunSuite
+import java.util.Properties
+
+import org.apache.spark.{SparkFunSuite, TaskContext, TaskContextImpl}
+import org.apache.spark.executor.TaskMetrics
+import org.apache.spark.util.{AccumulatorContext, AccumulatorMetadata, AccumulatorV2, Utils}
 
 class PartitionKeyedAccumulatorSuite extends SparkFunSuite {
 
@@ -126,4 +130,56 @@ class PartitionKeyedAccumulatorSuite extends SparkFunSuite {
         (rows + partitionRows, bytes + partitionBytes)
     }.contains((17L, 170L)))
   }
+
+  test("SPARK-57547: accessors are null-safe while readObject publishes the accumulator") {
+    // `AccumulatorV2.readObject` registers `this` with the `TaskContext` before Java
+    // deserialization has read this subclass's fields, so the backing map is still unset at that
+    // point. `isZero` is the accessor that hit this in production: the executor heartbeater calls
+    // it on every registered accumulator, where it threw a NullPointerException and killed the
+    // heartbeat thread. `value` is not on the heartbeat path in this window -- it is covered here
+    // as additional null-safety, since the driver reaches it later via `toInfoUpdate` should a
+    // half-read accumulator ever be shipped. Stand in for those readers by probing from
+    // `registerAccumulator`, which `readObject` calls at exactly that moment.
+    //
+    // Each accessor gets its own fresh deserialization: the first guarded call installs the map,
+    // so probing them together would let a regression in any later accessor pass unnoticed.
+    val probes = Seq[(String, PartitionKeyedAccumulator[Stats] => Unit)](
+      "isZero" -> (acc => assert(acc.isZero)),
+      "value" -> (acc => assert(acc.value.isEmpty)))
+
+    probes.foreach { case (accessor, probe) =>
+      val acc = new PartitionKeyedAccumulator[Stats]
+      acc.metadata =
+        AccumulatorMetadata(AccumulatorContext.newId(), None, countFailedValues = false)
+      AccumulatorContext.register(acc)
+
+      var probed = false
+      val taskContext = new TaskContextImpl(
+        stageId = 0,
+        stageAttemptNumber = 0,
+        partitionId = 0,
+        taskAttemptId = 0L,
+        attemptNumber = 0,
+        numPartitions = 1,
+        taskMemoryManager = null,
+        localProperties = new Properties,
+        metricsSystem = null,
+        taskMetrics = TaskMetrics.empty,
+        cpuAmount = BigDecimal(1)) {
+        private[spark] override def registerAccumulator(a: AccumulatorV2[_, _]): Unit = {
+          probe(a.asInstanceOf[PartitionKeyedAccumulator[Stats]])
+          probed = true
+        }
+      }
+
+      TaskContext.setTaskContext(taskContext)
+      try {
+        Utils.deserialize[PartitionKeyedAccumulator[Stats]](Utils.serialize(acc))
+      } finally {
+        TaskContext.unset()
+        AccumulatorContext.remove(acc.id)
+      }
+      assert(probed, s"$accessor was never probed, so the race was not exercised")
+    }
+  }
 }


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