You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@iceberg.apache.org by "sdd (via GitHub)" <gi...@apache.org> on 2024/07/31 01:30:27 UTC
[PR] Object Cache: caches parsed Manifests and ManifestLists for performance [iceberg-rust]
sdd opened a new pull request, #512:
URL: https://github.com/apache/iceberg-rust/pull/512
This builds on top of the [concurrent scans PR ](https://github.com/apache/iceberg-rust/pull/373) and so needs to be merged after that.
It caches parsed instances of `Manifest` and `ManifestList` objects so that they are not re-fetched and re-parsed if the same object is required in a subsequent scan. Experiments on the test data in my perf testing branch have shown that this can reduce the time taken for `plan_files` to execute a second time from 650ms down to 5ms, even if this involved a different filter predicate.
The cache is an LRU cache implemented using the great [moka](https://github.com/moka-rs/moka) crate. By default the cache size is 32Mb but it can be configured to use any size or be disabled entirely.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Object Cache: caches parsed Manifests and ManifestLists for performance [iceberg-rust]
Posted by "sdd (via GitHub)" <gi...@apache.org>.
sdd commented on code in PR #512:
URL: https://github.com/apache/iceberg-rust/pull/512#discussion_r1720845166
##########
crates/iceberg/src/io/object_cache.rs:
##########
@@ -0,0 +1,161 @@
+// 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.
+
+use std::sync::Arc;
+
+use crate::io::FileIO;
+use crate::spec::{
+ FormatVersion, Manifest, ManifestFile, ManifestList, SchemaId, SnapshotRef, TableMetadataRef,
+};
+use crate::{Error, ErrorKind, Result};
+
+const DEFAULT_CACHE_SIZE_BYTES: u64 = 32 * 1024 * 1024; // 32MB
+
+#[derive(Clone, Debug)]
+pub(crate) enum CachedItem {
+ ManifestList(Arc<ManifestList>),
+ Manifest(Arc<Manifest>),
+}
+
+#[derive(Clone, Debug, Hash, Eq, PartialEq)]
+pub(crate) enum CachedObjectKey {
+ ManifestList((String, FormatVersion, SchemaId)),
+ Manifest(String),
+}
+
+/// Caches metadata objects deserialized from immutable files
+#[derive(Clone, Debug)]
+pub struct ObjectCache {
+ cache: moka::future::Cache<CachedObjectKey, CachedItem>,
+ file_io: FileIO,
+ cache_disabled: bool,
+}
+
+impl ObjectCache {
+ /// Creates a new [`ObjectCache`]
+ /// with the default cache size
+ pub(crate) fn new(file_io: FileIO) -> Self {
+ Self::new_with_capacity(file_io, DEFAULT_CACHE_SIZE_BYTES)
+ }
+
+ /// Creates a new [`ObjectCache`]
+ /// with a specific cache size
+ pub(crate) fn new_with_capacity(file_io: FileIO, cache_size_bytes: u64) -> Self {
+ if cache_size_bytes == 0 {
+ Self::with_disabled_cache(file_io)
+ } else {
+ Self {
+ cache: moka::future::Cache::new(cache_size_bytes),
+ file_io,
+ cache_disabled: false,
+ }
+ }
+ }
+
+ /// Creates a new [`ObjectCache`]
+ /// with caching disabled
+ pub(crate) fn with_disabled_cache(file_io: FileIO) -> Self {
+ Self {
+ cache: moka::future::Cache::new(0),
+ file_io,
+ cache_disabled: true,
+ }
+ }
+
+ /// 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 {
+ return manifest_file
+ .load_manifest(&self.file_io)
+ .await
+ .map(Arc::new);
+ }
+
+ let key = CachedObjectKey::Manifest(manifest_file.manifest_path.clone());
+
+ let cache_entry = self
+ .cache
+ .entry_by_ref(&key)
+ .or_try_insert_with(self.fetch_and_parse_manifest(manifest_file))
+ .await
+ .map_err(|err| Error::new(ErrorKind::Unexpected, err.as_ref().message()))?
Review Comment:
done.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Object Cache: caches parsed Manifests and ManifestLists for performance [iceberg-rust]
Posted by "liurenjie1024 (via GitHub)" <gi...@apache.org>.
liurenjie1024 merged PR #512:
URL: https://github.com/apache/iceberg-rust/pull/512
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Object Cache: caches parsed Manifests and ManifestLists for performance [iceberg-rust]
Posted by "sdd (via GitHub)" <gi...@apache.org>.
sdd commented on code in PR #512:
URL: https://github.com/apache/iceberg-rust/pull/512#discussion_r1712263915
##########
crates/iceberg/src/scan.rs:
##########
@@ -199,298 +256,588 @@ impl<'a> TableScanBuilder<'a> {
field_ids.push(field_id);
}
- Ok(TableScan {
+ let snapshot_bound_predicate = if let Some(ref predicates) = self.filter {
+ Some(predicates.bind(schema.clone(), true)?)
+ } else {
+ None
+ };
+
+ let plan_context = PlanContext {
snapshot,
- file_io: self.table.file_io().clone(),
table_metadata: self.table.metadata_ref(),
- column_names: self.column_names,
- field_ids,
- bound_predicates,
- schema,
- batch_size: self.batch_size,
+ snapshot_schema: schema,
case_sensitive: self.case_sensitive,
- filter: self.filter.map(Arc::new),
+ predicate: self.filter.map(Arc::new),
+ snapshot_bound_predicate: snapshot_bound_predicate.map(Arc::new),
+ object_cache: self.table.object_cache(),
+ field_ids: Arc::new(field_ids),
+ partition_filter_cache: Arc::new(PartitionFilterCache::new()),
+ manifest_evaluator_cache: Arc::new(ManifestEvaluatorCache::new()),
+ expression_evaluator_cache: Arc::new(ExpressionEvaluatorCache::new()),
+ };
+
+ Ok(TableScan {
+ batch_size: self.batch_size,
+ column_names: self.column_names,
+ file_io: self.table.file_io().clone(),
+ plan_context,
+ table_scan_config: self.table_scan_config,
})
}
}
/// Table scan.
#[derive(Debug)]
pub struct TableScan {
- snapshot: SnapshotRef,
- table_metadata: TableMetadataRef,
+ plan_context: PlanContext,
+ batch_size: Option<usize>,
file_io: FileIO,
column_names: Vec<String>,
- field_ids: Vec<i32>,
- bound_predicates: Option<BoundPredicate>,
- schema: SchemaRef,
- batch_size: Option<usize>,
+ table_scan_config: TableScanConfig,
+}
+
+/// PlanContext wraps a [`SnapshotRef`] alongside all the other
+/// objects that are required to perform a scan file plan.
+#[derive(Debug)]
+struct PlanContext {
Review Comment:
This change is no longer in this PR after the rebase
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Object Cache: caches parsed Manifests and ManifestLists for performance [iceberg-rust]
Posted by "sdd (via GitHub)" <gi...@apache.org>.
sdd commented on PR #512:
URL: https://github.com/apache/iceberg-rust/pull/512#issuecomment-2278812113
Thanks for the review @Xuanwo, much appreciated! Back to you, I've addressed your comments.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Object Cache: caches parsed Manifests and ManifestLists for performance [iceberg-rust]
Posted by "dentiny (via GitHub)" <gi...@apache.org>.
dentiny commented on code in PR #512:
URL: https://github.com/apache/iceberg-rust/pull/512#discussion_r2365940293
##########
crates/iceberg/src/scan.rs:
##########
@@ -477,24 +478,22 @@ impl ManifestFileContext {
/// streaming its constituent [`ManifestEntries`] to the channel provided in the context
async fn fetch_manifest_and_stream_manifest_entries(self) -> Result<()> {
let ManifestFileContext {
- file_io,
+ object_cache,
manifest_file,
bound_predicates,
snapshot_schema,
field_ids,
- expression_evaluator_cache,
mut sender,
+ expression_evaluator_cache,
..
} = self;
- let file_io_cloned = file_io.clone();
- let manifest = manifest_file.load_manifest(&file_io_cloned).await?;
-
- let (entries, _) = manifest.consume();
+ let manifest = object_cache.get_manifest(&manifest_file).await?;
Review Comment:
I'm actually curious why do we take lookaside cache design, instead of read-through/write-through cache?
The benefit for later is when you write a new manifest list, you store it in object cache directly, so next read you don't need to fetch it again (which is [moonlink's](https://github.com/Mooncake-Labs/moonlink) usage).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Object Cache: caches parsed Manifests and ManifestLists for performance [iceberg-rust]
Posted by "sdd (via GitHub)" <gi...@apache.org>.
sdd commented on code in PR #512:
URL: https://github.com/apache/iceberg-rust/pull/512#discussion_r1721277607
##########
crates/iceberg/src/io/object_cache.rs:
##########
@@ -0,0 +1,396 @@
+// 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.
+
+use std::sync::Arc;
+
+use crate::io::FileIO;
+use crate::spec::{
+ FormatVersion, Manifest, ManifestFile, ManifestList, SchemaId, SnapshotRef, TableMetadataRef,
+};
+use crate::{Error, ErrorKind, Result};
+
+const DEFAULT_CACHE_SIZE_BYTES: u64 = 32 * 1024 * 1024; // 32MB
+
+#[derive(Clone, Debug)]
+pub(crate) enum CachedItem {
+ ManifestList(Arc<ManifestList>),
+ Manifest(Arc<Manifest>),
+}
+
+#[derive(Clone, Debug, Hash, Eq, PartialEq)]
+pub(crate) enum CachedObjectKey {
+ ManifestList((String, FormatVersion, SchemaId)),
+ Manifest(String),
+}
+
+/// Caches metadata objects deserialized from immutable files
+#[derive(Clone, Debug)]
+pub struct ObjectCache {
+ cache: moka::future::Cache<CachedObjectKey, CachedItem>,
+ file_io: FileIO,
+ cache_disabled: bool,
+}
+
+impl ObjectCache {
+ /// Creates a new [`ObjectCache`]
+ /// with the default cache size
+ pub(crate) fn new(file_io: FileIO) -> Self {
+ Self::new_with_capacity(file_io, DEFAULT_CACHE_SIZE_BYTES)
+ }
+
+ /// Creates a new [`ObjectCache`]
+ /// with a specific cache size
+ pub(crate) fn new_with_capacity(file_io: FileIO, cache_size_bytes: u64) -> Self {
+ if cache_size_bytes == 0 {
+ Self::with_disabled_cache(file_io)
+ } else {
+ Self {
+ cache: moka::future::Cache::new(cache_size_bytes),
+ file_io,
+ cache_disabled: false,
+ }
+ }
+ }
+
+ /// Creates a new [`ObjectCache`]
+ /// with caching disabled
+ pub(crate) fn with_disabled_cache(file_io: FileIO) -> Self {
+ Self {
+ cache: moka::future::Cache::new(0),
+ file_io,
+ cache_disabled: true,
+ }
+ }
+
+ /// 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 {
+ return manifest_file
+ .load_manifest(&self.file_io)
+ .await
+ .map(Arc::new);
+ }
+
+ let key = CachedObjectKey::Manifest(manifest_file.manifest_path.clone());
+
+ let cache_entry = self
+ .cache
+ .entry_by_ref(&key)
+ .or_try_insert_with(self.fetch_and_parse_manifest(manifest_file))
+ .await
+ .map_err(|err| {
+ Error::new(
+ ErrorKind::Unexpected,
+ format!("Failed to load manifest {}", manifest_file.manifest_path),
+ )
+ .with_source(err)
+ })?
+ .into_value();
+
+ match cache_entry {
+ CachedItem::Manifest(arc_manifest) => Ok(arc_manifest),
+ _ => Err(Error::new(
+ ErrorKind::Unexpected,
+ format!("cached object for key '{:?}' is not a Manifest", key),
+ )),
+ }
+ }
+
+ /// Retrieves an Arc [`ManifestList`] from the cache
+ /// or retrieves one from FileIO and parses it if not present
+ pub(crate) async fn get_manifest_list(
+ &self,
+ snapshot: &SnapshotRef,
+ table_metadata: &TableMetadataRef,
+ ) -> Result<Arc<ManifestList>> {
+ if self.cache_disabled {
+ return snapshot
+ .load_manifest_list(&self.file_io, table_metadata)
+ .await
+ .map(Arc::new);
+ }
+
+ let key = CachedObjectKey::ManifestList((
+ snapshot.manifest_list().to_string(),
+ table_metadata.format_version,
+ snapshot.schema_id().unwrap(),
+ ));
+ let cache_entry = self
+ .cache
+ .entry_by_ref(&key)
+ .or_try_insert_with(self.fetch_and_parse_manifest_list(snapshot, table_metadata))
+ .await
+ .map_err(|err| Error::new(ErrorKind::Unexpected, err.as_ref().message()))?
+ .into_value();
+
+ match cache_entry {
+ CachedItem::ManifestList(arc_manifest_list) => Ok(arc_manifest_list),
+ _ => Err(Error::new(
+ ErrorKind::Unexpected,
+ format!("cached object for path '{:?}' is not a manifest list", key),
+ )),
+ }
+ }
+
+ async fn fetch_and_parse_manifest(&self, manifest_file: &ManifestFile) -> Result<CachedItem> {
+ let manifest = manifest_file.load_manifest(&self.file_io).await?;
+
+ Ok(CachedItem::Manifest(Arc::new(manifest)))
+ }
+
+ async fn fetch_and_parse_manifest_list(
+ &self,
+ snapshot: &SnapshotRef,
+ table_metadata: &TableMetadataRef,
+ ) -> Result<CachedItem> {
+ let manifest_list = snapshot
+ .load_manifest_list(&self.file_io, table_metadata)
+ .await?;
+
+ Ok(CachedItem::ManifestList(Arc::new(manifest_list)))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::fs;
+
+ use tempfile::TempDir;
+ use tera::{Context, Tera};
+ use uuid::Uuid;
+
+ use super::*;
+ use crate::io::{FileIO, OutputFile};
+ use crate::spec::{
+ DataContentType, DataFileBuilder, DataFileFormat, FormatVersion, Literal, Manifest,
+ ManifestContentType, ManifestEntry, ManifestListWriter, ManifestMetadata, ManifestStatus,
+ ManifestWriter, Struct, TableMetadata, EMPTY_SNAPSHOT_ID,
+ };
+ use crate::table::Table;
+ use crate::TableIdent;
+
+ struct TableTestFixture {
+ table_location: String,
+ table: Table,
+ }
+
+ impl TableTestFixture {
+ fn new() -> Self {
+ let tmp_dir = TempDir::new().unwrap();
+ let table_location = tmp_dir.path().join("table1");
+ let manifest_list1_location = table_location.join("metadata/manifests_list_1.avro");
+ let manifest_list2_location = table_location.join("metadata/manifests_list_2.avro");
+ let table_metadata1_location = table_location.join("metadata/v1.json");
+
+ let file_io = FileIO::from_path(table_location.as_os_str().to_str().unwrap())
+ .unwrap()
+ .build()
+ .unwrap();
+
+ let table_metadata = {
+ let template_json_str = fs::read_to_string(format!(
+ "{}/testdata/example_table_metadata_v2.json",
+ env!("CARGO_MANIFEST_DIR")
+ ))
+ .unwrap();
+ let mut context = Context::new();
+ context.insert("table_location", &table_location);
+ context.insert("manifest_list_1_location", &manifest_list1_location);
+ context.insert("manifest_list_2_location", &manifest_list2_location);
+ context.insert("table_metadata_1_location", &table_metadata1_location);
+
+ let metadata_json = Tera::one_off(&template_json_str, &context, false).unwrap();
+ serde_json::from_str::<TableMetadata>(&metadata_json).unwrap()
+ };
+
+ let table = Table::builder()
+ .metadata(table_metadata)
+ .identifier(TableIdent::from_strs(["db", "table1"]).unwrap())
+ .file_io(file_io.clone())
+ .metadata_location(table_metadata1_location.as_os_str().to_str().unwrap())
+ .build()
+ .unwrap();
+
+ Self {
+ table_location: table_location.to_str().unwrap().to_string(),
+ table,
+ }
+ }
+
+ fn next_manifest_file(&self) -> OutputFile {
+ self.table
+ .file_io()
+ .new_output(format!(
+ "{}/metadata/manifest_{}.avro",
+ self.table_location,
+ Uuid::new_v4()
+ ))
+ .unwrap()
+ }
+
+ async fn setup_manifest_files(&mut self) {
+ let current_snapshot = self.table.metadata().current_snapshot().unwrap();
+ let current_schema = current_snapshot.schema(self.table.metadata()).unwrap();
+ let current_partition_spec = self.table.metadata().default_partition_spec().unwrap();
+
+ // Write data files
+ let data_file_manifest = ManifestWriter::new(
+ self.next_manifest_file(),
+ current_snapshot.snapshot_id(),
+ vec![],
+ )
+ .write(Manifest::new(
+ ManifestMetadata::builder()
+ .schema((*current_schema).clone())
+ .content(ManifestContentType::Data)
+ .format_version(FormatVersion::V2)
+ .partition_spec((**current_partition_spec).clone())
+ .schema_id(current_schema.schema_id())
+ .build(),
+ vec![ManifestEntry::builder()
+ .status(ManifestStatus::Added)
+ .data_file(
+ DataFileBuilder::default()
+ .content(DataContentType::Data)
+ .file_path(format!("{}/1.parquet", &self.table_location))
+ .file_format(DataFileFormat::Parquet)
+ .file_size_in_bytes(100)
+ .record_count(1)
+ .partition(Struct::from_iter([Some(Literal::long(100))]))
+ .build()
+ .unwrap(),
+ )
+ .build()],
+ ))
+ .await
+ .unwrap();
+
+ // Write to manifest list
+ let mut manifest_list_write = ManifestListWriter::v2(
+ self.table
+ .file_io()
+ .new_output(current_snapshot.manifest_list())
+ .unwrap(),
+ current_snapshot.snapshot_id(),
+ current_snapshot
+ .parent_snapshot_id()
+ .unwrap_or(EMPTY_SNAPSHOT_ID),
+ current_snapshot.sequence_number(),
+ );
+ manifest_list_write
+ .add_manifests(vec![data_file_manifest].into_iter())
+ .unwrap();
+ manifest_list_write.close().await.unwrap();
+ }
+ }
+
+ #[tokio::test]
+ async fn test_get_manifest_list_and_manifest_from_disabled_cache() {
+ let mut fixture = TableTestFixture::new();
+ fixture.setup_manifest_files().await;
+
+ let object_cache = ObjectCache::with_disabled_cache(fixture.table.file_io().clone());
Review Comment:
(Fix is on L343 rather than here)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Object Cache: caches parsed Manifests and ManifestLists for performance [iceberg-rust]
Posted by "dentiny (via GitHub)" <gi...@apache.org>.
dentiny commented on code in PR #512:
URL: https://github.com/apache/iceberg-rust/pull/512#discussion_r2365940293
##########
crates/iceberg/src/scan.rs:
##########
@@ -477,24 +478,22 @@ impl ManifestFileContext {
/// streaming its constituent [`ManifestEntries`] to the channel provided in the context
async fn fetch_manifest_and_stream_manifest_entries(self) -> Result<()> {
let ManifestFileContext {
- file_io,
+ object_cache,
manifest_file,
bound_predicates,
snapshot_schema,
field_ids,
- expression_evaluator_cache,
mut sender,
+ expression_evaluator_cache,
..
} = self;
- let file_io_cloned = file_io.clone();
- let manifest = manifest_file.load_manifest(&file_io_cloned).await?;
-
- let (entries, _) = manifest.consume();
+ let manifest = object_cache.get_manifest(&manifest_file).await?;
Review Comment:
I'm actually curious why do we take lookaside cache design, instead of read-through/write-through cache?
The benefit for later is when you write a new manifest list, you store it in object cache directly, so next read you don't need to fetch it again (which is moonlink's usage).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Object Cache: caches parsed Manifests and ManifestLists for performance [iceberg-rust]
Posted by "sdd (via GitHub)" <gi...@apache.org>.
sdd commented on code in PR #512:
URL: https://github.com/apache/iceberg-rust/pull/512#discussion_r1721285997
##########
crates/iceberg/src/io/object_cache.rs:
##########
@@ -0,0 +1,396 @@
+// 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.
+
+use std::sync::Arc;
+
+use crate::io::FileIO;
+use crate::spec::{
+ FormatVersion, Manifest, ManifestFile, ManifestList, SchemaId, SnapshotRef, TableMetadataRef,
+};
+use crate::{Error, ErrorKind, Result};
+
+const DEFAULT_CACHE_SIZE_BYTES: u64 = 32 * 1024 * 1024; // 32MB
+
+#[derive(Clone, Debug)]
+pub(crate) enum CachedItem {
+ ManifestList(Arc<ManifestList>),
+ Manifest(Arc<Manifest>),
+}
+
+#[derive(Clone, Debug, Hash, Eq, PartialEq)]
+pub(crate) enum CachedObjectKey {
+ ManifestList((String, FormatVersion, SchemaId)),
+ Manifest(String),
+}
+
+/// Caches metadata objects deserialized from immutable files
+#[derive(Clone, Debug)]
+pub struct ObjectCache {
+ cache: moka::future::Cache<CachedObjectKey, CachedItem>,
+ file_io: FileIO,
+ cache_disabled: bool,
+}
+
+impl ObjectCache {
+ /// Creates a new [`ObjectCache`]
+ /// with the default cache size
+ pub(crate) fn new(file_io: FileIO) -> Self {
+ Self::new_with_capacity(file_io, DEFAULT_CACHE_SIZE_BYTES)
+ }
+
+ /// Creates a new [`ObjectCache`]
+ /// with a specific cache size
+ pub(crate) fn new_with_capacity(file_io: FileIO, cache_size_bytes: u64) -> Self {
Review Comment:
Oops - that was not quite right. I was getting the size of the `Arc`, not the object within. Fixed:
https://github.com/apache/iceberg-rust/blob/f184c970e9efdef7c68da8127591965fd80d08a0/crates/iceberg/src/io/object_cache.rs#L62-L68
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Object Cache: caches parsed Manifests and ManifestLists for performance [iceberg-rust]
Posted by "liurenjie1024 (via GitHub)" <gi...@apache.org>.
liurenjie1024 commented on code in PR #512:
URL: https://github.com/apache/iceberg-rust/pull/512#discussion_r1720892585
##########
crates/iceberg/src/io/object_cache.rs:
##########
@@ -0,0 +1,396 @@
+// 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.
+
+use std::sync::Arc;
+
+use crate::io::FileIO;
+use crate::spec::{
+ FormatVersion, Manifest, ManifestFile, ManifestList, SchemaId, SnapshotRef, TableMetadataRef,
+};
+use crate::{Error, ErrorKind, Result};
+
+const DEFAULT_CACHE_SIZE_BYTES: u64 = 32 * 1024 * 1024; // 32MB
+
+#[derive(Clone, Debug)]
+pub(crate) enum CachedItem {
+ ManifestList(Arc<ManifestList>),
+ Manifest(Arc<Manifest>),
+}
+
+#[derive(Clone, Debug, Hash, Eq, PartialEq)]
+pub(crate) enum CachedObjectKey {
+ ManifestList((String, FormatVersion, SchemaId)),
+ Manifest(String),
+}
+
+/// Caches metadata objects deserialized from immutable files
+#[derive(Clone, Debug)]
+pub struct ObjectCache {
+ cache: moka::future::Cache<CachedObjectKey, CachedItem>,
+ file_io: FileIO,
+ cache_disabled: bool,
+}
+
+impl ObjectCache {
+ /// Creates a new [`ObjectCache`]
+ /// with the default cache size
+ pub(crate) fn new(file_io: FileIO) -> Self {
+ Self::new_with_capacity(file_io, DEFAULT_CACHE_SIZE_BYTES)
+ }
+
+ /// Creates a new [`ObjectCache`]
+ /// with a specific cache size
+ pub(crate) fn new_with_capacity(file_io: FileIO, cache_size_bytes: u64) -> Self {
+ if cache_size_bytes == 0 {
+ Self::with_disabled_cache(file_io)
+ } else {
+ Self {
+ cache: moka::future::Cache::new(cache_size_bytes),
+ file_io,
+ cache_disabled: false,
+ }
+ }
+ }
+
+ /// Creates a new [`ObjectCache`]
+ /// with caching disabled
+ pub(crate) fn with_disabled_cache(file_io: FileIO) -> Self {
+ Self {
+ cache: moka::future::Cache::new(0),
+ file_io,
+ cache_disabled: true,
+ }
+ }
+
+ /// 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 {
+ return manifest_file
+ .load_manifest(&self.file_io)
+ .await
+ .map(Arc::new);
+ }
+
+ let key = CachedObjectKey::Manifest(manifest_file.manifest_path.clone());
+
+ let cache_entry = self
+ .cache
+ .entry_by_ref(&key)
+ .or_try_insert_with(self.fetch_and_parse_manifest(manifest_file))
+ .await
+ .map_err(|err| {
+ Error::new(
+ ErrorKind::Unexpected,
+ format!("Failed to load manifest {}", manifest_file.manifest_path),
+ )
+ .with_source(err)
+ })?
+ .into_value();
+
+ match cache_entry {
+ CachedItem::Manifest(arc_manifest) => Ok(arc_manifest),
+ _ => Err(Error::new(
+ ErrorKind::Unexpected,
+ format!("cached object for key '{:?}' is not a Manifest", key),
+ )),
+ }
+ }
+
+ /// Retrieves an Arc [`ManifestList`] from the cache
+ /// or retrieves one from FileIO and parses it if not present
+ pub(crate) async fn get_manifest_list(
+ &self,
+ snapshot: &SnapshotRef,
+ table_metadata: &TableMetadataRef,
+ ) -> Result<Arc<ManifestList>> {
+ if self.cache_disabled {
+ return snapshot
+ .load_manifest_list(&self.file_io, table_metadata)
+ .await
+ .map(Arc::new);
+ }
+
+ let key = CachedObjectKey::ManifestList((
+ snapshot.manifest_list().to_string(),
+ table_metadata.format_version,
+ snapshot.schema_id().unwrap(),
+ ));
+ let cache_entry = self
+ .cache
+ .entry_by_ref(&key)
+ .or_try_insert_with(self.fetch_and_parse_manifest_list(snapshot, table_metadata))
+ .await
+ .map_err(|err| Error::new(ErrorKind::Unexpected, err.as_ref().message()))?
+ .into_value();
+
+ match cache_entry {
+ CachedItem::ManifestList(arc_manifest_list) => Ok(arc_manifest_list),
+ _ => Err(Error::new(
+ ErrorKind::Unexpected,
+ format!("cached object for path '{:?}' is not a manifest list", key),
+ )),
+ }
+ }
+
+ async fn fetch_and_parse_manifest(&self, manifest_file: &ManifestFile) -> Result<CachedItem> {
+ let manifest = manifest_file.load_manifest(&self.file_io).await?;
+
+ Ok(CachedItem::Manifest(Arc::new(manifest)))
+ }
+
+ async fn fetch_and_parse_manifest_list(
+ &self,
+ snapshot: &SnapshotRef,
+ table_metadata: &TableMetadataRef,
+ ) -> Result<CachedItem> {
+ let manifest_list = snapshot
+ .load_manifest_list(&self.file_io, table_metadata)
+ .await?;
+
+ Ok(CachedItem::ManifestList(Arc::new(manifest_list)))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::fs;
+
+ use tempfile::TempDir;
+ use tera::{Context, Tera};
+ use uuid::Uuid;
+
+ use super::*;
+ use crate::io::{FileIO, OutputFile};
+ use crate::spec::{
+ DataContentType, DataFileBuilder, DataFileFormat, FormatVersion, Literal, Manifest,
+ ManifestContentType, ManifestEntry, ManifestListWriter, ManifestMetadata, ManifestStatus,
+ ManifestWriter, Struct, TableMetadata, EMPTY_SNAPSHOT_ID,
+ };
+ use crate::table::Table;
+ use crate::TableIdent;
+
+ struct TableTestFixture {
+ table_location: String,
+ table: Table,
+ }
+
+ impl TableTestFixture {
+ fn new() -> Self {
+ let tmp_dir = TempDir::new().unwrap();
+ let table_location = tmp_dir.path().join("table1");
+ let manifest_list1_location = table_location.join("metadata/manifests_list_1.avro");
+ let manifest_list2_location = table_location.join("metadata/manifests_list_2.avro");
+ let table_metadata1_location = table_location.join("metadata/v1.json");
+
+ let file_io = FileIO::from_path(table_location.as_os_str().to_str().unwrap())
+ .unwrap()
+ .build()
+ .unwrap();
+
+ let table_metadata = {
+ let template_json_str = fs::read_to_string(format!(
+ "{}/testdata/example_table_metadata_v2.json",
+ env!("CARGO_MANIFEST_DIR")
+ ))
+ .unwrap();
+ let mut context = Context::new();
+ context.insert("table_location", &table_location);
+ context.insert("manifest_list_1_location", &manifest_list1_location);
+ context.insert("manifest_list_2_location", &manifest_list2_location);
+ context.insert("table_metadata_1_location", &table_metadata1_location);
+
+ let metadata_json = Tera::one_off(&template_json_str, &context, false).unwrap();
+ serde_json::from_str::<TableMetadata>(&metadata_json).unwrap()
+ };
+
+ let table = Table::builder()
+ .metadata(table_metadata)
+ .identifier(TableIdent::from_strs(["db", "table1"]).unwrap())
+ .file_io(file_io.clone())
+ .metadata_location(table_metadata1_location.as_os_str().to_str().unwrap())
+ .build()
+ .unwrap();
+
+ Self {
+ table_location: table_location.to_str().unwrap().to_string(),
+ table,
+ }
+ }
+
+ fn next_manifest_file(&self) -> OutputFile {
+ self.table
+ .file_io()
+ .new_output(format!(
+ "{}/metadata/manifest_{}.avro",
+ self.table_location,
+ Uuid::new_v4()
+ ))
+ .unwrap()
+ }
+
+ async fn setup_manifest_files(&mut self) {
+ let current_snapshot = self.table.metadata().current_snapshot().unwrap();
+ let current_schema = current_snapshot.schema(self.table.metadata()).unwrap();
+ let current_partition_spec = self.table.metadata().default_partition_spec().unwrap();
+
+ // Write data files
+ let data_file_manifest = ManifestWriter::new(
+ self.next_manifest_file(),
+ current_snapshot.snapshot_id(),
+ vec![],
+ )
+ .write(Manifest::new(
+ ManifestMetadata::builder()
+ .schema((*current_schema).clone())
+ .content(ManifestContentType::Data)
+ .format_version(FormatVersion::V2)
+ .partition_spec((**current_partition_spec).clone())
+ .schema_id(current_schema.schema_id())
+ .build(),
+ vec![ManifestEntry::builder()
+ .status(ManifestStatus::Added)
+ .data_file(
+ DataFileBuilder::default()
+ .content(DataContentType::Data)
+ .file_path(format!("{}/1.parquet", &self.table_location))
+ .file_format(DataFileFormat::Parquet)
+ .file_size_in_bytes(100)
+ .record_count(1)
+ .partition(Struct::from_iter([Some(Literal::long(100))]))
+ .build()
+ .unwrap(),
+ )
+ .build()],
+ ))
+ .await
+ .unwrap();
+
+ // Write to manifest list
+ let mut manifest_list_write = ManifestListWriter::v2(
+ self.table
+ .file_io()
+ .new_output(current_snapshot.manifest_list())
+ .unwrap(),
+ current_snapshot.snapshot_id(),
+ current_snapshot
+ .parent_snapshot_id()
+ .unwrap_or(EMPTY_SNAPSHOT_ID),
+ current_snapshot.sequence_number(),
+ );
+ manifest_list_write
+ .add_manifests(vec![data_file_manifest].into_iter())
+ .unwrap();
+ manifest_list_write.close().await.unwrap();
+ }
+ }
+
+ #[tokio::test]
+ async fn test_get_manifest_list_and_manifest_from_disabled_cache() {
+ let mut fixture = TableTestFixture::new();
+ fixture.setup_manifest_files().await;
+
+ let object_cache = ObjectCache::with_disabled_cache(fixture.table.file_io().clone());
Review Comment:
```suggestion
let object_cache = ObjectCache::new(fixture.table.file_io().clone());
```
##########
crates/iceberg/src/io/object_cache.rs:
##########
@@ -0,0 +1,396 @@
+// 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.
+
+use std::sync::Arc;
+
+use crate::io::FileIO;
+use crate::spec::{
+ FormatVersion, Manifest, ManifestFile, ManifestList, SchemaId, SnapshotRef, TableMetadataRef,
+};
+use crate::{Error, ErrorKind, Result};
+
+const DEFAULT_CACHE_SIZE_BYTES: u64 = 32 * 1024 * 1024; // 32MB
+
+#[derive(Clone, Debug)]
+pub(crate) enum CachedItem {
+ ManifestList(Arc<ManifestList>),
+ Manifest(Arc<Manifest>),
+}
+
+#[derive(Clone, Debug, Hash, Eq, PartialEq)]
+pub(crate) enum CachedObjectKey {
+ ManifestList((String, FormatVersion, SchemaId)),
+ Manifest(String),
+}
+
+/// Caches metadata objects deserialized from immutable files
+#[derive(Clone, Debug)]
+pub struct ObjectCache {
+ cache: moka::future::Cache<CachedObjectKey, CachedItem>,
+ file_io: FileIO,
+ cache_disabled: bool,
+}
+
+impl ObjectCache {
+ /// Creates a new [`ObjectCache`]
+ /// with the default cache size
+ pub(crate) fn new(file_io: FileIO) -> Self {
+ Self::new_with_capacity(file_io, DEFAULT_CACHE_SIZE_BYTES)
+ }
+
+ /// Creates a new [`ObjectCache`]
+ /// with a specific cache size
+ pub(crate) fn new_with_capacity(file_io: FileIO, cache_size_bytes: u64) -> Self {
Review Comment:
```suggestion
pub(crate) fn new_with_capacity(file_io: FileIO, max_cached_object_num: u64) -> Self {
```
According to `moka`'s doc, I think this is number of cached entries, rather bytes.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Object Cache: caches parsed Manifests and ManifestLists for performance [iceberg-rust]
Posted by "liurenjie1024 (via GitHub)" <gi...@apache.org>.
liurenjie1024 commented on code in PR #512:
URL: https://github.com/apache/iceberg-rust/pull/512#discussion_r1720891166
##########
crates/iceberg/src/io/object_cache.rs:
##########
@@ -0,0 +1,161 @@
+// 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.
+
+use std::sync::Arc;
+
+use crate::io::FileIO;
+use crate::spec::{
+ FormatVersion, Manifest, ManifestFile, ManifestList, SchemaId, SnapshotRef, TableMetadataRef,
+};
+use crate::{Error, ErrorKind, Result};
+
+const DEFAULT_CACHE_SIZE_BYTES: u64 = 32 * 1024 * 1024; // 32MB
+
+#[derive(Clone, Debug)]
+pub(crate) enum CachedItem {
+ ManifestList(Arc<ManifestList>),
+ Manifest(Arc<Manifest>),
+}
+
+#[derive(Clone, Debug, Hash, Eq, PartialEq)]
+pub(crate) enum CachedObjectKey {
+ ManifestList((String, FormatVersion, SchemaId)),
Review Comment:
I did some test and found that when we upgrade table format version, or alter table schema, the java version will create new snapshot, but not updating manifest list. I think this is a bug and java implementation is not strictly followig spec. For example, when we upgrade table format version from v1 to v2, we are expecting manifest list file is also v2, but it's still v1, and we can't parse it using v2 parser. Java's implementation doesn't strictly require this. Similar things happen to schema evolution. For example, if we remove a column, and the `partition_type` will return an error.
Thanks for this explaination, I agree that we should keep this as a workaround for the potential bug.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Object Cache: caches parsed Manifests and ManifestLists for performance [iceberg-rust]
Posted by "liurenjie1024 (via GitHub)" <gi...@apache.org>.
liurenjie1024 commented on code in PR #512:
URL: https://github.com/apache/iceberg-rust/pull/512#discussion_r2367372962
##########
crates/iceberg/src/scan.rs:
##########
@@ -477,24 +478,22 @@ impl ManifestFileContext {
/// streaming its constituent [`ManifestEntries`] to the channel provided in the context
async fn fetch_manifest_and_stream_manifest_entries(self) -> Result<()> {
let ManifestFileContext {
- file_io,
+ object_cache,
manifest_file,
bound_predicates,
snapshot_schema,
field_ids,
- expression_evaluator_cache,
mut sender,
+ expression_evaluator_cache,
..
} = self;
- let file_io_cloned = file_io.clone();
- let manifest = manifest_file.load_manifest(&file_io_cloned).await?;
-
- let (entries, _) = manifest.consume();
+ let manifest = object_cache.get_manifest(&manifest_file).await?;
Review Comment:
I'm not sure about the details but I guess it's to be compatible with no cache use case?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Object Cache: caches parsed Manifests and ManifestLists for performance [iceberg-rust]
Posted by "sdd (via GitHub)" <gi...@apache.org>.
sdd commented on code in PR #512:
URL: https://github.com/apache/iceberg-rust/pull/512#discussion_r2367635557
##########
crates/iceberg/src/scan.rs:
##########
@@ -477,24 +478,22 @@ impl ManifestFileContext {
/// streaming its constituent [`ManifestEntries`] to the channel provided in the context
async fn fetch_manifest_and_stream_manifest_entries(self) -> Result<()> {
let ManifestFileContext {
- file_io,
+ object_cache,
manifest_file,
bound_predicates,
snapshot_schema,
field_ids,
- expression_evaluator_cache,
mut sender,
+ expression_evaluator_cache,
..
} = self;
- let file_io_cloned = file_io.clone();
- let manifest = manifest_file.load_manifest(&file_io_cloned).await?;
-
- let (entries, _) = manifest.consume();
+ let manifest = object_cache.get_manifest(&manifest_file).await?;
Review Comment:
I think this was just because we were not writing yet at the time, only reading? It was a long time ago, my memory is hazy
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Object Cache: caches parsed Manifests and ManifestLists for performance [iceberg-rust]
Posted by "sdd (via GitHub)" <gi...@apache.org>.
sdd commented on PR #512:
URL: https://github.com/apache/iceberg-rust/pull/512#issuecomment-2277772962
Sure, will do so in a few hours time
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Object Cache: caches parsed Manifests and ManifestLists for performance [iceberg-rust]
Posted by "sdd (via GitHub)" <gi...@apache.org>.
sdd commented on code in PR #512:
URL: https://github.com/apache/iceberg-rust/pull/512#discussion_r1712256232
##########
crates/iceberg/src/io/object_cache.rs:
##########
@@ -0,0 +1,161 @@
+// 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.
+
+use std::sync::Arc;
+
+use crate::io::FileIO;
+use crate::spec::{
+ FormatVersion, Manifest, ManifestFile, ManifestList, SchemaId, SnapshotRef, TableMetadataRef,
+};
+use crate::{Error, ErrorKind, Result};
+
+const DEFAULT_CACHE_SIZE_BYTES: u64 = 2 ^ 15; // 32MB
+
+#[derive(Clone, Debug)]
+pub(crate) enum CachedItem {
+ ManifestList(Arc<ManifestList>),
+ Manifest(Arc<Manifest>),
+}
+
+#[derive(Clone, Debug, Hash, Eq, PartialEq)]
+pub(crate) enum CachedObjectKey {
+ ManifestList((String, FormatVersion, SchemaId)),
+ Manifest(String),
+}
+
+/// Caches metadata objects deserialized from immutable files
+#[derive(Clone, Debug)]
+pub struct ObjectCache {
Review Comment:
Sounds good - look forwards to hearing about it!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Object Cache: caches parsed Manifests and ManifestLists for performance [iceberg-rust]
Posted by "sdd (via GitHub)" <gi...@apache.org>.
sdd commented on code in PR #512:
URL: https://github.com/apache/iceberg-rust/pull/512#discussion_r1721276668
##########
crates/iceberg/src/io/object_cache.rs:
##########
@@ -0,0 +1,396 @@
+// 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.
+
+use std::sync::Arc;
+
+use crate::io::FileIO;
+use crate::spec::{
+ FormatVersion, Manifest, ManifestFile, ManifestList, SchemaId, SnapshotRef, TableMetadataRef,
+};
+use crate::{Error, ErrorKind, Result};
+
+const DEFAULT_CACHE_SIZE_BYTES: u64 = 32 * 1024 * 1024; // 32MB
+
+#[derive(Clone, Debug)]
+pub(crate) enum CachedItem {
+ ManifestList(Arc<ManifestList>),
+ Manifest(Arc<Manifest>),
+}
+
+#[derive(Clone, Debug, Hash, Eq, PartialEq)]
+pub(crate) enum CachedObjectKey {
+ ManifestList((String, FormatVersion, SchemaId)),
+ Manifest(String),
+}
+
+/// Caches metadata objects deserialized from immutable files
+#[derive(Clone, Debug)]
+pub struct ObjectCache {
+ cache: moka::future::Cache<CachedObjectKey, CachedItem>,
+ file_io: FileIO,
+ cache_disabled: bool,
+}
+
+impl ObjectCache {
+ /// Creates a new [`ObjectCache`]
+ /// with the default cache size
+ pub(crate) fn new(file_io: FileIO) -> Self {
+ Self::new_with_capacity(file_io, DEFAULT_CACHE_SIZE_BYTES)
+ }
+
+ /// Creates a new [`ObjectCache`]
+ /// with a specific cache size
+ pub(crate) fn new_with_capacity(file_io: FileIO, cache_size_bytes: u64) -> Self {
+ if cache_size_bytes == 0 {
+ Self::with_disabled_cache(file_io)
+ } else {
+ Self {
+ cache: moka::future::Cache::new(cache_size_bytes),
+ file_io,
+ cache_disabled: false,
+ }
+ }
+ }
+
+ /// Creates a new [`ObjectCache`]
+ /// with caching disabled
+ pub(crate) fn with_disabled_cache(file_io: FileIO) -> Self {
+ Self {
+ cache: moka::future::Cache::new(0),
+ file_io,
+ cache_disabled: true,
+ }
+ }
+
+ /// 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 {
+ return manifest_file
+ .load_manifest(&self.file_io)
+ .await
+ .map(Arc::new);
+ }
+
+ let key = CachedObjectKey::Manifest(manifest_file.manifest_path.clone());
+
+ let cache_entry = self
+ .cache
+ .entry_by_ref(&key)
+ .or_try_insert_with(self.fetch_and_parse_manifest(manifest_file))
+ .await
+ .map_err(|err| {
+ Error::new(
+ ErrorKind::Unexpected,
+ format!("Failed to load manifest {}", manifest_file.manifest_path),
+ )
+ .with_source(err)
+ })?
+ .into_value();
+
+ match cache_entry {
+ CachedItem::Manifest(arc_manifest) => Ok(arc_manifest),
+ _ => Err(Error::new(
+ ErrorKind::Unexpected,
+ format!("cached object for key '{:?}' is not a Manifest", key),
+ )),
+ }
+ }
+
+ /// Retrieves an Arc [`ManifestList`] from the cache
+ /// or retrieves one from FileIO and parses it if not present
+ pub(crate) async fn get_manifest_list(
+ &self,
+ snapshot: &SnapshotRef,
+ table_metadata: &TableMetadataRef,
+ ) -> Result<Arc<ManifestList>> {
+ if self.cache_disabled {
+ return snapshot
+ .load_manifest_list(&self.file_io, table_metadata)
+ .await
+ .map(Arc::new);
+ }
+
+ let key = CachedObjectKey::ManifestList((
+ snapshot.manifest_list().to_string(),
+ table_metadata.format_version,
+ snapshot.schema_id().unwrap(),
+ ));
+ let cache_entry = self
+ .cache
+ .entry_by_ref(&key)
+ .or_try_insert_with(self.fetch_and_parse_manifest_list(snapshot, table_metadata))
+ .await
+ .map_err(|err| Error::new(ErrorKind::Unexpected, err.as_ref().message()))?
+ .into_value();
+
+ match cache_entry {
+ CachedItem::ManifestList(arc_manifest_list) => Ok(arc_manifest_list),
+ _ => Err(Error::new(
+ ErrorKind::Unexpected,
+ format!("cached object for path '{:?}' is not a manifest list", key),
+ )),
+ }
+ }
+
+ async fn fetch_and_parse_manifest(&self, manifest_file: &ManifestFile) -> Result<CachedItem> {
+ let manifest = manifest_file.load_manifest(&self.file_io).await?;
+
+ Ok(CachedItem::Manifest(Arc::new(manifest)))
+ }
+
+ async fn fetch_and_parse_manifest_list(
+ &self,
+ snapshot: &SnapshotRef,
+ table_metadata: &TableMetadataRef,
+ ) -> Result<CachedItem> {
+ let manifest_list = snapshot
+ .load_manifest_list(&self.file_io, table_metadata)
+ .await?;
+
+ Ok(CachedItem::ManifestList(Arc::new(manifest_list)))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::fs;
+
+ use tempfile::TempDir;
+ use tera::{Context, Tera};
+ use uuid::Uuid;
+
+ use super::*;
+ use crate::io::{FileIO, OutputFile};
+ use crate::spec::{
+ DataContentType, DataFileBuilder, DataFileFormat, FormatVersion, Literal, Manifest,
+ ManifestContentType, ManifestEntry, ManifestListWriter, ManifestMetadata, ManifestStatus,
+ ManifestWriter, Struct, TableMetadata, EMPTY_SNAPSHOT_ID,
+ };
+ use crate::table::Table;
+ use crate::TableIdent;
+
+ struct TableTestFixture {
+ table_location: String,
+ table: Table,
+ }
+
+ impl TableTestFixture {
+ fn new() -> Self {
+ let tmp_dir = TempDir::new().unwrap();
+ let table_location = tmp_dir.path().join("table1");
+ let manifest_list1_location = table_location.join("metadata/manifests_list_1.avro");
+ let manifest_list2_location = table_location.join("metadata/manifests_list_2.avro");
+ let table_metadata1_location = table_location.join("metadata/v1.json");
+
+ let file_io = FileIO::from_path(table_location.as_os_str().to_str().unwrap())
+ .unwrap()
+ .build()
+ .unwrap();
+
+ let table_metadata = {
+ let template_json_str = fs::read_to_string(format!(
+ "{}/testdata/example_table_metadata_v2.json",
+ env!("CARGO_MANIFEST_DIR")
+ ))
+ .unwrap();
+ let mut context = Context::new();
+ context.insert("table_location", &table_location);
+ context.insert("manifest_list_1_location", &manifest_list1_location);
+ context.insert("manifest_list_2_location", &manifest_list2_location);
+ context.insert("table_metadata_1_location", &table_metadata1_location);
+
+ let metadata_json = Tera::one_off(&template_json_str, &context, false).unwrap();
+ serde_json::from_str::<TableMetadata>(&metadata_json).unwrap()
+ };
+
+ let table = Table::builder()
+ .metadata(table_metadata)
+ .identifier(TableIdent::from_strs(["db", "table1"]).unwrap())
+ .file_io(file_io.clone())
+ .metadata_location(table_metadata1_location.as_os_str().to_str().unwrap())
+ .build()
+ .unwrap();
+
+ Self {
+ table_location: table_location.to_str().unwrap().to_string(),
+ table,
+ }
+ }
+
+ fn next_manifest_file(&self) -> OutputFile {
+ self.table
+ .file_io()
+ .new_output(format!(
+ "{}/metadata/manifest_{}.avro",
+ self.table_location,
+ Uuid::new_v4()
+ ))
+ .unwrap()
+ }
+
+ async fn setup_manifest_files(&mut self) {
+ let current_snapshot = self.table.metadata().current_snapshot().unwrap();
+ let current_schema = current_snapshot.schema(self.table.metadata()).unwrap();
+ let current_partition_spec = self.table.metadata().default_partition_spec().unwrap();
+
+ // Write data files
+ let data_file_manifest = ManifestWriter::new(
+ self.next_manifest_file(),
+ current_snapshot.snapshot_id(),
+ vec![],
+ )
+ .write(Manifest::new(
+ ManifestMetadata::builder()
+ .schema((*current_schema).clone())
+ .content(ManifestContentType::Data)
+ .format_version(FormatVersion::V2)
+ .partition_spec((**current_partition_spec).clone())
+ .schema_id(current_schema.schema_id())
+ .build(),
+ vec![ManifestEntry::builder()
+ .status(ManifestStatus::Added)
+ .data_file(
+ DataFileBuilder::default()
+ .content(DataContentType::Data)
+ .file_path(format!("{}/1.parquet", &self.table_location))
+ .file_format(DataFileFormat::Parquet)
+ .file_size_in_bytes(100)
+ .record_count(1)
+ .partition(Struct::from_iter([Some(Literal::long(100))]))
+ .build()
+ .unwrap(),
+ )
+ .build()],
+ ))
+ .await
+ .unwrap();
+
+ // Write to manifest list
+ let mut manifest_list_write = ManifestListWriter::v2(
+ self.table
+ .file_io()
+ .new_output(current_snapshot.manifest_list())
+ .unwrap(),
+ current_snapshot.snapshot_id(),
+ current_snapshot
+ .parent_snapshot_id()
+ .unwrap_or(EMPTY_SNAPSHOT_ID),
+ current_snapshot.sequence_number(),
+ );
+ manifest_list_write
+ .add_manifests(vec![data_file_manifest].into_iter())
+ .unwrap();
+ manifest_list_write.close().await.unwrap();
+ }
+ }
+
+ #[tokio::test]
+ async fn test_get_manifest_list_and_manifest_from_disabled_cache() {
+ let mut fixture = TableTestFixture::new();
+ fixture.setup_manifest_files().await;
+
+ let object_cache = ObjectCache::with_disabled_cache(fixture.table.file_io().clone());
Review Comment:
Whoops! Fixed, good spot :-)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Object Cache: caches parsed Manifests and ManifestLists for performance [iceberg-rust]
Posted by "sdd (via GitHub)" <gi...@apache.org>.
sdd commented on code in PR #512:
URL: https://github.com/apache/iceberg-rust/pull/512#discussion_r1712255347
##########
crates/iceberg/src/table.rs:
##########
@@ -16,28 +16,156 @@
// under the License.
//! Table API for Apache Iceberg
-use typed_builder::TypedBuilder;
+
+use std::sync::Arc;
use crate::arrow::ArrowReaderBuilder;
+use crate::io::object_cache::ObjectCache;
use crate::io::FileIO;
use crate::scan::TableScanBuilder;
use crate::spec::{TableMetadata, TableMetadataRef};
-use crate::{Result, TableIdent};
+use crate::{Error, ErrorKind, Result, TableIdent};
+
+/// Builder to create table scan.
+pub struct TableBuilder {
+ file_io: Option<FileIO>,
+ metadata_location: Option<String>,
+ metadata: Option<TableMetadataRef>,
+ identifier: Option<TableIdent>,
+ readonly: bool,
+ disable_cache: bool,
+ cache_size_bytes: Option<u64>,
+}
+
+impl TableBuilder {
+ pub(crate) fn new() -> Self {
+ Self {
+ file_io: None,
+ metadata_location: None,
+ metadata: None,
+ identifier: None,
+ readonly: false,
+ disable_cache: false,
+ cache_size_bytes: None,
+ }
+ }
+
+ /// required - sets the necessary FileIO to use for the table
+ pub fn file_io(mut self, file_io: FileIO) -> Self {
+ self.file_io = Some(file_io);
+ self
+ }
+
+ /// optional - sets the tables metadata location
+ pub fn metadata_location<T: Into<String>>(mut self, metadata_location: T) -> Self {
+ self.metadata_location = Some(metadata_location.into());
+ self
+ }
+
+ /// required - passes in the TableMetadata to use for the Table
+ pub fn metadata<T: Into<TableMetadataRef>>(mut self, metadata: T) -> Self {
+ self.metadata = Some(metadata.into());
+ self
+ }
+
+ /// required - passes in the TableIdent to use for the Table
+ pub fn identifier(mut self, identifier: TableIdent) -> Self {
+ self.identifier = Some(identifier);
+ self
+ }
+
+ /// specifies if the Table is readonly or not (default not)
+ pub fn readonly(mut self, readonly: bool) -> Self {
+ self.readonly = readonly;
+ self
+ }
+
+ /// specifies if the Table's metadata cache will be disabled,
+ /// so that reads of Manifests and ManifestLists will never
+ /// get cached.
+ pub fn disable_cache(mut self) -> Self {
+ self.disable_cache = true;
+ self
+ }
+
+ /// optionally set a non-default metadata cache size
+ pub fn cache_size_bytes(mut self, cache_size_bytes: u64) -> Self {
+ self.cache_size_bytes = Some(cache_size_bytes);
+ self
+ }
Review Comment:
I like the sound of this! Look forwards to working with you on this afterwards :-)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Object Cache: caches parsed Manifests and ManifestLists for performance [iceberg-rust]
Posted by "sdd (via GitHub)" <gi...@apache.org>.
sdd commented on code in PR #512:
URL: https://github.com/apache/iceberg-rust/pull/512#discussion_r1712257994
##########
crates/iceberg/src/io/object_cache.rs:
##########
@@ -0,0 +1,161 @@
+// 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.
+
+use std::sync::Arc;
+
+use crate::io::FileIO;
+use crate::spec::{
+ FormatVersion, Manifest, ManifestFile, ManifestList, SchemaId, SnapshotRef, TableMetadataRef,
+};
+use crate::{Error, ErrorKind, Result};
+
+const DEFAULT_CACHE_SIZE_BYTES: u64 = 2 ^ 15; // 32MB
Review Comment:
Sure, done!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Object Cache: caches parsed Manifests and ManifestLists for performance [iceberg-rust]
Posted by "sdd (via GitHub)" <gi...@apache.org>.
sdd commented on code in PR #512:
URL: https://github.com/apache/iceberg-rust/pull/512#discussion_r1712265470
##########
crates/iceberg/src/spec/manifest_list.rs:
##########
@@ -78,6 +78,11 @@ impl ManifestList {
pub fn entries(&self) -> &[ManifestFile] {
&self.entries
}
+
+ /// Take ownership of the entries in the manifest list, consuming it
+ pub fn consume_entries(self) -> impl IntoIterator<Item = ManifestFile> {
Review Comment:
Oh that's nicer. Will do in another PR now that this change was eliminated from this PR in the rebase.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Object Cache: caches parsed Manifests and ManifestLists for performance [iceberg-rust]
Posted by "sdd (via GitHub)" <gi...@apache.org>.
sdd commented on code in PR #512:
URL: https://github.com/apache/iceberg-rust/pull/512#discussion_r1720845074
##########
crates/iceberg/src/io/object_cache.rs:
##########
@@ -0,0 +1,161 @@
+// 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.
+
+use std::sync::Arc;
+
+use crate::io::FileIO;
+use crate::spec::{
+ FormatVersion, Manifest, ManifestFile, ManifestList, SchemaId, SnapshotRef, TableMetadataRef,
+};
+use crate::{Error, ErrorKind, Result};
+
+const DEFAULT_CACHE_SIZE_BYTES: u64 = 32 * 1024 * 1024; // 32MB
+
+#[derive(Clone, Debug)]
+pub(crate) enum CachedItem {
+ ManifestList(Arc<ManifestList>),
+ Manifest(Arc<Manifest>),
+}
+
+#[derive(Clone, Debug, Hash, Eq, PartialEq)]
+pub(crate) enum CachedObjectKey {
+ ManifestList((String, FormatVersion, SchemaId)),
Review Comment:
This was done because a manifest list can be referenced from more than one snapshot, and those snapshots could have different schemas, and the table metadata that references them could also have potentially updated from V1 to V2.
We're caching the **parsed** ManifestList, and the parsing depends on the passed down table metadata format version and snapshot schema: https://github.com/apache/iceberg-rust/blob/17317660993a3c1b7974a37761356cbd27e3558e/crates/iceberg/src/spec/snapshot.rs#L164-L185
By adding the format version and schema id to the key, we ensure that, if the ManifestList is requested from either a snapshot with a different schema id, or from an updated table manifest data (unlikely, but I figured it safer to take this into consideration), then they will get a manifest list parsed with those specific parameters rather than one parsed under different settings.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Object Cache: caches parsed Manifests and ManifestLists for performance [iceberg-rust]
Posted by "liurenjie1024 (via GitHub)" <gi...@apache.org>.
liurenjie1024 commented on PR #512:
URL: https://github.com/apache/iceberg-rust/pull/512#issuecomment-2296144985
Security audit failure is tracked in #559 , I'll merge this first. Thanks @sdd !
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Object Cache: caches parsed Manifests and ManifestLists for performance [iceberg-rust]
Posted by "liurenjie1024 (via GitHub)" <gi...@apache.org>.
liurenjie1024 commented on code in PR #512:
URL: https://github.com/apache/iceberg-rust/pull/512#discussion_r1720743099
##########
crates/iceberg/src/io/object_cache.rs:
##########
@@ -0,0 +1,161 @@
+// 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.
+
+use std::sync::Arc;
+
+use crate::io::FileIO;
+use crate::spec::{
+ FormatVersion, Manifest, ManifestFile, ManifestList, SchemaId, SnapshotRef, TableMetadataRef,
+};
+use crate::{Error, ErrorKind, Result};
+
+const DEFAULT_CACHE_SIZE_BYTES: u64 = 32 * 1024 * 1024; // 32MB
+
+#[derive(Clone, Debug)]
+pub(crate) enum CachedItem {
+ ManifestList(Arc<ManifestList>),
+ Manifest(Arc<Manifest>),
+}
+
+#[derive(Clone, Debug, Hash, Eq, PartialEq)]
+pub(crate) enum CachedObjectKey {
+ ManifestList((String, FormatVersion, SchemaId)),
+ Manifest(String),
+}
+
+/// Caches metadata objects deserialized from immutable files
+#[derive(Clone, Debug)]
+pub struct ObjectCache {
+ cache: moka::future::Cache<CachedObjectKey, CachedItem>,
+ file_io: FileIO,
+ cache_disabled: bool,
+}
+
+impl ObjectCache {
+ /// Creates a new [`ObjectCache`]
+ /// with the default cache size
+ pub(crate) fn new(file_io: FileIO) -> Self {
+ Self::new_with_capacity(file_io, DEFAULT_CACHE_SIZE_BYTES)
+ }
+
+ /// Creates a new [`ObjectCache`]
+ /// with a specific cache size
+ pub(crate) fn new_with_capacity(file_io: FileIO, cache_size_bytes: u64) -> Self {
+ if cache_size_bytes == 0 {
+ Self::with_disabled_cache(file_io)
+ } else {
+ Self {
+ cache: moka::future::Cache::new(cache_size_bytes),
+ file_io,
+ cache_disabled: false,
+ }
+ }
+ }
+
+ /// Creates a new [`ObjectCache`]
+ /// with caching disabled
+ pub(crate) fn with_disabled_cache(file_io: FileIO) -> Self {
+ Self {
+ cache: moka::future::Cache::new(0),
+ file_io,
+ cache_disabled: true,
+ }
+ }
+
+ /// 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 {
+ return manifest_file
+ .load_manifest(&self.file_io)
+ .await
+ .map(Arc::new);
+ }
+
+ let key = CachedObjectKey::Manifest(manifest_file.manifest_path.clone());
+
+ let cache_entry = self
+ .cache
+ .entry_by_ref(&key)
+ .or_try_insert_with(self.fetch_and_parse_manifest(manifest_file))
+ .await
+ .map_err(|err| Error::new(ErrorKind::Unexpected, err.as_ref().message()))?
Review Comment:
```suggestion
.map_err(|err| Error::new(ErrorKind::Unexpected, format!("Failed load manifest {}", manifest_file.manifest_path)).with_source(err))?
```
##########
crates/iceberg/src/io/object_cache.rs:
##########
@@ -0,0 +1,161 @@
+// 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.
+
+use std::sync::Arc;
+
+use crate::io::FileIO;
+use crate::spec::{
+ FormatVersion, Manifest, ManifestFile, ManifestList, SchemaId, SnapshotRef, TableMetadataRef,
+};
+use crate::{Error, ErrorKind, Result};
+
+const DEFAULT_CACHE_SIZE_BYTES: u64 = 32 * 1024 * 1024; // 32MB
+
+#[derive(Clone, Debug)]
+pub(crate) enum CachedItem {
+ ManifestList(Arc<ManifestList>),
+ Manifest(Arc<Manifest>),
+}
+
+#[derive(Clone, Debug, Hash, Eq, PartialEq)]
+pub(crate) enum CachedObjectKey {
+ ManifestList((String, FormatVersion, SchemaId)),
+ Manifest(String),
+}
+
+/// Caches metadata objects deserialized from immutable files
+#[derive(Clone, Debug)]
+pub struct ObjectCache {
+ cache: moka::future::Cache<CachedObjectKey, CachedItem>,
+ file_io: FileIO,
+ cache_disabled: bool,
+}
+
+impl ObjectCache {
+ /// Creates a new [`ObjectCache`]
+ /// with the default cache size
+ pub(crate) fn new(file_io: FileIO) -> Self {
+ Self::new_with_capacity(file_io, DEFAULT_CACHE_SIZE_BYTES)
+ }
+
+ /// Creates a new [`ObjectCache`]
+ /// with a specific cache size
+ pub(crate) fn new_with_capacity(file_io: FileIO, cache_size_bytes: u64) -> Self {
+ if cache_size_bytes == 0 {
+ Self::with_disabled_cache(file_io)
+ } else {
+ Self {
+ cache: moka::future::Cache::new(cache_size_bytes),
+ file_io,
+ cache_disabled: false,
+ }
+ }
+ }
+
+ /// Creates a new [`ObjectCache`]
+ /// with caching disabled
+ pub(crate) fn with_disabled_cache(file_io: FileIO) -> Self {
+ Self {
+ cache: moka::future::Cache::new(0),
+ file_io,
+ cache_disabled: true,
+ }
+ }
+
+ /// 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 {
+ return manifest_file
+ .load_manifest(&self.file_io)
+ .await
+ .map(Arc::new);
+ }
+
+ let key = CachedObjectKey::Manifest(manifest_file.manifest_path.clone());
+
+ let cache_entry = self
+ .cache
+ .entry_by_ref(&key)
+ .or_try_insert_with(self.fetch_and_parse_manifest(manifest_file))
+ .await
+ .map_err(|err| Error::new(ErrorKind::Unexpected, err.as_ref().message()))?
+ .into_value();
+
+ match cache_entry {
+ CachedItem::Manifest(arc_manifest) => Ok(arc_manifest),
+ _ => Err(Error::new(
+ ErrorKind::Unexpected,
+ format!("cached object for key '{:?}' is not a Manifest", key),
+ )),
+ }
+ }
+
+ /// Retrieves an Arc [`ManifestList`] from the cache
+ /// or retrieves one from FileIO and parses it if not present
+ pub(crate) async fn get_manifest_list(
+ &self,
+ snapshot: &SnapshotRef,
+ table_metadata: &TableMetadataRef,
+ ) -> Result<Arc<ManifestList>> {
+ if self.cache_disabled {
+ return snapshot
+ .load_manifest_list(&self.file_io, table_metadata)
+ .await
+ .map(Arc::new);
+ }
+
+ let key = CachedObjectKey::ManifestList((
+ snapshot.manifest_list().to_string(),
+ table_metadata.format_version,
+ snapshot.schema_id().unwrap(),
+ ));
+ let cache_entry = self
+ .cache
+ .entry_by_ref(&key)
+ .or_try_insert_with(self.fetch_and_parse_manifest_list(snapshot, table_metadata))
+ .await
+ .map_err(|err| Error::new(ErrorKind::Unexpected, err.as_ref().message()))?
+ .into_value();
+
+ match cache_entry {
+ CachedItem::ManifestList(arc_manifest_list) => Ok(arc_manifest_list),
+ _ => Err(Error::new(
+ ErrorKind::Unexpected,
+ format!("cached object for path '{:?}' is not a Manifest", key),
Review Comment:
```suggestion
format!("cached object for path '{:?}' is not a manifest list", key),
```
##########
crates/iceberg/src/io/object_cache.rs:
##########
@@ -0,0 +1,161 @@
+// 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.
+
+use std::sync::Arc;
+
+use crate::io::FileIO;
+use crate::spec::{
+ FormatVersion, Manifest, ManifestFile, ManifestList, SchemaId, SnapshotRef, TableMetadataRef,
+};
+use crate::{Error, ErrorKind, Result};
+
+const DEFAULT_CACHE_SIZE_BYTES: u64 = 32 * 1024 * 1024; // 32MB
+
+#[derive(Clone, Debug)]
+pub(crate) enum CachedItem {
+ ManifestList(Arc<ManifestList>),
+ Manifest(Arc<Manifest>),
+}
+
+#[derive(Clone, Debug, Hash, Eq, PartialEq)]
+pub(crate) enum CachedObjectKey {
+ ManifestList((String, FormatVersion, SchemaId)),
Review Comment:
Why a `ManifestList` key isn't a simple `String` just like `Manifest`? If they both are just String, I think we don't need this enum?
##########
crates/iceberg/src/io/object_cache.rs:
##########
Review Comment:
Could we add some ut for this ?
##########
crates/iceberg/src/table.rs:
##########
@@ -62,6 +190,11 @@ impl Table {
&self.file_io
}
+ /// Returns this table's object cache
+ pub fn object_cache(&self) -> Arc<ObjectCache> {
Review Comment:
```suggestion
pub(crate) fn object_cache(&self) -> Arc<ObjectCache> {
```
How about making it crate private for now? I can't come up with a case where user need it.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Object Cache: caches parsed Manifests and ManifestLists for performance [iceberg-rust]
Posted by "sdd (via GitHub)" <gi...@apache.org>.
sdd commented on code in PR #512:
URL: https://github.com/apache/iceberg-rust/pull/512#discussion_r1720845074
##########
crates/iceberg/src/io/object_cache.rs:
##########
@@ -0,0 +1,161 @@
+// 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.
+
+use std::sync::Arc;
+
+use crate::io::FileIO;
+use crate::spec::{
+ FormatVersion, Manifest, ManifestFile, ManifestList, SchemaId, SnapshotRef, TableMetadataRef,
+};
+use crate::{Error, ErrorKind, Result};
+
+const DEFAULT_CACHE_SIZE_BYTES: u64 = 32 * 1024 * 1024; // 32MB
+
+#[derive(Clone, Debug)]
+pub(crate) enum CachedItem {
+ ManifestList(Arc<ManifestList>),
+ Manifest(Arc<Manifest>),
+}
+
+#[derive(Clone, Debug, Hash, Eq, PartialEq)]
+pub(crate) enum CachedObjectKey {
+ ManifestList((String, FormatVersion, SchemaId)),
Review Comment:
This was done because a manifest list can be referenced from more than one snapshot, and those snapshots could have different schemas, and the table metadata that references them could also have potentially updated from V1 to V2.
We're caching the **parsed** ManifestList, and the parsing depends on the passed down table metadata format version and snapshot schema (see https://github.com/apache/iceberg-rust/blob/17317660993a3c1b7974a37761356cbd27e3558e/crates/iceberg/src/spec/snapshot.rs#L164-L185).
By adding the format version and schema id to the key, we ensure that, if the ManifestList is requested from either a snapshot with a different schema id, or from an updated table manifest data (unlikely, but I figured it safer to take this into consideration), then they will get a manifest list parsed with those specific parameters rather than one parsed under different settings.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Object Cache: caches parsed Manifests and ManifestLists for performance [iceberg-rust]
Posted by "sdd (via GitHub)" <gi...@apache.org>.
sdd commented on code in PR #512:
URL: https://github.com/apache/iceberg-rust/pull/512#discussion_r1720848705
##########
crates/iceberg/src/io/object_cache.rs:
##########
Review Comment:
Done.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Object Cache: caches parsed Manifests and ManifestLists for performance [iceberg-rust]
Posted by "sdd (via GitHub)" <gi...@apache.org>.
sdd commented on code in PR #512:
URL: https://github.com/apache/iceberg-rust/pull/512#discussion_r1712254637
##########
crates/iceberg/src/table.rs:
##########
@@ -16,28 +16,156 @@
// under the License.
//! Table API for Apache Iceberg
-use typed_builder::TypedBuilder;
+
+use std::sync::Arc;
use crate::arrow::ArrowReaderBuilder;
+use crate::io::object_cache::ObjectCache;
use crate::io::FileIO;
use crate::scan::TableScanBuilder;
use crate::spec::{TableMetadata, TableMetadataRef};
-use crate::{Result, TableIdent};
+use crate::{Error, ErrorKind, Result, TableIdent};
+
+/// Builder to create table scan.
+pub struct TableBuilder {
Review Comment:
Unfortunately I could not get it to work with `typed_builder`, despite spending a long time trying. I could not configure `typed_builder` to be able to initialise the object cache with either an optional capacity, default capacity or disabled.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Object Cache: caches parsed Manifests and ManifestLists for performance [iceberg-rust]
Posted by "liurenjie1024 (via GitHub)" <gi...@apache.org>.
liurenjie1024 commented on PR #512:
URL: https://github.com/apache/iceberg-rust/pull/512#issuecomment-2277578710
cc @sdd Would you mind to update pr to resolve conflicts?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Object Cache: caches parsed Manifests and ManifestLists for performance [iceberg-rust]
Posted by "sdd (via GitHub)" <gi...@apache.org>.
sdd commented on code in PR #512:
URL: https://github.com/apache/iceberg-rust/pull/512#discussion_r1712259304
##########
crates/iceberg/src/io/object_cache.rs:
##########
@@ -0,0 +1,161 @@
+// 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.
+
+use std::sync::Arc;
+
+use crate::io::FileIO;
+use crate::spec::{
+ FormatVersion, Manifest, ManifestFile, ManifestList, SchemaId, SnapshotRef, TableMetadataRef,
+};
+use crate::{Error, ErrorKind, Result};
+
+const DEFAULT_CACHE_SIZE_BYTES: u64 = 2 ^ 15; // 32MB
+
+#[derive(Clone, Debug)]
+pub(crate) enum CachedItem {
+ ManifestList(Arc<ManifestList>),
+ Manifest(Arc<Manifest>),
+}
+
+#[derive(Clone, Debug, Hash, Eq, PartialEq)]
+pub(crate) enum CachedObjectKey {
+ ManifestList((String, FormatVersion, SchemaId)),
+ Manifest(String),
+}
+
+/// Caches metadata objects deserialized from immutable files
+#[derive(Clone, Debug)]
+pub struct ObjectCache {
+ cache: moka::future::Cache<CachedObjectKey, CachedItem>,
+ file_io: FileIO,
+ cache_disabled: bool,
+}
+
+impl ObjectCache {
+ /// Creates a new [`ObjectCache`]
+ /// with the default cache size
+ pub(crate) fn new(file_io: FileIO) -> Self {
+ Self::new_with_cache_size(file_io, DEFAULT_CACHE_SIZE_BYTES)
+ }
+
+ /// Creates a new [`ObjectCache`]
+ /// with a specific cache size
+ pub(crate) fn new_with_cache_size(file_io: FileIO, cache_size_bytes: u64) -> Self {
Review Comment:
I like that! Done.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Object Cache: caches parsed Manifests and ManifestLists for performance [iceberg-rust]
Posted by "Xuanwo (via GitHub)" <gi...@apache.org>.
Xuanwo commented on code in PR #512:
URL: https://github.com/apache/iceberg-rust/pull/512#discussion_r1711342057
##########
crates/iceberg/src/io/object_cache.rs:
##########
@@ -0,0 +1,161 @@
+// 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.
+
+use std::sync::Arc;
+
+use crate::io::FileIO;
+use crate::spec::{
+ FormatVersion, Manifest, ManifestFile, ManifestList, SchemaId, SnapshotRef, TableMetadataRef,
+};
+use crate::{Error, ErrorKind, Result};
+
+const DEFAULT_CACHE_SIZE_BYTES: u64 = 2 ^ 15; // 32MB
+
+#[derive(Clone, Debug)]
+pub(crate) enum CachedItem {
+ ManifestList(Arc<ManifestList>),
+ Manifest(Arc<Manifest>),
+}
+
+#[derive(Clone, Debug, Hash, Eq, PartialEq)]
+pub(crate) enum CachedObjectKey {
+ ManifestList((String, FormatVersion, SchemaId)),
+ Manifest(String),
+}
+
+/// Caches metadata objects deserialized from immutable files
+#[derive(Clone, Debug)]
+pub struct ObjectCache {
Review Comment:
I have an idea to make the cache more transparent, but the comment section is too small to explain it. I will prepare a PR once this one is merged. :love_letter:
##########
crates/iceberg/src/io/object_cache.rs:
##########
@@ -0,0 +1,161 @@
+// 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.
+
+use std::sync::Arc;
+
+use crate::io::FileIO;
+use crate::spec::{
+ FormatVersion, Manifest, ManifestFile, ManifestList, SchemaId, SnapshotRef, TableMetadataRef,
+};
+use crate::{Error, ErrorKind, Result};
+
+const DEFAULT_CACHE_SIZE_BYTES: u64 = 2 ^ 15; // 32MB
+
+#[derive(Clone, Debug)]
+pub(crate) enum CachedItem {
+ ManifestList(Arc<ManifestList>),
+ Manifest(Arc<Manifest>),
+}
+
+#[derive(Clone, Debug, Hash, Eq, PartialEq)]
+pub(crate) enum CachedObjectKey {
+ ManifestList((String, FormatVersion, SchemaId)),
+ Manifest(String),
+}
+
+/// Caches metadata objects deserialized from immutable files
+#[derive(Clone, Debug)]
+pub struct ObjectCache {
+ cache: moka::future::Cache<CachedObjectKey, CachedItem>,
+ file_io: FileIO,
+ cache_disabled: bool,
+}
+
+impl ObjectCache {
+ /// Creates a new [`ObjectCache`]
+ /// with the default cache size
+ pub(crate) fn new(file_io: FileIO) -> Self {
+ Self::new_with_cache_size(file_io, DEFAULT_CACHE_SIZE_BYTES)
+ }
+
+ /// Creates a new [`ObjectCache`]
+ /// with a specific cache size
+ pub(crate) fn new_with_cache_size(file_io: FileIO, cache_size_bytes: u64) -> Self {
Review Comment:
We often use `capacity` for this. What do you think? For example, `ObjectCache::with_capacity`.
`ObjectCache::new_with_cache_size` doesn't look appealing to me.
##########
crates/iceberg/src/spec/manifest.rs:
##########
@@ -94,6 +94,12 @@ impl Manifest {
&self.entries
}
+ /// Consume this Manifest, returning its constituent parts
+ pub fn consume(self) -> (Vec<ManifestEntryRef>, ManifestMetadata) {
Review Comment:
We often use `into_parts` for API like this, do you like it?
##########
crates/iceberg/src/table.rs:
##########
@@ -16,28 +16,156 @@
// under the License.
//! Table API for Apache Iceberg
-use typed_builder::TypedBuilder;
+
+use std::sync::Arc;
use crate::arrow::ArrowReaderBuilder;
+use crate::io::object_cache::ObjectCache;
use crate::io::FileIO;
use crate::scan::TableScanBuilder;
use crate::spec::{TableMetadata, TableMetadataRef};
-use crate::{Result, TableIdent};
+use crate::{Error, ErrorKind, Result, TableIdent};
+
+/// Builder to create table scan.
+pub struct TableBuilder {
+ file_io: Option<FileIO>,
+ metadata_location: Option<String>,
+ metadata: Option<TableMetadataRef>,
+ identifier: Option<TableIdent>,
+ readonly: bool,
+ disable_cache: bool,
+ cache_size_bytes: Option<u64>,
+}
+
+impl TableBuilder {
+ pub(crate) fn new() -> Self {
+ Self {
+ file_io: None,
+ metadata_location: None,
+ metadata: None,
+ identifier: None,
+ readonly: false,
+ disable_cache: false,
+ cache_size_bytes: None,
+ }
+ }
+
+ /// required - sets the necessary FileIO to use for the table
+ pub fn file_io(mut self, file_io: FileIO) -> Self {
+ self.file_io = Some(file_io);
+ self
+ }
+
+ /// optional - sets the tables metadata location
+ pub fn metadata_location<T: Into<String>>(mut self, metadata_location: T) -> Self {
+ self.metadata_location = Some(metadata_location.into());
+ self
+ }
+
+ /// required - passes in the TableMetadata to use for the Table
+ pub fn metadata<T: Into<TableMetadataRef>>(mut self, metadata: T) -> Self {
+ self.metadata = Some(metadata.into());
+ self
+ }
+
+ /// required - passes in the TableIdent to use for the Table
+ pub fn identifier(mut self, identifier: TableIdent) -> Self {
+ self.identifier = Some(identifier);
+ self
+ }
+
+ /// specifies if the Table is readonly or not (default not)
+ pub fn readonly(mut self, readonly: bool) -> Self {
+ self.readonly = readonly;
+ self
+ }
+
+ /// specifies if the Table's metadata cache will be disabled,
+ /// so that reads of Manifests and ManifestLists will never
+ /// get cached.
+ pub fn disable_cache(mut self) -> Self {
+ self.disable_cache = true;
+ self
+ }
+
+ /// optionally set a non-default metadata cache size
+ pub fn cache_size_bytes(mut self, cache_size_bytes: u64) -> Self {
+ self.cache_size_bytes = Some(cache_size_bytes);
+ self
+ }
Review Comment:
This is the area I want to improve. If we can incorporate it into `FileIO`, we might avoid exposing the API wherever we need caching.
However, I think it's not a blocker of this PR. I'm willing to help improve this later.
##########
Cargo.toml:
##########
@@ -66,6 +66,7 @@ itertools = "0.13"
log = "^0.4"
mockito = "^1"
murmur3 = "0.5.2"
+num_cpus = "1"
Review Comment:
We can replace this by [std::thread::available_parallelism](https://doc.rust-lang.org/stable/std/thread/fn.available_parallelism.html)
##########
crates/iceberg/src/io/object_cache.rs:
##########
@@ -0,0 +1,161 @@
+// 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.
+
+use std::sync::Arc;
+
+use crate::io::FileIO;
+use crate::spec::{
+ FormatVersion, Manifest, ManifestFile, ManifestList, SchemaId, SnapshotRef, TableMetadataRef,
+};
+use crate::{Error, ErrorKind, Result};
+
+const DEFAULT_CACHE_SIZE_BYTES: u64 = 2 ^ 15; // 32MB
Review Comment:
How about using `32 * 1024 * 1024` to make it clearer? I'm not good at math :laughing:
##########
crates/iceberg/src/table.rs:
##########
@@ -16,28 +16,156 @@
// under the License.
//! Table API for Apache Iceberg
-use typed_builder::TypedBuilder;
+
+use std::sync::Arc;
use crate::arrow::ArrowReaderBuilder;
+use crate::io::object_cache::ObjectCache;
use crate::io::FileIO;
use crate::scan::TableScanBuilder;
use crate::spec::{TableMetadata, TableMetadataRef};
-use crate::{Result, TableIdent};
+use crate::{Error, ErrorKind, Result, TableIdent};
+
+/// Builder to create table scan.
+pub struct TableBuilder {
Review Comment:
We frequently used `typed_builder`. Does it work well in this situation too?
##########
crates/iceberg/Cargo.toml:
##########
@@ -60,7 +60,9 @@ derive_builder = { workspace = true }
fnv = { workspace = true }
futures = { workspace = true }
itertools = { workspace = true }
+moka = { version = "0.12.8", features = ["future"] }
murmur3 = { workspace = true }
+num_cpus = { workspace = true }
Review Comment:
The same.
##########
crates/iceberg/src/spec/manifest_list.rs:
##########
@@ -78,6 +78,11 @@ impl ManifestList {
pub fn entries(&self) -> &[ManifestFile] {
&self.entries
}
+
+ /// Take ownership of the entries in the manifest list, consuming it
+ pub fn consume_entries(self) -> impl IntoIterator<Item = ManifestFile> {
Review Comment:
It's better to implement `IntoIterator` for `ManifestList` instead. This will allow users to use `ManifestList` more easily with other iterator-based APIs.
##########
crates/iceberg/src/scan.rs:
##########
@@ -199,298 +256,588 @@ impl<'a> TableScanBuilder<'a> {
field_ids.push(field_id);
}
- Ok(TableScan {
+ let snapshot_bound_predicate = if let Some(ref predicates) = self.filter {
+ Some(predicates.bind(schema.clone(), true)?)
+ } else {
+ None
+ };
+
+ let plan_context = PlanContext {
snapshot,
- file_io: self.table.file_io().clone(),
table_metadata: self.table.metadata_ref(),
- column_names: self.column_names,
- field_ids,
- bound_predicates,
- schema,
- batch_size: self.batch_size,
+ snapshot_schema: schema,
case_sensitive: self.case_sensitive,
- filter: self.filter.map(Arc::new),
+ predicate: self.filter.map(Arc::new),
+ snapshot_bound_predicate: snapshot_bound_predicate.map(Arc::new),
+ object_cache: self.table.object_cache(),
+ field_ids: Arc::new(field_ids),
+ partition_filter_cache: Arc::new(PartitionFilterCache::new()),
+ manifest_evaluator_cache: Arc::new(ManifestEvaluatorCache::new()),
+ expression_evaluator_cache: Arc::new(ExpressionEvaluatorCache::new()),
+ };
+
+ Ok(TableScan {
+ batch_size: self.batch_size,
+ column_names: self.column_names,
+ file_io: self.table.file_io().clone(),
+ plan_context,
+ table_scan_config: self.table_scan_config,
})
}
}
/// Table scan.
#[derive(Debug)]
pub struct TableScan {
- snapshot: SnapshotRef,
- table_metadata: TableMetadataRef,
+ plan_context: PlanContext,
+ batch_size: Option<usize>,
file_io: FileIO,
column_names: Vec<String>,
- field_ids: Vec<i32>,
- bound_predicates: Option<BoundPredicate>,
- schema: SchemaRef,
- batch_size: Option<usize>,
+ table_scan_config: TableScanConfig,
+}
+
+/// PlanContext wraps a [`SnapshotRef`] alongside all the other
+/// objects that are required to perform a scan file plan.
+#[derive(Debug)]
+struct PlanContext {
Review Comment:
Do you think it's a good idea to use `Arc<PlanContext>` instead?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Object Cache: caches parsed Manifests and ManifestLists for performance [iceberg-rust]
Posted by "sdd (via GitHub)" <gi...@apache.org>.
sdd commented on code in PR #512:
URL: https://github.com/apache/iceberg-rust/pull/512#discussion_r1721274453
##########
crates/iceberg/src/io/object_cache.rs:
##########
@@ -0,0 +1,396 @@
+// 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.
+
+use std::sync::Arc;
+
+use crate::io::FileIO;
+use crate::spec::{
+ FormatVersion, Manifest, ManifestFile, ManifestList, SchemaId, SnapshotRef, TableMetadataRef,
+};
+use crate::{Error, ErrorKind, Result};
+
+const DEFAULT_CACHE_SIZE_BYTES: u64 = 32 * 1024 * 1024; // 32MB
+
+#[derive(Clone, Debug)]
+pub(crate) enum CachedItem {
+ ManifestList(Arc<ManifestList>),
+ Manifest(Arc<Manifest>),
+}
+
+#[derive(Clone, Debug, Hash, Eq, PartialEq)]
+pub(crate) enum CachedObjectKey {
+ ManifestList((String, FormatVersion, SchemaId)),
+ Manifest(String),
+}
+
+/// Caches metadata objects deserialized from immutable files
+#[derive(Clone, Debug)]
+pub struct ObjectCache {
+ cache: moka::future::Cache<CachedObjectKey, CachedItem>,
+ file_io: FileIO,
+ cache_disabled: bool,
+}
+
+impl ObjectCache {
+ /// Creates a new [`ObjectCache`]
+ /// with the default cache size
+ pub(crate) fn new(file_io: FileIO) -> Self {
+ Self::new_with_capacity(file_io, DEFAULT_CACHE_SIZE_BYTES)
+ }
+
+ /// Creates a new [`ObjectCache`]
+ /// with a specific cache size
+ pub(crate) fn new_with_capacity(file_io: FileIO, cache_size_bytes: u64) -> Self {
Review Comment:
Aah - I'd forgot to set up the weigher config on the cache. I've done that now:
https://github.com/apache/iceberg-rust/blob/29812b1f60c6c1e715b62f16782d5dec280d1f4a/crates/iceberg/src/io/object_cache.rs#L62-L65
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Object Cache: caches parsed Manifests and ManifestLists for performance [iceberg-rust]
Posted by "sdd (via GitHub)" <gi...@apache.org>.
sdd commented on code in PR #512:
URL: https://github.com/apache/iceberg-rust/pull/512#discussion_r1715808031
##########
crates/iceberg/src/spec/manifest.rs:
##########
@@ -94,6 +94,12 @@ impl Manifest {
&self.entries
}
+ /// Consume this Manifest, returning its constituent parts
+ pub fn consume(self) -> (Vec<ManifestEntryRef>, ManifestMetadata) {
Review Comment:
This change was no longer present in this PR after it got rebased, but I've renamed it anyway for consistency with the rest of the codebase. Thanks!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Object Cache: caches parsed Manifests and ManifestLists for performance [iceberg-rust]
Posted by "dentiny (via GitHub)" <gi...@apache.org>.
dentiny commented on code in PR #512:
URL: https://github.com/apache/iceberg-rust/pull/512#discussion_r2369996350
##########
crates/iceberg/src/scan.rs:
##########
@@ -477,24 +478,22 @@ impl ManifestFileContext {
/// streaming its constituent [`ManifestEntries`] to the channel provided in the context
async fn fetch_manifest_and_stream_manifest_entries(self) -> Result<()> {
let ManifestFileContext {
- file_io,
+ object_cache,
manifest_file,
bound_predicates,
snapshot_schema,
field_ids,
- expression_evaluator_cache,
mut sender,
+ expression_evaluator_cache,
..
} = self;
- let file_io_cloned = file_io.clone();
- let manifest = manifest_file.load_manifest(&file_io_cloned).await?;
-
- let (entries, _) = manifest.consume();
+ let manifest = object_cache.get_manifest(&manifest_file).await?;
Review Comment:
Gotcha, thank you both for the quick reply! Appreciate it!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org