dhruvarya-db commented on code in PR #2543:
URL: https://github.com/apache/iceberg-rust/pull/2543#discussion_r3625610890


##########
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()) {
+                    min_first_row_id = Some(min_first_row_id.map_or(frid_u, 
|m| m.min(frid_u)));
+                }
+                writer.add_existing_file(data_file, snap_id, seq, file_seq)?;
+                accumulated = accumulated.saturating_add(bytes_per_entry);
+            }
+            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);
+        }
+
+        let manifest_list_path = format!(
+            "{}/metadata/snap-{}-0-{}.{}",
+            metadata.location(),
+            snapshot_id,
+            commit_uuid,
+            DataFileFormat::Avro,
+        );
+        let next_seq_num = metadata.next_sequence_number();
+        let next_row_id = metadata.next_row_id();
+        let writer = table
+            .file_io()
+            .new_output(manifest_list_path.clone())?
+            .writer()
+            .await?;
+        let mut list_writer = match format_version {
+            FormatVersion::V1 => {
+                ManifestListWriter::v1(writer, snapshot_id, 
metadata.current_snapshot_id())
+            }
+            FormatVersion::V2 => ManifestListWriter::v2(
+                writer,
+                snapshot_id,
+                metadata.current_snapshot_id(),
+                next_seq_num,
+            ),
+            FormatVersion::V3 => ManifestListWriter::v3(

Review Comment:
   I suspect that all of the DataFiles above will have `first_row_id` as None 
because we don't inherit it from the Manifest/snapshot on the read paht. If the 
`first_row_id` in the new Manifest is None, we will end up matching with this 
case of the ManifestListWriter and assign new row ids to these existing rows 
(which seems incorrect).
   
   ```
   (Some(writer_next_row_id), None) => {
                           // Case: Unassigned first row ID for data manifest. 
This is either a new
                           // manifest, or a manifest from a pre-v3 snapshot. 
We need to assign one.
                           let (existing_rows_count, added_rows_count) =
                               require_row_counts_in_manifest(manifest)?;
   ```
   



-- 
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]

Reply via email to