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

github-merge-queue[bot] pushed a commit to branch 
gh-readonly-queue/main/pr-3679-58af4edf5158709d8ec01643400ec64cfacc779f
in repository https://gitbox.apache.org/repos/asf/iceberg-rust.git

commit c9d52179bb6ffbda339b05ce245436b8651711e2
Author: alexanderbianchi <[email protected]>
AuthorDate: Mon Nov 16 20:03:35 2026 +0000

    fix(io): initialize manifest caches only when used (#3679)
    
    Defer Moka cache construction until the first manifest or manifest-list
    read, and skip it entirely when caching is disabled. Share lazy cache
    state across clones and retain existing cache policy and encryption.
    
    Adapted from DataDog/iceberg-rust#34 for upstream main, without the
    fork-specific FileIO rebinding helper.
    
    Co-authored-by: Geoffrey Claude <[email protected]>
---
 crates/iceberg/src/io/object_cache.rs | 98 +++++++++++++++++++----------------
 1 file changed, 52 insertions(+), 46 deletions(-)

diff --git a/crates/iceberg/src/io/object_cache.rs 
b/crates/iceberg/src/io/object_cache.rs
index 874c9d348..37ded3894 100644
--- a/crates/iceberg/src/io/object_cache.rs
+++ b/crates/iceberg/src/io/object_cache.rs
@@ -16,7 +16,7 @@
 // under the License.
 
 use std::mem::size_of_val;
-use std::sync::Arc;
+use std::sync::{Arc, OnceLock};
 
 use crate::encryption::EncryptionManager;
 use crate::io::FileIO;
@@ -74,9 +74,9 @@ impl ManifestKey {
 /// Caches metadata objects deserialized from immutable files
 #[derive(Clone, Debug)]
 pub struct ObjectCache {
-    cache: moka::future::Cache<CachedObjectKey, CachedItem>,
+    cache: Arc<OnceLock<moka::future::Cache<CachedObjectKey, CachedItem>>>,
     file_io: FileIO,
-    cache_disabled: bool,
+    cache_size_bytes: u64,
     encryption_manager: Option<Arc<EncryptionManager>>,
 }
 
@@ -94,21 +94,11 @@ impl ObjectCache {
         cache_size_bytes: u64,
         encryption_manager: Option<Arc<EncryptionManager>>,
     ) -> Self {
-        if cache_size_bytes == 0 {
-            Self::with_disabled_cache(file_io, encryption_manager)
-        } else {
-            Self {
-                cache: moka::future::Cache::builder()
-                    .weigher(|_, val: &CachedItem| match val {
-                        CachedItem::ManifestList(item) => 
size_of_val(item.as_ref()),
-                        CachedItem::Manifest(item) => 
size_of_val(item.as_ref()),
-                    } as u32)
-                    .max_capacity(cache_size_bytes)
-                    .build(),
-                file_io,
-                cache_disabled: false,
-                encryption_manager,
-            }
+        Self {
+            cache: Arc::new(OnceLock::new()),
+            file_io,
+            cache_size_bytes,
+            encryption_manager,
         }
     }
 
@@ -118,28 +108,37 @@ impl ObjectCache {
         file_io: FileIO,
         encryption_manager: Option<Arc<EncryptionManager>>,
     ) -> Self {
-        Self {
-            cache: moka::future::Cache::new(0),
-            file_io,
-            cache_disabled: true,
-            encryption_manager,
+        Self::new_with_capacity(file_io, 0, encryption_manager)
+    }
+
+    fn cache(&self) -> Option<&moka::future::Cache<CachedObjectKey, 
CachedItem>> {
+        if self.cache_size_bytes == 0 {
+            return None;
         }
+        Some(self.cache.get_or_init(|| {
+            moka::future::Cache::builder()
+                .weigher(|_, val: &CachedItem| match val {
+                    CachedItem::ManifestList(item) => 
size_of_val(item.as_ref()),
+                    CachedItem::Manifest(item) => size_of_val(item.as_ref()),
+                } as u32)
+                .max_capacity(self.cache_size_bytes)
+                .build()
+        }))
     }
 
     /// Retrieves an Arc [`Manifest`] from the cache
     /// or retrieves one from FileIO and parses it if not present
     pub(crate) async fn get_manifest(&self, manifest_file: &ManifestFile) -> 
Result<Arc<Manifest>> {
-        if self.cache_disabled {
+        let Some(cache) = self.cache() else {
             return ManifestReader::new(self.file_io.clone())
                 .read(manifest_file)
                 .await
                 .map(Arc::new);
-        }
+        };
 
         let key = CachedObjectKey::Manifest(ManifestKey::new(manifest_file));
 
-        let cache_entry = self
-            .cache
+        let cache_entry = cache
             .entry_by_ref(&key)
             .or_try_insert_with(self.fetch_and_parse_manifest(manifest_file))
             .await
@@ -168,7 +167,7 @@ impl ObjectCache {
         snapshot: &SnapshotRef,
         table_metadata: &TableMetadataRef,
     ) -> Result<Arc<ManifestList>> {
-        if self.cache_disabled {
+        let Some(cache) = self.cache() else {
             return ManifestListReader::new(
                 snapshot.clone(),
                 self.file_io.clone(),
@@ -178,11 +177,10 @@ impl ObjectCache {
             .load()
             .await
             .map(Arc::new);
-        }
+        };
 
         let key = 
CachedObjectKey::ManifestList(snapshot.manifest_list().to_string());
-        let cache_entry = self
-            .cache
+        let cache_entry = cache
             .entry_by_ref(&key)
             .or_try_insert_with(self.fetch_and_parse_manifest_list(snapshot, 
table_metadata))
             .await
@@ -425,6 +423,21 @@ mod tests {
         }
     }
 
+    #[test]
+    fn cache_initializes_once_on_first_use() {
+        let original = 
ObjectCache::new_with_capacity(FileIO::new_with_memory(), 1024, None);
+        let cloned = original.clone();
+        let another_clone = original.clone();
+        assert!(original.cache.get().is_none());
+        drop(original);
+        assert!(cloned.cache.get().is_none());
+        assert!(another_clone.cache.get().is_none());
+
+        let cache = cloned.cache().unwrap();
+        assert!(std::ptr::eq(cache, another_clone.cache().unwrap()));
+        assert_eq!(cache.policy().max_capacity(), Some(1024));
+    }
+
     #[tokio::test]
     async fn test_get_manifest_list_and_manifest_from_disabled_cache() {
         let mut fixture = TableTestFixture::new();
@@ -456,6 +469,7 @@ mod tests {
                 .unwrap(),
             "1.parquet"
         );
+        assert!(object_cache.cache.get().is_none());
     }
 
     #[tokio::test]
@@ -464,6 +478,8 @@ mod tests {
         fixture.setup_manifest_files().await;
 
         let object_cache = ObjectCache::new(fixture.table.file_io().clone(), 
None);
+        let cloned = object_cache.clone();
+        assert!(object_cache.cache.get().is_none());
 
         // not in cache
         let result_manifest_list = object_cache
@@ -477,7 +493,8 @@ mod tests {
         assert_eq!(result_manifest_list.entries().len(), 1);
 
         // retrieve cached version
-        let result_manifest_list = object_cache
+        let first_manifest_list = result_manifest_list;
+        let result_manifest_list = cloned
             .get_manifest_list(
                 fixture.table.metadata().current_snapshot().unwrap(),
                 &fixture.table.metadata_ref(),
@@ -485,7 +502,7 @@ mod tests {
             .await
             .unwrap();
 
-        assert_eq!(result_manifest_list.entries().len(), 1);
+        assert!(Arc::ptr_eq(&first_manifest_list, &result_manifest_list));
 
         let manifest_file = result_manifest_list.entries().first().unwrap();
 
@@ -505,19 +522,8 @@ mod tests {
         );
 
         // retrieve cached version
-        let result_manifest = 
object_cache.get_manifest(manifest_file).await.unwrap();
-
-        assert_eq!(
-            result_manifest
-                .entries()
-                .first()
-                .unwrap()
-                .file_path()
-                .split("/")
-                .last()
-                .unwrap(),
-            "1.parquet"
-        );
+        let cached_manifest = 
cloned.get_manifest(manifest_file).await.unwrap();
+        assert!(Arc::ptr_eq(&result_manifest, &cached_manifest));
     }
 
     #[tokio::test]

Reply via email to