Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion mllib/src/main/scala/org/apache/spark/ml/Model.scala
Original file line number Diff line number Diff line change
Expand Up @@ -57,5 +57,19 @@ abstract class Model[M <: Model[M]] extends Transformer { self =>
* 4, For 3-rd extension, if external languages are used, it is recommended to override
* this method and return a proper size.
*/
private[spark] def estimatedSize: Long = SizeEstimator.estimate(self)
private[spark] def estimatedSize: Long = synchronized {
// SPARK-57521: Temporarily clear the parent reference during size estimation.
// After fit(), the parent estimator may retain indirect references to the SparkSession
// (via closures or query plan state from DataFrame operations executed during fit).
// SizeEstimator traverses the entire reachable object graph, causing it to count
// shared SparkSession state as part of every model's size.
// The parent is @transient (not persisted) and is not needed for transform() or save().
val savedParent = parent
parent = null

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please investigate and address a possible thread-safety regression here. There is a side-effecting mutation of shared state in a base-class method. Two concurrent estimatedSize calls on the same model can interleave so both save then both restore, with the second finally clobbering parent to null permanently; a concurrent reader (hasParent, transform, save) can also observe parent == null during the window.

In the current path this is masked because estimatedSize is invoked inside MLCache.register (which is synchronized) on a freshly-fit, not-yet-shared model, so it is not an active production bug today, but estimatedSize is private[spark] and the previous implementation was side-effect free, so the new contract is strictly weaker.

Please consider a non-mutating approach rather than mutating shared instance state.

@mkincaid mkincaid Jun 22, 2026

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @uros-b, thanks for the quick review and input. I pushed a change that adds synchronized so that we wouldn't have two concurrent estimatedSize calls from here. However, I'm realizing this doesn't address the second part of your comment (a concurrent reader from elsewhere would still observe parent == null).

As I looked into this further, the truly non-mutating approaches I came up with were:

  • Create a copy of the Model with empty parent, then size that. But this depends on the implementation of the copy method which is model-specific (so not sure if it can be relied on to faithfully copy everything we care about sizing).
  • Make the Model object Cloneable, then clone(), clear parent, and size. But changing an interface of Model itself seems less conservative and beyond the scope I was intending for this original fix.
  • Serialize and deserialize the object before estimating its size. Since the parent is @transient it would be gone in the serialized copy. This seems conceptually appealing (it seems like, in principle, the data the model keeps and serializes is the state we care about sizing) but not sure if it might be expensive for large models and, like the copy option, should I worry about the possibility something relevant doesn’t survive the round trip.
  • Target the fix elsewhere, e.g., perhaps SizeEstimator itself should skip walking through SparkSession objects (the same way as there are existing exclusions there for ClassLoader and scala.reflect). This also seems less conservative since other users of SizeEstimator might not want the behavior to change.

Or I may be missing something easier/cleaner. It is probably pretty obvious that I'm new to this code base, so I want to be thoughtful about design and get more input before proceeding. Appreciate your patience with me and looking forward to your thoughts :)

try {
SizeEstimator.estimate(self)
} finally {
parent = savedParent
}
}
}
72 changes: 72 additions & 0 deletions mllib/src/test/scala/org/apache/spark/ml/ModelSuite.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
* 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.ml

import org.apache.spark.SparkFunSuite
import org.apache.spark.ml.feature.{MinMaxScaler, StringIndexer}
import org.apache.spark.ml.linalg.Vectors
import org.apache.spark.mllib.util.MLlibTestSparkContext

class ModelSuite extends SparkFunSuite with MLlibTestSparkContext {

test("SPARK-57521: estimatedSize should not include parent's reachable object graph") {
val df = spark.createDataFrame(Seq(
Tuple1("a"), Tuple1("b"), Tuple1("c")
)).toDF("label")

val model = new StringIndexer()
.setInputCol("label").setOutputCol("idx")
.fit(df)

assert(model.hasParent, "model should have parent after fit()")
val size = model.estimatedSize

// Model data is 3 string labels + overhead, well under 50KB.
// Without the fix, SizeEstimator traverses model.parent -> estimator ->
// SparkSession, counting hundreds of KB (local) to hundreds of MB
// (production cluster) of shared session state per model.
assert(size < 50 * 1024,
s"estimatedSize ($size bytes) should reflect model data only, " +
s"not the parent estimator's reachable object graph (SparkSession)")

// Parent must be preserved - it is only excluded during estimation
assert(model.hasParent, "parent should be preserved after estimatedSize call")
}

test("SPARK-57521: estimatedSize excludes parent for multiple estimator types") {
// The issue affects all estimators that execute DataFrame operations during fit().
// Test with two different estimator types to verify the fix is in Model, not
// specific to any one estimator.
val df = spark.createDataFrame(Seq(
Tuple1(Vectors.dense(1.0, 2.0)),
Tuple1(Vectors.dense(3.0, 4.0))
)).toDF("features")

val model = new MinMaxScaler()
.setInputCol("features").setOutputCol("scaled")
.fit(df)

assert(model.hasParent)
val size = model.estimatedSize

assert(size < 50 * 1024,
s"MinMaxScalerModel estimatedSize ($size bytes) should not include " +
s"parent's reachable object graph")
assert(model.hasParent, "parent should be preserved after estimatedSize call")
}
}