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.

Image

The following image shows the “Dominators” report in VisualVM org.apache.spark.TaskContextImpl

Image

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. Image

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;
    }
Image

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

Most upvoted comments

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

Image

is it for all wide iceberg tables, and coalesce just makes it more vulnerable?

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 CloseableIterable as the culprit. Unfortunately, I never had time to upstream it properly.

CloseableIterable has the following two problems:

  1. When turning a CloseableIterable into an iterator, the returned CloseableIterator doesn’t properly close the iterable, thereby causing a resource leak. By returning a custom instance of CloseableIterator which keeps track of the closable iterable, we properly close the iterable when the iterator gets closed.
  2. When combining an iterable with a closeable using CloseableIterable.combine we have a resource leak if the iterable implements CloseableIterable because we never call close on the iterable. By overloading combine for CloseableIterable we 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.

From 6e2cfd71c2dcecf432f2db2119ac530674af5042 Mon Sep 17 00:00:00 2001
From: Emmanuel Pescosta <emmanuelpescosta099@gmail.com>
Date: Thu, 16 Jan 2025 12:19:46 +0100
Subject: [PATCH] fix(iceberg.io): Properly close CloseableIterable when
 turning it into an iterator

A CloseableIterator created from a CloseableIterable didn't close
the iterable when the iterator is closed. This may cause a resource
leak.
---
 .../apache/iceberg/io/CloseableIterable.java  | 40 ++++++++++++++++++-
 1 file changed, 38 insertions(+), 2 deletions(-)

diff --git a/api/src/main/java/org/apache/iceberg/io/CloseableIterable.java b/api/src/main/java/org/apache/iceberg/io/CloseableIterable.java
index 06323612a..240c1ef8f 100644
--- a/api/src/main/java/org/apache/iceberg/io/CloseableIterable.java
+++ b/api/src/main/java/org/apache/iceberg/io/CloseableIterable.java
@@ -51,7 +51,7 @@ public interface CloseableIterable<T> extends Iterable<T>, Closeable {
 
       @Override
       public CloseableIterator<E> iterator() {
-        return CloseableIterator.withClose(iterable.iterator());
+        return closeableIteratorOf(iterable, this);
       }
     };
   }
@@ -69,7 +69,43 @@ public interface CloseableIterable<T> extends Iterable<T>, Closeable {
 
       @Override
       public CloseableIterator<E> iterator() {
-        return CloseableIterator.withClose(iterable.iterator());
+        return closeableIteratorOf(iterable, this);
+      }
+    };
+  }
+
+  static <E> CloseableIterable<E> combine(CloseableIterable<E> iterable, Closeable closeable) {
+    return new CloseableIterable<E>() {
+      @Override
+      public void close() throws IOException {
+        closeable.close();
+        iterable.close();
+      }
+
+      @Override
+      public CloseableIterator<E> iterator() {
+        return closeableIteratorOf(iterable, this);
+      }
+    };
+  }
+
+  private static <E> CloseableIterator<E> closeableIteratorOf(
+      Iterable<E> iterable, Closeable closeable) {
+    Iterator<E> iterator = iterable.iterator();
+    return new CloseableIterator<E>() {
+      @Override
+      public void close() throws IOException {
+        closeable.close();
+      }
+
+      @Override
+      public boolean hasNext() {
+        return iterator.hasNext();
+      }
+
+      @Override
+      public E next() {
+        return iterator.next();
       }
     };
   }
-- 
2.49.0

@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.useV1SourceList to an empty string it reproduced via the new v2 datasource code, but not the v1 datasource.

Image

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?