This is an automated email from the ASF dual-hosted git repository.
HyukjinKwon 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 04a4063d19de [SPARK-61322][CORE] Report a clear error when a
serialized task exceeds the Java array size limit
04a4063d19de is described below
commit 04a4063d19de70e8d833dd187d7c60e896523545
Author: Ivan <[email protected]>
AuthorDate: Thu Nov 12 08:42:24 2026 +0900
[SPARK-61322][CORE] Report a clear error when a serialized task exceeds the
Java array size limit
### What changes were proposed in this pull request?
Serializing a task, or the task binary that a stage's tasks share, can fail
with an `OutOfMemoryError` when the serialized bytes exceed Java's maximum
array size (about 2 GB). This PR detects that case and fails the stage with a
new user-facing error condition, `TASK_SERIALIZATION_TOO_LARGE`, instead of
treating it as a generic failure.
- `Utils.isJavaArraySizeLimitExceeded` recognizes the two messages the JVM
uses when an array cannot grow any further: `Required array length ... is too
large` and `Requested array size exceeds VM limit`. Other `OutOfMemoryError`s,
such as `Java heap space`, do not match.
- The new `JavaArraySizeLimitExceeded` exception is a `SparkThrowable` with
one of two error conditions:
- `TASK_SERIALIZATION_TOO_LARGE.TASK`: a single task is too large,
usually because its partition holds too much data created on the driver (e.g.
`sc.parallelize` of a large local collection).
- `TASK_SERIALIZATION_TOO_LARGE.TASK_BINARY`: the functions or objects
shared by the stage's tasks are too large, usually because a closure captures a
large object.
It does not keep the original `OutOfMemoryError` as its cause, so this
deterministic size-limit failure is not mistaken for heap exhaustion, which
more memory would not fix. The JVM's message is kept in `jvmMessage` and logged.
- `TaskSetManager.resourceOffer`: when serializing a task hits the limit,
the task set is aborted with the new error, like other task serialization
failures. `NonFatal` does not match an `OutOfMemoryError`, so before this
change the error escaped from the scheduler instead.
- `DAGScheduler.submitMissingTasks`: when serializing the task binary hits
the limit, the stage is aborted with the new error instead of the generic `Task
serialization failed: java.lang.OutOfMemoryError: ...` with the
`OutOfMemoryError` as cause.
### Why are the changes needed?
The array size limit is deterministic: retrying, or adding driver or
executor memory, can never make the task fit. Before this change, users saw
either an `OutOfMemoryError` thrown out of the scheduler, or a stage failure
whose cause was an `OutOfMemoryError`. Both look like heap exhaustion and
suggest raising memory, which does not help. The new error says which limit was
hit and how to fix it: read the data from files or a table, split it into more
partitions, or use broadcast varia [...]
### Does this PR introduce _any_ user-facing change?
Yes. When a serialized task or task binary exceeds the 2 GB array limit,
the job now fails with:
```
[TASK_SERIALIZATION_TOO_LARGE.TASK] Cannot run stage 0 because a serialized
task exceeds the 2 GB size limit. Partition 0 holds too much data created on
the driver. Read the data from files or a table, or split it into more
partitions. SQLSTATE: 54000
```
or
```
[TASK_SERIALIZATION_TOO_LARGE.TASK_BINARY] Cannot run stage 0 because a
serialized task exceeds the 2 GB size limit. The functions or objects shared by
its tasks are too large. Use broadcast variables for large objects instead of
capturing them in functions. SQLSTATE: 54000
```
Previously the task case let the `OutOfMemoryError` escape the scheduler,
and the task binary case failed with `Task serialization failed:
java.lang.OutOfMemoryError: Required array length ... is too large`. Other
`OutOfMemoryError`s during serialization behave as before.
### How was this patch tested?
New tests:
- `FailureSuite`:
- A task too large to serialize fails with
`TASK_SERIALIZATION_TOO_LARGE.TASK`, without an `OutOfMemoryError` cause, and
the driver keeps running jobs afterwards.
- The same for a task binary, with
`TASK_SERIALIZATION_TOO_LARGE.TASK_BINARY`.
- A `Java heap space` error during serialization is still reported as
before, with the `OutOfMemoryError` as cause (negative case).
- `TaskSetManagerSuite`: for both JVM messages, `resourceOffer` aborts the
task set with the new error instead of letting the `OutOfMemoryError` escape.
- `UtilsSuite`: `isJavaArraySizeLimitExceeded` matches both array-limit
messages and rejects heap-space errors, an `OutOfMemoryError` without a
message, and non-OOM throwables.
- `SparkThrowableSuite` passes with the new error condition.
The tests make serialization throw the `OutOfMemoryError` from
`writeObject`, so they do not allocate 2 GB.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Code (Claude Opus 5.5)
Closes #60269 from sadikovi/SPARK-61322.
Authored-by: Ivan <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
(cherry picked from commit 6f512cb62c41d667b4ddfd0fd02dd9cf02877f5d)
Signed-off-by: Hyukjin Kwon <[email protected]>
skip-checks: true
---
.../src/main/resources/error/error-conditions.json | 18 ++++++
.../apache/spark/JavaArraySizeLimitExceeded.scala | 73 +++++++++++++++++++++
.../org/apache/spark/scheduler/DAGScheduler.scala | 11 ++++
.../apache/spark/scheduler/TaskSetManager.scala | 9 +++
.../main/scala/org/apache/spark/util/Utils.scala | 19 ++++++
.../test/scala/org/apache/spark/FailureSuite.scala | 74 +++++++++++++++++++++-
.../spark/scheduler/NotSerializableFakeTask.scala | 18 ++++++
.../spark/scheduler/TaskSetManagerSuite.scala | 34 ++++++++++
.../scala/org/apache/spark/util/UtilsSuite.scala | 14 ++++
9 files changed, 269 insertions(+), 1 deletion(-)
diff --git a/common/utils/src/main/resources/error/error-conditions.json
b/common/utils/src/main/resources/error/error-conditions.json
index 505eb5f69333..438e7bf2a8b1 100644
--- a/common/utils/src/main/resources/error/error-conditions.json
+++ b/common/utils/src/main/resources/error/error-conditions.json
@@ -8504,6 +8504,24 @@
],
"sqlState" : "54023"
},
+ "TASK_SERIALIZATION_TOO_LARGE" : {
+ "message" : [
+ "Cannot run stage <stageId> because a serialized task exceeds the 2 GB
size limit."
+ ],
+ "subClass" : {
+ "TASK" : {
+ "message" : [
+ "Partition <partitionId> holds too much data created on the driver.
Read the data from files or a table, or split it into more partitions."
+ ]
+ },
+ "TASK_BINARY" : {
+ "message" : [
+ "The functions or objects shared by its tasks are too large. Use
broadcast variables for large objects instead of capturing them in functions."
+ ]
+ }
+ },
+ "sqlState" : "54000"
+ },
"TASK_WRITE_FAILED" : {
"message" : [
"Task failed while writing rows to <path>."
diff --git
a/core/src/main/scala/org/apache/spark/JavaArraySizeLimitExceeded.scala
b/core/src/main/scala/org/apache/spark/JavaArraySizeLimitExceeded.scala
new file mode 100644
index 000000000000..6fbc40df05c3
--- /dev/null
+++ b/core/src/main/scala/org/apache/spark/JavaArraySizeLimitExceeded.scala
@@ -0,0 +1,73 @@
+/*
+ * 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
+
+import scala.jdk.CollectionConverters._
+
+/**
+ * Exception used when serializing a task, or the task binary shared by the
tasks of a stage,
+ * fails because the serialized bytes would exceed Java's maximum array size
(about 2 GB).
+ *
+ * It carries the user-facing error condition `TASK_SERIALIZATION_TOO_LARGE`,
so the scheduler
+ * surfaces it to the user as is instead of wrapping it in a generic stage
failure.
+ *
+ * This intentionally does not retain the original [[OutOfMemoryError]] as its
cause, so this
+ * deterministic size-limit failure is not mistaken for heap exhaustion, which
more memory would
+ * not fix. The JVM's message is kept in [[jvmMessage]] for logging.
+ */
+private[spark] class JavaArraySizeLimitExceeded private (
+ errorClass: String,
+ messageParameters: Map[String, String],
+ val jvmMessage: String,
+ stackTrace: Array[StackTraceElement])
+ extends Exception(SparkThrowableHelper.getMessage(errorClass,
messageParameters))
+ with SparkThrowable {
+
+ setStackTrace(stackTrace)
+
+ override def getMessageParameters: java.util.Map[String, String] =
messageParameters.asJava
+
+ override def getCondition: String = errorClass
+}
+
+private[spark] object JavaArraySizeLimitExceeded {
+
+ /** A single task, which carries the data of its partition, is too large to
serialize. */
+ def forTask(
+ error: OutOfMemoryError,
+ stageId: Int,
+ partitionId: Int): JavaArraySizeLimitExceeded = {
+ new JavaArraySizeLimitExceeded(
+ "TASK_SERIALIZATION_TOO_LARGE.TASK",
+ Map("stageId" -> stageId.toString, "partitionId" ->
partitionId.toString),
+ error.getMessage,
+ error.getStackTrace)
+ }
+
+ /**
+ * The task binary of a stage, which holds the RDD chain and the function
shared by all of its
+ * tasks, is too large to serialize.
+ */
+ def forTaskBinary(error: OutOfMemoryError, stageId: Int):
JavaArraySizeLimitExceeded = {
+ new JavaArraySizeLimitExceeded(
+ "TASK_SERIALIZATION_TOO_LARGE.TASK_BINARY",
+ Map("stageId" -> stageId.toString),
+ error.getMessage,
+ error.getStackTrace)
+ }
+}
diff --git a/core/src/main/scala/org/apache/spark/scheduler/DAGScheduler.scala
b/core/src/main/scala/org/apache/spark/scheduler/DAGScheduler.scala
index d4e32f93d64c..33f450338345 100644
--- a/core/src/main/scala/org/apache/spark/scheduler/DAGScheduler.scala
+++ b/core/src/main/scala/org/apache/spark/scheduler/DAGScheduler.scala
@@ -3415,6 +3415,17 @@ private[spark] class DAGScheduler(
abortStage(stage, "Task not serializable: " + e.toString, Some(e))
runningStages -= stage
+ // Abort execution
+ return
+ case e: OutOfMemoryError if Utils.isJavaArraySizeLimitExceeded(e) =>
+ // The task binary is too large for a Java array. Report it with a
user-facing error and
+ // without the OutOfMemoryError as cause, so it is not mistaken for
heap exhaustion.
+ val failure = JavaArraySizeLimitExceeded.forTaskBinary(e, stage.id)
+ logError(log"Failed to serialize the task binary of ${MDC(STAGE,
stage)} because it " +
+ log"exceeded Java's maximum array size: ${MDC(ERROR,
failure.jvmMessage)}")
+ abortStage(stage, failure.getMessage, Some(failure))
+ runningStages -= stage
+
// Abort execution
return
case e: Throwable =>
diff --git
a/core/src/main/scala/org/apache/spark/scheduler/TaskSetManager.scala
b/core/src/main/scala/org/apache/spark/scheduler/TaskSetManager.scala
index ccf2ba014ba7..c0969e66ac3e 100644
--- a/core/src/main/scala/org/apache/spark/scheduler/TaskSetManager.scala
+++ b/core/src/main/scala/org/apache/spark/scheduler/TaskSetManager.scala
@@ -561,6 +561,15 @@ private[spark] class TaskSetManager(
} catch {
// If the task cannot be serialized, then there's no point to re-attempt
the task,
// as it will always fail. So just abort the whole task-set.
+ case e: OutOfMemoryError if Utils.isJavaArraySizeLimitExceeded(e) =>
+ // The task is larger than a Java array can hold. This is not heap
exhaustion, so it is
+ // reported with a user-facing error that does not keep the
OutOfMemoryError as cause.
+ val failure = JavaArraySizeLimitExceeded.forTask(e, task.stageId,
task.partitionId)
+ logError(log"Failed to serialize task ${MDC(TASK_ID, taskId)} (stage "
+
+ log"${MDC(STAGE_ID, task.stageId)}, partition ${MDC(PARTITION_ID,
task.partitionId)}) " +
+ log"because it exceeded Java's maximum array size: ${MDC(ERROR,
failure.jvmMessage)}")
+ abort(failure.getMessage, Some(failure))
+ throw SparkCoreErrors.failToSerializeTaskError(failure)
case NonFatal(e) =>
val msg = log"Failed to serialize task ${MDC(TASK_ID, taskId)}, not
attempting to retry it."
logError(msg, e)
diff --git a/core/src/main/scala/org/apache/spark/util/Utils.scala
b/core/src/main/scala/org/apache/spark/util/Utils.scala
index 00f427245031..214c389c154c 100644
--- a/core/src/main/scala/org/apache/spark/util/Utils.scala
+++ b/core/src/main/scala/org/apache/spark/util/Utils.scala
@@ -2046,6 +2046,25 @@ private[spark] object Utils
}
}
+ /**
+ * Detects the distinct messages used by supported JDKs when an array cannot
grow any further.
+ * There are two known patterns:
+ *
+ * - `Required array length 2147483639 + 626 is too large`
+ * - `Requested array size exceeds VM limit`
+ *
+ * Unlike a heap-space OOM, this failure can be handled because retrying the
same operation can
+ * never succeed.
+ */
+ def isJavaArraySizeLimitExceeded(error: Throwable): Boolean = error match {
+ case oom: OutOfMemoryError =>
+ Option(oom.getMessage).exists { message =>
+ (message.startsWith("Required array length") && message.endsWith("is
too large")) ||
+ message.contains("Requested array size exceeds VM limit")
+ }
+ case _ => false
+ }
+
/** Resolve a comma-separated list of paths. */
def resolveURIs(paths: String): String = {
if (paths == null || paths.trim.isEmpty) {
diff --git a/core/src/test/scala/org/apache/spark/FailureSuite.scala
b/core/src/test/scala/org/apache/spark/FailureSuite.scala
index 8b75c3a0ba65..caf64108aa05 100644
--- a/core/src/test/scala/org/apache/spark/FailureSuite.scala
+++ b/core/src/test/scala/org/apache/spark/FailureSuite.scala
@@ -17,10 +17,11 @@
package org.apache.spark
-import java.io.{IOException, NotSerializableException, ObjectInputStream}
+import java.io.{IOException, NotSerializableException, ObjectInputStream,
ObjectOutputStream}
import org.apache.spark.internal.config.UNSAFE_EXCEPTION_ON_MEMORY_LEAK
import org.apache.spark.memory.TestMemoryConsumer
+import org.apache.spark.rdd.RDD
import org.apache.spark.storage.StorageLevel
import org.apache.spark.util.NonSerializable
@@ -265,6 +266,53 @@ class FailureSuite extends SparkFunSuite with
LocalSparkContext {
}
}
+ test("SPARK-61322: task that exceeds the Java array size limit fails with a
clear error") {
+ sc = new SparkContext("local[1,1]", "test")
+ // The rows of a parallelized collection are shipped inside the task of
their partition.
+ val error = intercept[JavaArraySizeLimitExceeded] {
+ sc.parallelize(Seq(new ArraySizeLimitBomb), 1).count()
+ }
+ checkError(
+ exception = error,
+ condition = "TASK_SERIALIZATION_TOO_LARGE.TASK",
+ sqlState = Some("54000"),
+ parameters = Map("stageId" -> "0", "partitionId" -> "0"))
+ // The OutOfMemoryError is not kept as cause, so the failure is not seen
as heap exhaustion.
+ assert(error.getCause === null)
+ assert(error.jvmMessage === ArraySizeLimitBomb.message)
+
+ // The driver survives and keeps running jobs.
+ assert(sc.parallelize(1 to 10, 2).count() === 10)
+ }
+
+ test("SPARK-61322: task binary that exceeds the Java array size limit fails
with a clear " +
+ "error") {
+ sc = new SparkContext("local[1,1]", "test")
+ // The RDD is serialized once per stage into the task binary shared by all
of its tasks.
+ val error = intercept[JavaArraySizeLimitExceeded] {
+ new ArraySizeLimitBombRDD(sc).count()
+ }
+ checkError(
+ exception = error,
+ condition = "TASK_SERIALIZATION_TOO_LARGE.TASK_BINARY",
+ sqlState = Some("54000"),
+ parameters = Map("stageId" -> "0"))
+ assert(error.getCause === null)
+ assert(error.jvmMessage === ArraySizeLimitBomb.message)
+
+ assert(sc.parallelize(1 to 10, 2).count() === 10)
+ }
+
+ test("SPARK-61322: heap exhaustion during task serialization is not reported
as too large") {
+ sc = new SparkContext("local[1,1]", "test")
+ val error = intercept[SparkException] {
+ new ArraySizeLimitBombRDD(sc, "Java heap space").count()
+ }
+ // A SparkException, not JavaArraySizeLimitExceeded, without the too-large
error condition.
+
assert(!Option(error.getCondition).exists(_.startsWith("TASK_SERIALIZATION_TOO_LARGE")))
+ assert(error.getCause.isInstanceOf[OutOfMemoryError])
+ }
+
// TODO: Need to add tests with shuffle fetch failures.
}
@@ -280,3 +328,27 @@ class NonDeserializableUserException extends
RuntimeException {
throw new IOException("Intentional exception during deserialization.")
}
}
+
+/** Fails Java serialization the way the JVM does when a byte array cannot
grow any further. */
+class ArraySizeLimitBomb(message: String = ArraySizeLimitBomb.message) extends
Serializable {
+ private def writeObject(out: ObjectOutputStream): Unit = {
+ // scalastyle:off throwerror
+ throw new OutOfMemoryError(message)
+ // scalastyle:on throwerror
+ }
+}
+
+object ArraySizeLimitBomb {
+ val message = "Required array length 2147483639 + 626 is too large"
+}
+
+/** An RDD whose serialization, and so its stage task binary, fails like
[[ArraySizeLimitBomb]]. */
+class ArraySizeLimitBombRDD(sc: SparkContext, message: String =
ArraySizeLimitBomb.message)
+ extends RDD[Int](sc, Nil) {
+ private val bomb = new ArraySizeLimitBomb(message)
+
+ override def compute(split: Partition, context: TaskContext): Iterator[Int]
= Iterator(1)
+
+ override protected def getPartitions: Array[Partition] =
+ Array(new Partition { override def index: Int = 0 })
+}
diff --git
a/core/src/test/scala/org/apache/spark/scheduler/NotSerializableFakeTask.scala
b/core/src/test/scala/org/apache/spark/scheduler/NotSerializableFakeTask.scala
index 0b6f27692057..db595af17da9 100644
---
a/core/src/test/scala/org/apache/spark/scheduler/NotSerializableFakeTask.scala
+++
b/core/src/test/scala/org/apache/spark/scheduler/NotSerializableFakeTask.scala
@@ -40,3 +40,21 @@ private[spark] class NotSerializableFakeTask(myId: Int,
stageId: Int)
@throws(classOf[IOException])
private def readObject(in: ObjectInputStream): Unit = {}
}
+
+/**
+ * A wrapper class to test how (de)serialization of a task that exceeds Java's
maximum array size
+ * is handled. Its serialization fails the way the JVM does when a byte array
cannot grow.
+ */
+private[spark] class ArraySizeLimitFakeTask(stageId: Int, partitionId: Int,
errorMessage: String)
+ extends Task[Array[Byte]](stageId, 0, partitionId, 1,
JobArtifactSet.emptyJobArtifactSet) {
+
+ override def runTask(context: TaskContext): Array[Byte] = Array.empty[Byte]
+ override def preferredLocations: Seq[TaskLocation] = Seq[TaskLocation]()
+
+ @throws(classOf[IOException])
+ private def writeObject(out: ObjectOutputStream): Unit = {
+ // scalastyle:off throwerror
+ throw new OutOfMemoryError(errorMessage)
+ // scalastyle:on throwerror
+ }
+}
diff --git
a/core/src/test/scala/org/apache/spark/scheduler/TaskSetManagerSuite.scala
b/core/src/test/scala/org/apache/spark/scheduler/TaskSetManagerSuite.scala
index 6a02e00d755b..98f88b2d81e5 100644
--- a/core/src/test/scala/org/apache/spark/scheduler/TaskSetManagerSuite.scala
+++ b/core/src/test/scala/org/apache/spark/scheduler/TaskSetManagerSuite.scala
@@ -885,6 +885,40 @@ class TaskSetManagerSuite
assert(manager.isZombie)
}
+ test("SPARK-61322: abort the task set if a task exceeds Java's maximum array
size") {
+ Seq(
+ "Required array length 2147483639 + 626 is too large",
+ "Requested array size exceeds VM limit"
+ ).foreach { errorMessage =>
+ sc = new SparkContext("local", "test")
+ sched = new FakeTaskScheduler(sc, ("exec1", "host1"))
+
+ val taskSet = new TaskSet(
+ Array(new ArraySizeLimitFakeTask(stageId = 0, partitionId = 3,
errorMessage)),
+ 0, 0, 0, null, ResourceProfile.DEFAULT_RESOURCE_PROFILE_ID, None)
+ val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES)
+
+ // The fatal OutOfMemoryError does not escape: the task set is aborted
instead.
+ val error = intercept[TaskNotSerializableException] {
+ manager.resourceOffer("exec1", "host1", ANY)
+ }
+ assert(manager.isZombie)
+ assert(sched.taskSetsFailed.contains(taskSet.id))
+
+ val failure = error.getCause.asInstanceOf[JavaArraySizeLimitExceeded]
+ checkError(
+ exception = failure,
+ condition = "TASK_SERIALIZATION_TOO_LARGE.TASK",
+ sqlState = Some("54000"),
+ parameters = Map("stageId" -> "0", "partitionId" -> "3"))
+ assert(failure.jvmMessage === errorMessage)
+ assert(failure.getCause === null)
+
+ sc.stop()
+ sc = null
+ }
+ }
+
test("abort the job if total size of results is too large") {
val conf = new SparkConf().set(config.MAX_RESULT_SIZE.key, "2m")
sc = new SparkContext("local", "test", conf)
diff --git a/core/src/test/scala/org/apache/spark/util/UtilsSuite.scala
b/core/src/test/scala/org/apache/spark/util/UtilsSuite.scala
index e296dc96bb10..ecb078c6b4fb 100644
--- a/core/src/test/scala/org/apache/spark/util/UtilsSuite.scala
+++ b/core/src/test/scala/org/apache/spark/util/UtilsSuite.scala
@@ -2042,6 +2042,20 @@ class UtilsSuite extends SparkFunSuite with
ResetSystemProperties {
assert(Utils.medianInPlace(input.clone()) === Utils.median(input, false))
}
}
+
+ test("SPARK-61322: isJavaArraySizeLimitExceeded distinguishes array-size
limits from heap " +
+ "exhaustion") {
+ Seq(
+ "Required array length 2147483639 + 626 is too large",
+ "Requested array size exceeds VM limit"
+ ).foreach { message =>
+ assert(Utils.isJavaArraySizeLimitExceeded(new OutOfMemoryError(message)))
+ }
+ assert(!Utils.isJavaArraySizeLimitExceeded(new OutOfMemoryError("Java heap
space")))
+ assert(!Utils.isJavaArraySizeLimitExceeded(new OutOfMemoryError()))
+ assert(!Utils.isJavaArraySizeLimitExceeded(
+ new RuntimeException("Requested array size exceeds VM limit")))
+ }
}
private class SimpleExtension
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]