dhruvarya-db commented on code in PR #2543: URL: https://github.com/apache/iceberg-rust/pull/2543#discussion_r3625567890
########## crates/iceberg/src/transaction/rewrite_manifests.rs: ########## @@ -0,0 +1,804 @@ +// 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::collections::HashMap; +use std::sync::Arc; + +use async_trait::async_trait; +use futures::TryStreamExt; +use futures::stream::{self, StreamExt}; +use uuid::Uuid; + +use crate::error::Result; +use crate::spec::{ + DataFile, DataFileFormat, FormatVersion, MAIN_BRANCH, ManifestContentType, ManifestFile, + ManifestListWriter, ManifestWriter, ManifestWriterBuilder, Operation, Snapshot, + SnapshotReference, SnapshotRetention, Struct, Summary, TableProperties, +}; +use crate::table::Table; +use crate::transaction::snapshot::generate_unique_snapshot_id; +use crate::transaction::{ActionCommit, TransactionAction}; +use crate::{Error, ErrorKind, TableRequirement, TableUpdate}; + +const FALLBACK_BYTES_PER_ENTRY: u64 = 256; + +pub struct RewriteManifestsAction { + target_size_bytes: Option<u64>, + snapshot_properties: HashMap<String, String>, +} + +impl RewriteManifestsAction { + pub(crate) fn new() -> Self { + Self { + target_size_bytes: None, + snapshot_properties: HashMap::new(), + } + } + + pub fn set_target_size_bytes(mut self, target_size_bytes: u64) -> Self { + self.target_size_bytes = Some(target_size_bytes); + self + } + + pub fn set_snapshot_properties(mut self, snapshot_properties: HashMap<String, String>) -> Self { + self.snapshot_properties = snapshot_properties; + self + } +} + +#[async_trait] +impl TransactionAction for RewriteManifestsAction { + async fn commit(self: Arc<Self>, table: &Table) -> Result<ActionCommit> { + let metadata = table.metadata(); + let Some(current_snapshot) = metadata.current_snapshot() else { + return Err(Error::new( + ErrorKind::PreconditionFailed, + "RewriteManifests requires the table to have a current snapshot", + )); + }; + + let target_size_bytes = self.target_size_bytes.unwrap_or_else(|| { + metadata + .properties() + .get(TableProperties::PROPERTY_COMMIT_MANIFEST_TARGET_SIZE_BYTES) + .and_then(|s| s.parse::<u64>().ok()) + .unwrap_or(TableProperties::PROPERTY_COMMIT_MANIFEST_TARGET_SIZE_BYTES_DEFAULT) + }); + let default_spec_id = metadata.default_partition_spec_id(); + let format_version = metadata.format_version(); + + let manifest_list = table.manifest_list_reader(current_snapshot).load().await?; + + let (to_rewrite, kept): (Vec<ManifestFile>, Vec<ManifestFile>) = + manifest_list.entries().iter().cloned().partition(|m| { + m.content == ManifestContentType::Data + && m.partition_spec_id == default_spec_id + && (m.has_added_files() || m.has_existing_files()) + }); + + if to_rewrite.is_empty() { + return Ok(ActionCommit::new(vec![], vec![])); + } + + let total_size: u64 = to_rewrite + .iter() + .map(|m| u64::try_from(m.manifest_length).unwrap_or(0)) + .sum(); + if to_rewrite.len() == 1 && total_size <= target_size_bytes { + return Ok(ActionCommit::new(vec![], vec![])); + } + let total_input_entries: u64 = to_rewrite + .iter() + .map(|m| { + u64::from(m.added_files_count.unwrap_or(0)) + + u64::from(m.existing_files_count.unwrap_or(0)) + }) + .sum(); + let bytes_per_entry = total_size + .checked_div(total_input_entries) + .map_or(FALLBACK_BYTES_PER_ENTRY, |b| b.max(1)); + let manifests_replaced = to_rewrite.len(); + + let commit_uuid = Uuid::now_v7(); + let snapshot_id = generate_unique_snapshot_id(table); + + let loaded: Vec<_> = stream::iter(to_rewrite) + .map(|m| { + let file_io = table.file_io().clone(); + async move { m.load_manifest(&file_io).await } + }) + .buffer_unordered(16) + .try_collect() + .await?; + + let mut grouped: Vec<Vec<(DataFile, i64, i64, Option<i64>)>> = Vec::new(); + let mut group_index: HashMap<Struct, usize> = HashMap::new(); + let mut entries_processed: u64 = 0; + + for manifest in loaded { + for entry in manifest.entries() { + if !entry.is_alive() { + continue; + } + let snap_id = entry.snapshot_id().ok_or_else(|| { + Error::new( + ErrorKind::DataInvalid, + "Live manifest entry is missing snapshot_id", + ) + })?; + let seq = entry.sequence_number().ok_or_else(|| { + Error::new( + ErrorKind::DataInvalid, + "Live manifest entry is missing sequence_number", + ) + })?; + let data_file = entry.data_file().clone(); + let idx = match group_index.get(&data_file.partition) { + Some(&i) => i, + None => { + let i = grouped.len(); + group_index.insert(data_file.partition.clone(), i); + grouped.push(Vec::new()); + i + } + }; + grouped[idx].push((data_file, snap_id, seq, entry.file_sequence_number)); + entries_processed += 1; + } + } + + let mut counter: u64 = 0; + let mut new_manifests: Vec<ManifestFile> = Vec::with_capacity(grouped.len()); + + for group in grouped { + let mut writer = new_manifest_writer(table, &commit_uuid, counter, snapshot_id)?; + counter += 1; + let mut accumulated: u64 = 0; + let mut min_first_row_id: Option<u64> = None; + + for (data_file, snap_id, seq, file_seq) in group { + if accumulated > 0 + && accumulated.saturating_add(bytes_per_entry) > target_size_bytes + { + let mut written = writer.write_manifest_file().await?; + if format_version == FormatVersion::V3 { + written.first_row_id = min_first_row_id; + } + new_manifests.push(written); + writer = new_manifest_writer(table, &commit_uuid, counter, snapshot_id)?; + counter += 1; + accumulated = 0; + min_first_row_id = None; + } + if let Some(frid_u) = data_file.first_row_id.and_then(|f| u64::try_from(f).ok()) { Review Comment: Does the reader automatically populate the `first_row_id` inherited from the snapshot/manifest in the data_file? My understanding is that most data_files don't have a materialized `first_row_id` and that `first_row_id` will remain `None` throughout this loop for most cases. -- 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: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
