iceberg: Spark: Doing a Coalesce and foreachpartitions in spark directly on an iceberg table is leaking memory heavy iterators
Apache Iceberg version
1.5.0
Query engine
Spark
Please describe the bug 🐞
Summary
Doing the following should not leak any significant amount of memory.
sparkSession.sql("select * from icebergcatalog.db.table").coalesce(4).foreachPartition( (iterator) -> {
while (iterator.hasNext()) iterator.next();
});
A workaround is to use repartition() instead however this requires more resources to handle spilling shuffling etc…
Spark version: Spark 3.4.X
Details
The Below code can be run on a sufficiently large iceberg table.
static AtomicInteger partitionCounter = new AtomicInteger(0);
static void reproduceBug(SparkSession sparkSession, String table) {
sparkSession.sql("select * from "+table).coalesce(4).foreachPartition( (iterator) -> {
int partition = partitionCounter.getAndIncrement();
AtomicLong rowCounter = ThreadLocal.withInitial(() -> new AtomicLong(0)).get();
while (iterator.hasNext()) {
iterator.next();
if (rowCounter.getAndIncrement() % 100000 == 0) {
System.out.println(partition + " " + rowCounter.get());
}
}
});
}
The following image is me running the reproduceBug method over sufficiently large table that we have in our environment with ~500 columns.
The following image shows the “Dominators” report in VisualVM org.apache.spark.TaskContextImpl
Digging deeper we see that the onCallbacks is keeping an anonymous class inside org.apache.spark.sql.execution.datasources.v2.DataSourceRDD and that is holding a reference to org.apache.iceberg.spark.source.RowDataReader
I believe this callback is added here https://github.com/apache/spark/blob/master/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/DataSourceRDD.scala#L90
We also see the org.apache.iceberg.util.Filter iterator holding a heavy reference.
Exploring the problem
Is this inherently a bug in org.apache.spark.sql.execution.datasources.v2.DataSourceRDD? Or should iterators not hold onto state no longer needed once advanced to the end? Is the iterator even exhausted? Once an iterator is exhausted there is no longer a need for referencing. However this kind of breaks the concept of a CloseableIterator which has an explicit close vs an implicit close where you could detect hasNext() is false and auto-close. then even ignore a duplicate close() as it was handled by an implicit close() of iterator exhaustion. I believe an iterator accumulating hundreds of megabytes of state kind of breaks the implicit “expected” contract of an iterator being a streaming set of objects. There might even be a distinction between closing and simply holding onto large object references.
Digging deeper I see items = org.apache.iceberg.parquet.ParquetReader$FileIterator#6 holding onto a model reference. It might be possible to null out the model references when hasNext() is false.
@Override
public boolean hasNext() {
boolean hasNext = valuesRead < totalValues;
if (!hasNext) {
this.model = null;
}
return hasNext;
}
Willingness to contribute
- I can contribute a fix for this bug independently
- I would be willing to contribute a fix for this bug with guidance from the Iceberg community
- I cannot contribute a fix for this bug at this time
About this issue
- Original URL
- State: open
- Created a year ago
- Comments: 28 (27 by maintainers)
Commits related to this issue
- [SPARK-52809][SQL] Don't hold reader and iterator references for all partitions in task completion listeners for metric update ### What changes were proposed in this pull request? This patch adds on... — committed to apache/spark by viirya a year ago
- [SPARK-52809][SQL] Don't hold reader and iterator references for all partitions in task completion listeners for metric update ### What changes were proposed in this pull request? This patch adds on... — committed to apache/spark by viirya a year ago
- [SPARK-52809][SQL] Don't hold reader and iterator references for all partitions in task completion listeners for metric update This patch adds only one task completion listener for metric updating fo... — committed to apache/spark by viirya a year ago
I proposed a fix at https://github.com/apache/spark/pull/51503
I’ve stopped working on this issue for now but will get back to it later. I plan on writing some integration tests that can take as parameters a Spark docker image version and an iceberg version to find when this regression started. I also suspect there may possibly be a leak in the VectorizedParquetRecordReader and the corresponding classes in iceberg, but I need to prove that.
I believe it is happening because normally these would be separate tasks but coalesce kind of hides each task and combines multiple partitions into 1 partition so the task cannot “complete” and the callbacks are held much longer.
Also I ran with the parquet v2 code https://github.com/apache/iceberg/issues/13297#issuecomment-2968557949
and a similar fix needs to be applied here I believe. https://github.com/apache/spark/blob/59e6b5b7d350a1603502bc92e3c117311ab2cbb6/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/parquet/ParquetPartitionReaderFactory.scala#L312
This particular table is ~ 500 columns wide and with nesting. I can produce a synthetic dataset later or as part of this issue so it can be reproduced by anyone.
Hi, my team and I had a similar problem while querying and optimizing tables with a huge number of data and delete files. Spark always ran OOM, because resources (Parquet readers, …) weren’t freed properly. I did some debugging and identified
CloseableIterableas the culprit. Unfortunately, I never had time to upstream it properly.CloseableIterablehas the following two problems:CloseableIterableinto an iterator, the returnedCloseableIteratordoesn’t properly close the iterable, thereby causing a resource leak. By returning a custom instance ofCloseableIteratorwhich keeps track of the closable iterable, we properly close the iterable when the iterator gets closed.CloseableIterable.combinewe have a resource leak if the iterable implementsCloseableIterablebecause we never call close on the iterable. By overloadingcombineforCloseableIterablewe can ensure that we close the iterable in addition to the closeable.With the following patch applied, the queries and table optimizations ran without OOM and much lower memory limits.
@jkolash Can you please check if this would fix your problem?
I wanted to bring up another point that @RussellSpitzer helped me identify which was this issue reproduces in a similar way with the v2 Datasources
when I Ran https://github.com/apache/iceberg/issues/13297#issuecomment-2963910701 but set the spark option
spark.sql.sources.useV1SourceListto an empty string it reproduced via the new v2 datasource code, but not the v1 datasource.So this issue also needs to be addressed in spark as well.
On the spark side I think the close() call likely should be done on task completion not via a callback on job completion?, and the metrics can be collected before that close?