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-3670-641f59049e0aefad0c60e19915ecdb54933e002f in repository https://gitbox.apache.org/repos/asf/iceberg-rust.git
commit 219078c9d8d82cdc431af77a430e07c8fe56bd65 Author: Shawn Chang <[email protected]> AuthorDate: Thu Nov 19 15:00:33 2026 +0000 perf(scan): parse manifests concurrently (#3670) * perf(scan): parse manifests concurrently TableScan::plan_files loads manifests from one task spawned on the io runtime, and ManifestReader::read parsed each manifest on that task, so the Avro decoding of every manifest in a snapshot ran one after another while the other workers idled. Planning a 601-manifest table spent about 80% of its time in Manifest::try_from_avro_bytes on a single core. ManifestReader now takes an optional Runtime and runs the parse on its cpu handle, which is what Runtime::cpu is documented for; the fetch stays on the calling io task. The scan passes the table's runtime through ObjectCache::get_manifest, so up to concurrency_limit_manifest_files parses run in parallel. ObjectCache itself stores no runtime, so Table::with_runtime keeps sharing it. Spawning the whole per-manifest future on io() would parallelise but keep CPU work on the io runtime; spawning it on cpu() would run storage IO on a runtime that an engine using iceberg-rust for planning only may build without an IO driver. spawn rather than spawn_blocking keeps the parse within the worker count the embedding engine sized cpu() with, matching how the entry stages in plan_files already spawn their work. A panic or cancellation in a parse surfaces as ErrorKind::Unexpected through JoinHandle, and try_for_each_concurrent stops starting new manifests on the first error, so the plan stream ends with that error exactly as it does for a read error. plan_bench medians (4 workers): SF10 23.9 -> 7.0 ms, SF100 232.9 -> 65.4 ms. (cherry picked from commit ce885c91743e7b6a33c70017ca224173865f758b) * refactor(scan): require a runtime on ManifestReader and name the manifest on JoinError ManifestReader took an Option<Runtime>, which left two parse paths: the spawned one the scan uses and an inline one that catalog::utils' delete_data_files and several tests still took, so manifests read while dropping a table were parsed serially. The runtime is now a constructor argument, with_runtime is gone, and delete_data_files builds its reader from the table. The inline-vs-spawned equivalence test goes with the inline path it compared against. A JoinError from the spawned parse (a panic, or a cpu runtime shut down mid-plan) carried only "spawned task failed"; a parse error already names the manifest. The reader now attaches the manifest path as context, so every failure out of ManifestReader::read names the file. ObjectCache wraps the error with the path too, which is why the scan-level cancellation test passed without this; a reader-level test fails without it. The scan-level test also asserts the path now, matching its corrupt and missing siblings. * refactor(scan): bind the parse runtime to ObjectCache instead of passing it per call ObjectCache::get_manifest took a &Runtime on every call, which threaded a runtime through PlanContext, ManifestFileContext and validate_files_not_live only to hand it to the ManifestReader it builds. The cache now owns the runtime it parses on, taken at construction from the TableBuilder, and get_manifest has its original signature again. Table::with_runtime rebinds the cache through ObjectCache::with_runtime, which clones the moka cache: a moka Cache is a handle to shared storage, so the rebound table keeps every entry the original loaded while its misses parse on the new runtime. The with_runtime test now checks both, by building the table on a runtime it then shuts down: a cache that kept the old runtime fails its first miss, and a cache that did not share storage cannot answer for a manifest list whose file has been removed. * docs(scan): note that manifest reads parse on the table's cpu runtime Table::manifest_reader and ManifestReader::read now say the parse runs on the cpu runtime and fails with ErrorKind::Unexpected once that runtime has shut down. The scan-level cancellation test credits ObjectCache's wrapper for the manifest path, and points to the reader-level test that pins the reader's own context. --- crates/iceberg/src/catalog/utils.rs | 9 ++- crates/iceberg/src/io/object_cache.rs | 51 +++++++++--- crates/iceberg/src/scan/mod.rs | 90 +++++++++++++++++++++- crates/iceberg/src/spec/manifest/reader.rs | 77 +++++++++++++++--- .../src/spec/manifest_list/manifest_file.rs | 20 +++-- crates/iceberg/src/table.rs | 59 +++++++++++--- 6 files changed, 264 insertions(+), 42 deletions(-) diff --git a/crates/iceberg/src/catalog/utils.rs b/crates/iceberg/src/catalog/utils.rs index 3fb9b007d..a1238c63b 100644 --- a/crates/iceberg/src/catalog/utils.rs +++ b/crates/iceberg/src/catalog/utils.rs @@ -23,7 +23,7 @@ use futures::{StreamExt, TryStreamExt, stream}; use crate::Result; use crate::io::FileIO; -use crate::spec::{ManifestFile, ManifestReader, TableMetadata}; +use crate::spec::{ManifestFile, TableMetadata}; use crate::table::Table; const DELETE_CONCURRENCY: usize = 10; @@ -62,7 +62,7 @@ pub async fn drop_table_data(table_info: &Table) -> Result<()> { // Delete data files only if gc.enabled is true, to avoid corrupting shared tables if metadata.table_properties().gc_enabled()? { - delete_data_files(io, &manifests_to_delete).await?; + delete_data_files(table_info, &manifests_to_delete).await?; } // Delete manifest files @@ -145,12 +145,13 @@ pub async fn delete_removed_metadata_files(io: &FileIO, base: &TableMetadata, ne /// Reads manifests concurrently and deletes the data files referenced within. async fn delete_data_files( - io: &FileIO, + table: &Table, manifest_files: &HashMap<String, ManifestFile>, ) -> Result<()> { + let io = table.file_io(); stream::iter(manifest_files.values().map(Ok)) .try_for_each_concurrent(DELETE_CONCURRENCY, |manifest_file| async move { - let manifest = ManifestReader::new(io.clone()).read(manifest_file).await?; + let manifest = table.manifest_reader().read(manifest_file).await?; let data_file_paths = manifest .entries() .iter() diff --git a/crates/iceberg/src/io/object_cache.rs b/crates/iceberg/src/io/object_cache.rs index 37ded3894..e7152096c 100644 --- a/crates/iceberg/src/io/object_cache.rs +++ b/crates/iceberg/src/io/object_cache.rs @@ -20,6 +20,7 @@ use std::sync::{Arc, OnceLock}; use crate::encryption::EncryptionManager; use crate::io::FileIO; +use crate::runtime::Runtime; use crate::spec::{ Manifest, ManifestFile, ManifestList, ManifestListReader, ManifestReader, SnapshotRef, TableMetadataRef, @@ -78,13 +79,24 @@ pub struct ObjectCache { file_io: FileIO, cache_size_bytes: u64, encryption_manager: Option<Arc<EncryptionManager>>, + /// Manifests that miss the cache are parsed on this runtime's cpu handle. + runtime: Runtime, } impl ObjectCache { /// Creates a new [`ObjectCache`] /// with the default cache size - pub(crate) fn new(file_io: FileIO, encryption_manager: Option<Arc<EncryptionManager>>) -> Self { - Self::new_with_capacity(file_io, DEFAULT_CACHE_SIZE_BYTES, encryption_manager) + pub(crate) fn new( + file_io: FileIO, + encryption_manager: Option<Arc<EncryptionManager>>, + runtime: Runtime, + ) -> Self { + Self::new_with_capacity( + file_io, + DEFAULT_CACHE_SIZE_BYTES, + encryption_manager, + runtime, + ) } /// Creates a new [`ObjectCache`] @@ -93,12 +105,14 @@ impl ObjectCache { file_io: FileIO, cache_size_bytes: u64, encryption_manager: Option<Arc<EncryptionManager>>, + runtime: Runtime, ) -> Self { Self { cache: Arc::new(OnceLock::new()), file_io, cache_size_bytes, encryption_manager, + runtime, } } @@ -107,8 +121,19 @@ impl ObjectCache { pub(crate) fn with_disabled_cache( file_io: FileIO, encryption_manager: Option<Arc<EncryptionManager>>, + runtime: Runtime, ) -> Self { - Self::new_with_capacity(file_io, 0, encryption_manager) + Self::new_with_capacity(file_io, 0, encryption_manager, runtime) + } + + /// Returns this cache bound to `runtime`. The returned cache shares its + /// entries with `self`: the moka cache sits behind a shared `Arc`, so + /// cloning neither copies nor drops anything already cached. + pub(crate) fn with_runtime(&self, runtime: Runtime) -> Self { + Self { + runtime, + ..self.clone() + } } fn cache(&self) -> Option<&moka::future::Cache<CachedObjectKey, CachedItem>> { @@ -130,7 +155,7 @@ impl ObjectCache { /// or retrieves one from FileIO and parses it if not present pub(crate) async fn get_manifest(&self, manifest_file: &ManifestFile) -> Result<Arc<Manifest>> { let Some(cache) = self.cache() else { - return ManifestReader::new(self.file_io.clone()) + return ManifestReader::new(self.file_io.clone(), self.runtime.clone()) .read(manifest_file) .await .map(Arc::new); @@ -205,7 +230,7 @@ impl ObjectCache { } async fn fetch_and_parse_manifest(&self, manifest_file: &ManifestFile) -> Result<CachedItem> { - let manifest = ManifestReader::new(self.file_io.clone()) + let manifest = ManifestReader::new(self.file_io.clone(), self.runtime.clone()) .read(manifest_file) .await?; @@ -425,7 +450,8 @@ mod tests { #[test] fn cache_initializes_once_on_first_use() { - let original = ObjectCache::new_with_capacity(FileIO::new_with_memory(), 1024, None); + let original = + ObjectCache::new_with_capacity(FileIO::new_with_memory(), 1024, None, test_runtime()); let cloned = original.clone(); let another_clone = original.clone(); assert!(original.cache.get().is_none()); @@ -443,7 +469,8 @@ mod tests { let mut fixture = TableTestFixture::new(); fixture.setup_manifest_files().await; - let object_cache = ObjectCache::with_disabled_cache(fixture.table.file_io().clone(), None); + let object_cache = + ObjectCache::with_disabled_cache(fixture.table.file_io().clone(), None, test_runtime()); let result_manifest_list = object_cache .get_manifest_list( @@ -477,7 +504,7 @@ mod tests { let mut fixture = TableTestFixture::new(); fixture.setup_manifest_files().await; - let object_cache = ObjectCache::new(fixture.table.file_io().clone(), None); + let object_cache = ObjectCache::new(fixture.table.file_io().clone(), None, test_runtime()); let cloned = object_cache.clone(); assert!(object_cache.cache.get().is_none()); @@ -550,7 +577,7 @@ mod tests { assert!(snapshot_without_schema_id.schema_id().is_none()); assert!(current_snapshot.schema_id().is_some()); - let object_cache = ObjectCache::new(fixture.table.file_io().clone(), None); + let object_cache = ObjectCache::new(fixture.table.file_io().clone(), None, test_runtime()); // Cold miss: the schema-id-less snapshot populates the cache. let inserted = object_cache @@ -591,7 +618,7 @@ mod tests { "setup invariant: the two metadata refs must differ in format version" ); - let object_cache = ObjectCache::new(fixture.table.file_io().clone(), None); + let object_cache = ObjectCache::new(fixture.table.file_io().clone(), None, test_runtime()); // Cold miss under v1 parses the v1 bytes as v1: content defaults to Data and // the sequence number to 0. @@ -671,7 +698,7 @@ mod tests { let mut manifest_file_b = manifest_file; manifest_file_b.first_row_id = Some(2000); - let object_cache = ObjectCache::new(io, None); + let object_cache = ObjectCache::new(io, None, test_runtime()); let manifest_a = object_cache.get_manifest(&manifest_file_a).await.unwrap(); let manifest_b = object_cache.get_manifest(&manifest_file_b).await.unwrap(); @@ -748,7 +775,7 @@ mod tests { let mut retry = manifest_file; retry.sequence_number = 36; - let object_cache = ObjectCache::new(io, None); + let object_cache = ObjectCache::new(io, None, test_runtime()); let first = object_cache.get_manifest(&first_attempt).await.unwrap(); let second = object_cache.get_manifest(&retry).await.unwrap(); diff --git a/crates/iceberg/src/scan/mod.rs b/crates/iceberg/src/scan/mod.rs index c3740911d..ac2730a28 100644 --- a/crates/iceberg/src/scan/mod.rs +++ b/crates/iceberg/src/scan/mod.rs @@ -787,7 +787,7 @@ mod tests { }; use crate::test_utils::test_runtime; use crate::util::snapshot::snapshot_id_as_of_time; - use crate::{ErrorKind, Runtime, TableIdent}; + use crate::{ErrorKind, Result, Runtime, TableIdent}; #[tokio::test] async fn test_table_scan_columns() { @@ -3620,6 +3620,94 @@ mod tests { assert!(result.is_ok(), "Scan timed out - deadlock detected"); } + /// Plans `table` under a timeout so a swallowed manifest error shows up as + /// a timeout instead of a hang, and returns the collected result. + async fn plan_files_with_timeout(table: &Table) -> Result<Vec<FileScanTask>> { + tokio::time::timeout(std::time::Duration::from_secs(5), async { + table + .scan() + .build() + .unwrap() + .plan_files() + .await + .unwrap() + .try_collect::<Vec<_>>() + .await + }) + .await + .expect("plan_files hung instead of reporting the manifest error") + } + + /// Returns the path of the first manifest in the current snapshot. + async fn first_manifest_path(fixture: &TableTestFixture) -> String { + let snapshot = fixture.table.metadata().current_snapshot().unwrap(); + let manifest_list = fixture + .table + .manifest_list_reader(snapshot) + .load() + .await + .unwrap(); + manifest_list.entries()[0].manifest_path.clone() + } + + #[tokio::test] + async fn test_plan_files_reports_corrupt_manifest_as_error() { + let mut fixture = TableTestFixture::new(); + fixture.setup_manifest_files().await; + let path = first_manifest_path(&fixture).await; + fs::write(&path, b"not an avro file").unwrap(); + + let err = plan_files_with_timeout(&fixture.table) + .await + .expect_err("a corrupt manifest must fail the plan"); + assert_eq!(err.kind(), ErrorKind::Unexpected); + assert!(err.to_string().contains(&path), "{err}"); + } + + #[tokio::test] + async fn test_plan_files_reports_missing_manifest_as_error() { + let mut fixture = TableTestFixture::new(); + fixture.setup_manifest_files().await; + let path = first_manifest_path(&fixture).await; + fs::remove_file(&path).unwrap(); + + let err = plan_files_with_timeout(&fixture.table) + .await + .expect_err("a missing manifest must fail the plan"); + assert_eq!(err.kind(), ErrorKind::Unexpected); + assert!(err.to_string().contains(&path), "{err}"); + } + + /// A manifest parse spawned on a shut-down cpu runtime is cancelled, which + /// takes the same `JoinError` path a panicking parse does. The manifest path + /// in the error comes from `ObjectCache`'s "Failed to load manifest" wrapper; + /// `test_read_names_manifest_when_parse_is_cancelled` covers the reader's own + /// context. + #[tokio::test] + async fn test_plan_files_reports_cancelled_manifest_parse_as_error() { + let mut fixture = TableTestFixture::new(); + fixture.setup_manifest_files().await; + let path = first_manifest_path(&fixture).await; + let io_rt = tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + .unwrap(); + let cpu_rt = tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + .unwrap(); + let rt = Runtime::new_with_split(&io_rt, &cpu_rt); + cpu_rt.shutdown_background(); + let table = fixture.table.clone().with_runtime(rt); + + let err = plan_files_with_timeout(&table) + .await + .expect_err("a cancelled manifest parse must fail the plan"); + assert_eq!(err.kind(), ErrorKind::Unexpected); + assert!(err.to_string().contains(&path), "{err}"); + io_rt.shutdown_background(); + } + #[tokio::test] async fn test_select_with_spec_id_column() { let mut fixture = TableTestFixture::new(); diff --git a/crates/iceberg/src/spec/manifest/reader.rs b/crates/iceberg/src/spec/manifest/reader.rs index 14348ca49..d7504f430 100644 --- a/crates/iceberg/src/spec/manifest/reader.rs +++ b/crates/iceberg/src/spec/manifest/reader.rs @@ -19,22 +19,31 @@ use super::Manifest; use crate::encryption::{EncryptedInputFile, StandardKeyMetadata}; use crate::error::{Result, invalid_data}; use crate::io::FileIO; +use crate::runtime::Runtime; use crate::spec::{ManifestContentType, ManifestEntry, ManifestFile}; /// Reads a manifest file referenced by a manifest list entry, transparently /// decrypting it when the entry records key metadata. pub struct ManifestReader { file_io: FileIO, + /// Manifests are parsed on this runtime's cpu handle, so the Avro decoding + /// of many manifests runs in parallel instead of on the calling task. + runtime: Runtime, } impl ManifestReader { - /// Create a manifest reader. - pub(crate) fn new(file_io: FileIO) -> Self { - Self { file_io } + /// Create a manifest reader that parses manifests on `runtime`. + pub(crate) fn new(file_io: FileIO, runtime: Runtime) -> Self { + Self { file_io, runtime } } /// Read, decrypt, parse and return the manifest described by /// `manifest_file`. + /// + /// The file is fetched on the calling task and parsed on the reader's cpu + /// runtime. A parse that panics, or a cpu runtime that has shut down, returns + /// an [`ErrorKind::Unexpected`](crate::ErrorKind::Unexpected) error naming the + /// manifest. pub async fn read(self, manifest_file: &ManifestFile) -> Result<Manifest> { let input_file = self.file_io.new_input(&manifest_file.manifest_path)?; let key_metadata = manifest_file @@ -51,8 +60,15 @@ impl ManifestReader { None => input_file.read().await?, }; - let (metadata, mut entries) = - Manifest::try_from_avro_bytes(&bytes, Some(&manifest_file.manifest_path))?; + let location = manifest_file.manifest_path.clone(); + let (metadata, mut entries) = self + .runtime + .cpu() + .spawn(async move { Manifest::try_from_avro_bytes(&bytes, Some(&location)) }) + .await + // A `JoinError` (the parse panicked, or the cpu runtime shut down) + // names no manifest; a parse error already does. + .map_err(|err| err.with_context("manifest", &manifest_file.manifest_path))??; for entry in &mut entries { entry.inherit_data(manifest_file); @@ -139,6 +155,7 @@ mod tests { DataContentType, DataFile, DataFileBuilder, DataFileFormat, ManifestEntry, ManifestStatus, ManifestWriterBuilder, NestedField, PartitionSpec, PrimitiveType, Schema, Struct, Type, }; + use crate::test_utils::test_runtime; #[tokio::test] async fn test_read_plaintext_manifest_inherits_entries() { @@ -161,7 +178,10 @@ mod tests { // Writing the manifest yields the manifest list entry describing it. let manifest_file = writer.write_manifest_file().await.unwrap(); - let manifest = ManifestReader::new(io).read(&manifest_file).await.unwrap(); + let manifest = ManifestReader::new(io, test_runtime()) + .read(&manifest_file) + .await + .unwrap(); assert_eq!(manifest.entries().len(), 1); assert_eq!( manifest.entries()[0].data_file().file_path(), @@ -202,11 +222,48 @@ mod tests { let mut manifest_file = writer.write_manifest_file().await.unwrap(); manifest_file.sequence_number = 36; - let manifest = ManifestReader::new(io).read(&manifest_file).await.unwrap(); + let manifest = ManifestReader::new(io, test_runtime()) + .read(&manifest_file) + .await + .unwrap(); assert_eq!(manifest.entries()[0].sequence_number(), Some(0)); assert_eq!(manifest.entries()[0].file_sequence_number, Some(0)); } + /// A parse spawned on a shut-down cpu runtime fails with a `JoinError`, + /// which names no file; the reader must add the manifest path itself. + #[tokio::test] + async fn test_read_names_manifest_when_parse_is_cancelled() { + let schema = test_schema(); + let partition_spec = PartitionSpec::builder(schema.clone()) + .with_spec_id(0) + .build() + .unwrap(); + + let io = FileIO::new_with_memory(); + let path = "memory:///table/metadata/cancelled.avro"; + let mut writer = ManifestWriterBuilder::new( + io.new_output(path).unwrap(), + Some(1), + schema.clone(), + partition_spec, + ) + .build_v2_data(); + writer.add_entry(test_entry()).unwrap(); + let manifest_file = writer.write_manifest_file().await.unwrap(); + + let cpu_rt = tokio::runtime::Builder::new_multi_thread().build().unwrap(); + let runtime = Runtime::new(&cpu_rt); + cpu_rt.shutdown_background(); + + let err = ManifestReader::new(io, runtime) + .read(&manifest_file) + .await + .expect_err("a cancelled parse must fail the read"); + assert_eq!(err.kind(), ErrorKind::Unexpected); + assert!(err.to_string().contains(path), "{err}"); + } + #[tokio::test] async fn test_read_encrypted_manifest_roundtrip() { let schema = test_schema(); @@ -234,7 +291,7 @@ mod tests { assert!(manifest_file.key_metadata.is_some()); // Reading with the recorded key metadata must recover the entry. - let manifest = ManifestReader::new(io.clone()) + let manifest = ManifestReader::new(io.clone(), test_runtime()) .read(&manifest_file) .await .unwrap(); @@ -248,7 +305,7 @@ mod tests { let mut plaintext_entry = manifest_file.clone(); plaintext_entry.key_metadata = None; assert!( - ManifestReader::new(io) + ManifestReader::new(io, test_runtime()) .read(&plaintext_entry) .await .is_err(), @@ -308,7 +365,7 @@ mod tests { /// A reader with an unused in-memory `FileIO`, for exercising the pure /// row-id assignment logic without touching storage. fn test_reader() -> ManifestReader { - ManifestReader::new(FileIO::new_with_memory()) + ManifestReader::new(FileIO::new_with_memory(), test_runtime()) } /// Builds a data-file manifest entry with the given status, record count, diff --git a/crates/iceberg/src/spec/manifest_list/manifest_file.rs b/crates/iceberg/src/spec/manifest_list/manifest_file.rs index 24df6d4dc..14d6f7a9a 100644 --- a/crates/iceberg/src/spec/manifest_list/manifest_file.rs +++ b/crates/iceberg/src/spec/manifest_list/manifest_file.rs @@ -204,6 +204,7 @@ mod test { ManifestStatus, ManifestWriterBuilder, NestedField, PartitionSpec, PrimitiveType, Schema, SchemaRef, Type, }; + use crate::test_utils::test_runtime; #[test] fn test_manifest_content_type_default() { @@ -296,7 +297,10 @@ mod test { key_metadata.with_file_length(size) ); - let manifest = ManifestReader::new(io).read(&manifest_file).await.unwrap(); + let manifest = ManifestReader::new(io, test_runtime()) + .read(&manifest_file) + .await + .unwrap(); assert_eq!(manifest.entries().len(), 1); assert_eq!( manifest.entries()[0].file_path(), @@ -325,7 +329,7 @@ mod test { .with_file_length(manifest_file.manifest_length as u64); manifest_file.key_metadata = Some(wrong_key_metadata.encode().unwrap().to_vec()); - let err = ManifestReader::new(io) + let err = ManifestReader::new(io, test_runtime()) .read(&manifest_file) .await .expect_err("read must fail when decrypting with the wrong key"); @@ -351,7 +355,7 @@ mod test { .with_file_length(manifest_file.manifest_length as u64); manifest_file.key_metadata = Some(wrong_aad_metadata.encode().unwrap().to_vec()); - let err = ManifestReader::new(io) + let err = ManifestReader::new(io, test_runtime()) .read(&manifest_file) .await .expect_err("read must fail when decrypting with the wrong AAD prefix"); @@ -388,7 +392,10 @@ mod test { let manifest_file = write_manifest(&io, path).await; assert_eq!(manifest_file.key_metadata, None); - let manifest = ManifestReader::new(io).read(&manifest_file).await.unwrap(); + let manifest = ManifestReader::new(io, test_runtime()) + .read(&manifest_file) + .await + .unwrap(); assert_eq!(manifest.entries().len(), 1); assert_eq!( manifest.entries()[0].file_path(), @@ -410,7 +417,10 @@ mod test { // Stamp a manifest-level first_row_id, as the manifest-list writer would. manifest_file.first_row_id = Some(1000); - let manifest = ManifestReader::new(io).read(&manifest_file).await.unwrap(); + let manifest = ManifestReader::new(io, test_runtime()) + .read(&manifest_file) + .await + .unwrap(); assert_eq!(manifest.entries().len(), 1); assert_eq!(manifest.entries()[0].data_file().first_row_id(), Some(1000)); } diff --git a/crates/iceberg/src/table.rs b/crates/iceberg/src/table.rs index f33c246eb..d2dded58a 100644 --- a/crates/iceberg/src/table.rs +++ b/crates/iceberg/src/table.rs @@ -166,17 +166,20 @@ impl TableBuilder { Arc::new(ObjectCache::with_disabled_cache( file_io.clone(), encryption_manager.clone(), + runtime.clone(), )) } else if let Some(cache_size_bytes) = cache_size_bytes { Arc::new(ObjectCache::new_with_capacity( file_io.clone(), cache_size_bytes, encryption_manager.clone(), + runtime.clone(), )) } else { Arc::new(ObjectCache::new( file_io.clone(), encryption_manager.clone(), + runtime.clone(), )) }; @@ -224,6 +227,7 @@ impl Table { /// Tasks such as scan planning and reads are spawned on `runtime`. A table rebuilt /// through [`Table::builder`] starts with an empty cache. pub fn with_runtime(mut self, runtime: Runtime) -> Self { + self.object_cache = Arc::new(self.object_cache.with_runtime(runtime.clone())); self.runtime = runtime; self } @@ -317,8 +321,13 @@ impl Table { } /// Creates a [`ManifestReader`] for loading manifests referenced by this table. + /// + /// The reader parses manifests on this table's [`Runtime::cpu`] handle, so + /// [`ManifestReader::read`] returns an + /// [`ErrorKind::Unexpected`](crate::ErrorKind::Unexpected) error once that + /// runtime has shut down. pub fn manifest_reader(&self) -> ManifestReader { - ManifestReader::new(self.file_io.clone()) + ManifestReader::new(self.file_io.clone(), self.runtime.clone()) } /// Create a reader for the table. @@ -422,6 +431,7 @@ mod tests { use crate::encryption::SensitiveBytes; use crate::encryption::kms::MemoryKeyManagementClient; use crate::spec::TableProperties; + use crate::test_utils::scan::TableTestFixture; fn load_test_metadata(filename: &str) -> TableMetadata { let path = format!( @@ -506,29 +516,58 @@ mod tests { assert_eq!(table.identifier.name(), "table"); } + /// `with_runtime` must move both the table's own spawns and the object + /// cache's manifest parses onto the new runtime, while the rebound cache + /// keeps serving what the original already loaded. #[tokio::test] async fn test_table_with_runtime_moves_work_and_keeps_object_cache() { - let old = tokio::runtime::Builder::new_current_thread() - .build() - .unwrap(); + let old = tokio::runtime::Builder::new_multi_thread().build().unwrap(); + let mut fixture = TableTestFixture::new(); + fixture.setup_manifest_files().await; + // Built on `old` from the start, so its object cache is bound to `old` + // too; `with_runtime` on a table built elsewhere would not show that. let table = Table::builder() - .metadata(load_test_metadata("TableMetadataV2Valid.json")) - .identifier(TableIdent::from_strs(["ns", "table"]).unwrap()) - .file_io(FileIO::new_with_memory()) + .metadata(fixture.table.metadata().clone()) + .identifier(fixture.table.identifier().clone()) + .file_io(fixture.table.file_io().clone()) .runtime(Runtime::new(&old)) .build() .unwrap(); - // With the old runtime shut down, the spawn below succeeds only if + + // Load the manifest list through the original table so it is cached. + let snapshot = table.metadata().current_snapshot().unwrap().clone(); + let manifest_list = table + .object_cache() + .get_manifest_list(&snapshot, &table.metadata_ref()) + .await + .unwrap(); + // With the old runtime shut down, every spawn below succeeds only if // `rebound` uses the new one. old.shutdown_background(); let rebound = table.clone().with_runtime(Runtime::try_current().unwrap()); - - assert!(Arc::ptr_eq(&table.object_cache(), &rebound.object_cache())); assert_eq!( rebound.runtime().io().spawn(async { 42 }).await.unwrap(), 42 ); + + // The rebound cache parses a manifest it has not seen on the new runtime. + let manifest_file = manifest_list.entries()[0].clone(); + rebound + .object_cache() + .get_manifest(&manifest_file) + .await + .unwrap(); + + // And it still holds the manifest list the original table loaded: with + // the file gone, only a cache hit can answer. + fs::remove_file(snapshot.manifest_list()).unwrap(); + let from_cache = rebound + .object_cache() + .get_manifest_list(&snapshot, &rebound.metadata_ref()) + .await + .unwrap(); + assert!(Arc::ptr_eq(&manifest_list, &from_cache)); } fn make_kms() -> Arc<dyn KeyManagementClient> {
