blackmwk commented on code in PR #3564:
URL: https://github.com/apache/iceberg-rust/pull/3564#discussion_r4706266069


##########
crates/iceberg/src/spec/transform.rs:
##########
@@ -221,6 +221,9 @@ impl Transform {
             (Self::Hour, PrimitiveLiteral::Int(ordinal)) => 
Self::human_hour(ordinal),
             (_, value) => {
                 let field_type = field_type.as_primitive_type().unwrap();
+                // A value written before its source column was promoted (`int`
+                // to `long`, `float` to `double`) still carries the old type.
+                let value = value.promote_to(field_type).unwrap_or(value);

Review Comment:
   Why we need to add this? The original semantics of this function is to 
ensure that the type and value should exactly match. I perfer to put the 
promotion outside the function and let caller do it, which make the semanctics 
of this function clear



##########
crates/iceberg/src/transaction/snapshot/mod.rs:
##########
@@ -473,7 +549,7 @@ mod tests {
     use crate::transaction::tests::make_v2_minimal_table;
     use crate::{ErrorKind, TableUpdate};
 
-    fn data_file(table: &Table, path: &str, record_count: u64) -> DataFile {
+    pub(super) fn data_file(table: &Table, path: &str, record_count: u64) -> 
DataFile {

Review Comment:
   Please move the helper functions to test_utils mods rather than making tests 
mod visible to others.



##########
crates/iceberg/src/transaction/snapshot/mod.rs:
##########
@@ -173,6 +180,61 @@ pub(crate) async fn current_manifests(table: &Table) -> 
Result<Vec<ManifestFile>
         .collect())
 }
 
+/// The manifests a producer wrote for one execution's added files.
+///
+/// Reusable while the table's format version is unchanged. Per spec, sequence
+/// number inheritance does not apply to v1 manifests, so one written before a
+/// concurrent upgrade cannot carry the v2 sequence number a retry assigns and
+/// must be rewritten. The schema is not a guard: the manifest's embedded 
schema
+/// describes the files it was written for, which do not change. Nor is the
+/// default partition spec: the files name their own spec, which stays valid.
+pub(crate) struct AddedManifests {
+    /// One per content type today. Several once added files are grouped by
+    /// partition spec (#3500) or rolled over at a target size (#3499).
+    pub manifests: Vec<ManifestFile>,

Review Comment:
   I perfer not using pub fields as the reason stated in 
https://github.com/apache/iceberg-rust/issues/3172, how about we use 
TypedBuilder + pub accessor function?



##########
crates/iceberg/src/transaction/snapshot/manifest_filter.rs:
##########
@@ -0,0 +1,316 @@
+// 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.
+
+//! Rewrites existing manifests to mark files as deleted.
+
+use std::collections::{HashMap, HashSet};
+
+use uuid::Uuid;
+
+use super::{manifest_path, new_manifest_writer};
+use crate::error::{Result, invalid_data};
+use crate::io::object_cache::ManifestKey;
+use crate::spec::{DataFile, DataFileFormat, FormatVersion, 
ManifestContentType, ManifestFile};
+use crate::table::Table;
+
+/// Identifies one entry to mark as `Deleted`, a data file or a delete file.
+///
+/// A path alone is not enough: a Puffin file may hold several deletion
+/// vectors, each its own entry at a distinct blob offset. Data files and
+/// non-DV delete files have no offset, so for them this is the path.
+#[derive(Clone, Debug, PartialEq, Eq, Hash)]
+struct RemovedFileIdentity {
+    /// The absolute path, as stored in the manifest entry. Comparison is
+    /// textual, so a relative path would not match the entry it names.
+    path: String,
+    content_offset: Option<i64>,
+    content_size_in_bytes: Option<i64>,
+}
+
+impl RemovedFileIdentity {
+    fn of(file: &DataFile) -> Self {
+        Self {
+            path: file.file_path().to_string(),
+            content_offset: file.content_offset(),
+            content_size_in_bytes: file.content_size_in_bytes(),
+        }
+    }
+}
+
+impl std::fmt::Display for RemovedFileIdentity {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        match (self.content_offset, self.content_size_in_bytes) {
+            (Some(offset), Some(size)) => write!(f, "{}@{offset}+{size}", 
self.path),
+            _ => f.write_str(&self.path),
+        }
+    }
+}
+
+/// Removes a fixed set of files from the manifests of one content type.
+///
+/// One manager lives for one logical execution of an action and is driven
+/// once per attempt via [`ManifestFilterManager::filter`]. A manifest that
+/// references none of the files passes through untouched. One that does is
+/// rewritten with those entries marked `Deleted` and the rest `Existing`.
+///
+/// A rewrite is reused across attempts while its inputs are unchanged. Its
+/// entries carry the sequence numbers and row ids the source's entries
+/// inherited from the manifest list when they were read, so the reuse key is
+/// the source's [`ManifestKey`], not its path alone: a transaction-local
+/// source manifest keeps its path across attempts but inherits new values
+/// after a rebase.
+pub(crate) struct ManifestFilterManager {
+    content: ManifestContentType,
+    /// The files to remove, by absolute path (and blob range for deletion
+    /// vectors). Fixed for the execution.
+    files_to_remove: HashSet<RemovedFileIdentity>,
+    /// Whether a file to remove that is not live in any manifest fails the
+    /// attempt. Off lets a retry succeed after a concurrent commit removed the
+    /// same file; the action decides which it needs.
+    fail_missing_delete_paths: bool,
+    /// Absolute paths of the data files the commit removes. A deletion vector
+    /// referencing one of them is dangling and is marked `Deleted` too. Not
+    /// required to be found, unlike `files_to_remove`. Only set on the delete
+    /// filter; see [`Self::with_dangling_dvs_for`].
+    removed_data_file_paths: HashSet<String>,
+    /// Source manifest → rewritten result.
+    filtered: HashMap<ManifestKey, FilteredManifest>,
+    /// Format version the rewrites were written under. Per spec, v1 entries
+    /// cannot inherit sequence numbers, so an upgrade invalidates them.
+    format_version: Option<FormatVersion>,

Review Comment:
   Why it's optional?



##########
crates/iceberg/src/transaction/snapshot/manifest_filter.rs:
##########
@@ -0,0 +1,316 @@
+// 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.
+
+//! Rewrites existing manifests to mark files as deleted.
+
+use std::collections::{HashMap, HashSet};
+
+use uuid::Uuid;
+
+use super::{manifest_path, new_manifest_writer};
+use crate::error::{Result, invalid_data};
+use crate::io::object_cache::ManifestKey;
+use crate::spec::{DataFile, DataFileFormat, FormatVersion, 
ManifestContentType, ManifestFile};
+use crate::table::Table;
+
+/// Identifies one entry to mark as `Deleted`, a data file or a delete file.
+///
+/// A path alone is not enough: a Puffin file may hold several deletion
+/// vectors, each its own entry at a distinct blob offset. Data files and
+/// non-DV delete files have no offset, so for them this is the path.
+#[derive(Clone, Debug, PartialEq, Eq, Hash)]
+struct RemovedFileIdentity {

Review Comment:
   How about we turn this into an enum so that its fields are type safe?



##########
crates/iceberg/src/transaction/snapshot/merging.rs:
##########
@@ -0,0 +1,1329 @@
+// 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.
+
+//! Persistent producer for snapshot actions that add and remove data and
+//! delete files.
+
+use std::collections::{HashMap, HashSet};
+
+use uuid::Uuid;
+
+use super::manifest_filter::ManifestFilterManager;
+use super::{
+    AddedManifests, SnapshotCommitInput, current_manifests, 
generate_snapshot_id,
+    manifest_list_path, manifest_path, validate_partition_value, 
write_added_manifest,
+    write_snapshot_commit,
+};
+use crate::error::{Result, invalid_data};
+use crate::spec::{
+    DataContentType, DataFile, DataFileFormat, FormatVersion, 
ManifestContentType, ManifestFile,
+    Operation,
+};
+use crate::table::Table;
+use crate::transaction::ActionCommit;
+
+/// What a merging action asks the producer to do.
+///
+/// Fixed for one logical execution; the producer derives everything else from
+/// it and the table of the current attempt. The action validates the
+/// table-independent parts, such as content types, before each attempt. A path
+/// may be both removed and added: the producer marks the old entry `Deleted`
+/// and writes a new `Added` one, so whether to allow it is the action's call.
+pub(crate) struct MergingIntent {

Review Comment:
   See https://github.com/apache/iceberg-rust/pull/3564/changes#r4706285762



##########
crates/iceberg/src/transaction/snapshot/manifest_filter.rs:
##########
@@ -0,0 +1,316 @@
+// 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.
+
+//! Rewrites existing manifests to mark files as deleted.
+
+use std::collections::{HashMap, HashSet};
+
+use uuid::Uuid;
+
+use super::{manifest_path, new_manifest_writer};
+use crate::error::{Result, invalid_data};
+use crate::io::object_cache::ManifestKey;
+use crate::spec::{DataFile, DataFileFormat, FormatVersion, 
ManifestContentType, ManifestFile};
+use crate::table::Table;
+
+/// Identifies one entry to mark as `Deleted`, a data file or a delete file.
+///
+/// A path alone is not enough: a Puffin file may hold several deletion
+/// vectors, each its own entry at a distinct blob offset. Data files and
+/// non-DV delete files have no offset, so for them this is the path.
+#[derive(Clone, Debug, PartialEq, Eq, Hash)]
+struct RemovedFileIdentity {
+    /// The absolute path, as stored in the manifest entry. Comparison is
+    /// textual, so a relative path would not match the entry it names.
+    path: String,
+    content_offset: Option<i64>,
+    content_size_in_bytes: Option<i64>,
+}
+
+impl RemovedFileIdentity {
+    fn of(file: &DataFile) -> Self {
+        Self {
+            path: file.file_path().to_string(),
+            content_offset: file.content_offset(),
+            content_size_in_bytes: file.content_size_in_bytes(),
+        }
+    }
+}
+
+impl std::fmt::Display for RemovedFileIdentity {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        match (self.content_offset, self.content_size_in_bytes) {
+            (Some(offset), Some(size)) => write!(f, "{}@{offset}+{size}", 
self.path),
+            _ => f.write_str(&self.path),
+        }
+    }
+}
+
+/// Removes a fixed set of files from the manifests of one content type.
+///
+/// One manager lives for one logical execution of an action and is driven
+/// once per attempt via [`ManifestFilterManager::filter`]. A manifest that
+/// references none of the files passes through untouched. One that does is
+/// rewritten with those entries marked `Deleted` and the rest `Existing`.
+///
+/// A rewrite is reused across attempts while its inputs are unchanged. Its
+/// entries carry the sequence numbers and row ids the source's entries
+/// inherited from the manifest list when they were read, so the reuse key is
+/// the source's [`ManifestKey`], not its path alone: a transaction-local
+/// source manifest keeps its path across attempts but inherits new values
+/// after a rebase.
+pub(crate) struct ManifestFilterManager {
+    content: ManifestContentType,
+    /// The files to remove, by absolute path (and blob range for deletion
+    /// vectors). Fixed for the execution.
+    files_to_remove: HashSet<RemovedFileIdentity>,
+    /// Whether a file to remove that is not live in any manifest fails the
+    /// attempt. Off lets a retry succeed after a concurrent commit removed the
+    /// same file; the action decides which it needs.
+    fail_missing_delete_paths: bool,
+    /// Absolute paths of the data files the commit removes. A deletion vector
+    /// referencing one of them is dangling and is marked `Deleted` too. Not
+    /// required to be found, unlike `files_to_remove`. Only set on the delete
+    /// filter; see [`Self::with_dangling_dvs_for`].
+    removed_data_file_paths: HashSet<String>,
+    /// Source manifest → rewritten result.
+    filtered: HashMap<ManifestKey, FilteredManifest>,
+    /// Format version the rewrites were written under. Per spec, v1 entries
+    /// cannot inherit sequence numbers, so an upgrade invalidates them.
+    format_version: Option<FormatVersion>,
+}
+
+/// One rewritten manifest and the files it marked as deleted.
+#[derive(Clone)]
+struct FilteredManifest {
+    manifest: ManifestFile,
+    removed_files: Vec<DataFile>,
+}
+
+/// The result of one filter pass.
+pub(crate) struct Filtered {
+    /// The resulting manifests, in input order.
+    pub manifests: Vec<ManifestFile>,
+    /// The files that were live and are now marked deleted, including their
+    /// metrics as read from the source manifests.
+    pub removed_files: Vec<DataFile>,
+}
+
+impl ManifestFilterManager {
+    pub(crate) fn new(
+        content: ManifestContentType,
+        files_to_remove: &[DataFile],
+        fail_missing_delete_paths: bool,
+    ) -> Self {
+        Self {
+            content,
+            files_to_remove: files_to_remove
+                .iter()
+                .map(RemovedFileIdentity::of)
+                .collect(),
+            fail_missing_delete_paths,
+            removed_data_file_paths: HashSet::new(),
+            filtered: HashMap::new(),
+            format_version: None,
+        }
+    }
+
+    /// Also marks `Deleted` any deletion vector whose referenced data file is
+    /// among `removed_data_files`, as Java's `removeDanglingDeletesFor` does.
+    /// Only deletion vectors qualify: a position delete file's
+    /// `referenced_data_file` is a hint, not a guarantee of its contents.
+    pub(crate) fn with_dangling_dvs_for(mut self, removed_data_files: 
&[DataFile]) -> Self {
+        debug_assert_eq!(self.content, ManifestContentType::Deletes);
+        self.removed_data_file_paths = removed_data_files
+            .iter()
+            .map(|f| f.file_path().to_string())
+            .collect();
+        self
+    }
+
+    /// Applies the removals to `manifests`, rewriting those of this manager's
+    /// content type that reference a file to remove.
+    ///
+    /// With `fail_missing_delete_paths`, fails if a file to remove is not live
+    /// in any manifest: it was never in the table, or a concurrent commit
+    /// already removed it. Otherwise such files are skipped.
+    ///
+    /// Rewritten manifests take their paths from `next_manifest_number` and 
are
+    /// recorded in `owned_artifacts` before being written, so a failed write
+    /// still leaves its path tracked for cleanup.
+    pub(crate) async fn filter(
+        &mut self,
+        table: &Table,
+        snapshot_id: i64,
+        commit_uuid: Uuid,
+        manifests: Vec<ManifestFile>,
+        next_manifest_number: &mut u64,
+        owned_artifacts: &mut HashSet<String>,
+    ) -> Result<Filtered> {
+        let format_version = table.metadata().format_version();
+        // The delete filter must still scan when no delete file is named but a
+        // removed data file may leave a DV dangling. DVs exist from v3, so on
+        // older tables nothing can dangle.
+        let may_have_dangling_dvs =
+            !matches!(format_version, FormatVersion::V1 | FormatVersion::V2)
+                && !self.removed_data_file_paths.is_empty();
+        if self.files_to_remove.is_empty() && !may_have_dangling_dvs {
+            return Ok(Filtered {
+                manifests,
+                removed_files: Vec::new(),
+            });
+        }
+
+        if self.format_version != Some(format_version) {
+            self.filtered.clear();
+            self.format_version = Some(format_version);
+        }
+
+        let mut out = Vec::with_capacity(manifests.len());
+        let mut removed_files: Vec<DataFile> = Vec::new();
+
+        // TODO: every manifest of this content type is read, one at a time.
+        // Skip manifests with no live files and prune by partition summary
+        // before reading, as Java's ManifestFilterManager does, and read the
+        // rest concurrently as `validate_files_not_live` does.
+        for source in manifests {
+            if source.content != self.content {

Review Comment:
   I think we should return error here? 



##########
crates/iceberg/src/transaction/snapshot/manifest_filter.rs:
##########
@@ -0,0 +1,316 @@
+// 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.
+
+//! Rewrites existing manifests to mark files as deleted.
+
+use std::collections::{HashMap, HashSet};
+
+use uuid::Uuid;
+
+use super::{manifest_path, new_manifest_writer};
+use crate::error::{Result, invalid_data};
+use crate::io::object_cache::ManifestKey;
+use crate::spec::{DataFile, DataFileFormat, FormatVersion, 
ManifestContentType, ManifestFile};
+use crate::table::Table;
+
+/// Identifies one entry to mark as `Deleted`, a data file or a delete file.
+///
+/// A path alone is not enough: a Puffin file may hold several deletion
+/// vectors, each its own entry at a distinct blob offset. Data files and
+/// non-DV delete files have no offset, so for them this is the path.
+#[derive(Clone, Debug, PartialEq, Eq, Hash)]
+struct RemovedFileIdentity {
+    /// The absolute path, as stored in the manifest entry. Comparison is
+    /// textual, so a relative path would not match the entry it names.
+    path: String,
+    content_offset: Option<i64>,
+    content_size_in_bytes: Option<i64>,
+}
+
+impl RemovedFileIdentity {
+    fn of(file: &DataFile) -> Self {
+        Self {
+            path: file.file_path().to_string(),
+            content_offset: file.content_offset(),
+            content_size_in_bytes: file.content_size_in_bytes(),
+        }
+    }
+}
+
+impl std::fmt::Display for RemovedFileIdentity {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        match (self.content_offset, self.content_size_in_bytes) {
+            (Some(offset), Some(size)) => write!(f, "{}@{offset}+{size}", 
self.path),
+            _ => f.write_str(&self.path),
+        }
+    }
+}
+
+/// Removes a fixed set of files from the manifests of one content type.
+///
+/// One manager lives for one logical execution of an action and is driven
+/// once per attempt via [`ManifestFilterManager::filter`]. A manifest that
+/// references none of the files passes through untouched. One that does is
+/// rewritten with those entries marked `Deleted` and the rest `Existing`.
+///
+/// A rewrite is reused across attempts while its inputs are unchanged. Its
+/// entries carry the sequence numbers and row ids the source's entries
+/// inherited from the manifest list when they were read, so the reuse key is
+/// the source's [`ManifestKey`], not its path alone: a transaction-local
+/// source manifest keeps its path across attempts but inherits new values
+/// after a rebase.
+pub(crate) struct ManifestFilterManager {
+    content: ManifestContentType,
+    /// The files to remove, by absolute path (and blob range for deletion
+    /// vectors). Fixed for the execution.
+    files_to_remove: HashSet<RemovedFileIdentity>,
+    /// Whether a file to remove that is not live in any manifest fails the
+    /// attempt. Off lets a retry succeed after a concurrent commit removed the
+    /// same file; the action decides which it needs.
+    fail_missing_delete_paths: bool,
+    /// Absolute paths of the data files the commit removes. A deletion vector
+    /// referencing one of them is dangling and is marked `Deleted` too. Not
+    /// required to be found, unlike `files_to_remove`. Only set on the delete
+    /// filter; see [`Self::with_dangling_dvs_for`].
+    removed_data_file_paths: HashSet<String>,
+    /// Source manifest → rewritten result.
+    filtered: HashMap<ManifestKey, FilteredManifest>,
+    /// Format version the rewrites were written under. Per spec, v1 entries
+    /// cannot inherit sequence numbers, so an upgrade invalidates them.
+    format_version: Option<FormatVersion>,
+}
+
+/// One rewritten manifest and the files it marked as deleted.
+#[derive(Clone)]
+struct FilteredManifest {
+    manifest: ManifestFile,
+    removed_files: Vec<DataFile>,
+}
+
+/// The result of one filter pass.
+pub(crate) struct Filtered {
+    /// The resulting manifests, in input order.
+    pub manifests: Vec<ManifestFile>,

Review Comment:
   Ditto.



##########
crates/iceberg/src/transaction/snapshot/manifest_filter.rs:
##########
@@ -0,0 +1,316 @@
+// 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.
+
+//! Rewrites existing manifests to mark files as deleted.
+
+use std::collections::{HashMap, HashSet};
+
+use uuid::Uuid;
+
+use super::{manifest_path, new_manifest_writer};
+use crate::error::{Result, invalid_data};
+use crate::io::object_cache::ManifestKey;
+use crate::spec::{DataFile, DataFileFormat, FormatVersion, 
ManifestContentType, ManifestFile};
+use crate::table::Table;
+
+/// Identifies one entry to mark as `Deleted`, a data file or a delete file.
+///
+/// A path alone is not enough: a Puffin file may hold several deletion
+/// vectors, each its own entry at a distinct blob offset. Data files and
+/// non-DV delete files have no offset, so for them this is the path.
+#[derive(Clone, Debug, PartialEq, Eq, Hash)]
+struct RemovedFileIdentity {
+    /// The absolute path, as stored in the manifest entry. Comparison is
+    /// textual, so a relative path would not match the entry it names.
+    path: String,
+    content_offset: Option<i64>,
+    content_size_in_bytes: Option<i64>,
+}
+
+impl RemovedFileIdentity {
+    fn of(file: &DataFile) -> Self {
+        Self {
+            path: file.file_path().to_string(),
+            content_offset: file.content_offset(),
+            content_size_in_bytes: file.content_size_in_bytes(),
+        }
+    }
+}
+
+impl std::fmt::Display for RemovedFileIdentity {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        match (self.content_offset, self.content_size_in_bytes) {
+            (Some(offset), Some(size)) => write!(f, "{}@{offset}+{size}", 
self.path),
+            _ => f.write_str(&self.path),
+        }
+    }
+}
+
+/// Removes a fixed set of files from the manifests of one content type.
+///
+/// One manager lives for one logical execution of an action and is driven
+/// once per attempt via [`ManifestFilterManager::filter`]. A manifest that
+/// references none of the files passes through untouched. One that does is
+/// rewritten with those entries marked `Deleted` and the rest `Existing`.
+///
+/// A rewrite is reused across attempts while its inputs are unchanged. Its
+/// entries carry the sequence numbers and row ids the source's entries
+/// inherited from the manifest list when they were read, so the reuse key is
+/// the source's [`ManifestKey`], not its path alone: a transaction-local
+/// source manifest keeps its path across attempts but inherits new values
+/// after a rebase.
+pub(crate) struct ManifestFilterManager {
+    content: ManifestContentType,
+    /// The files to remove, by absolute path (and blob range for deletion
+    /// vectors). Fixed for the execution.
+    files_to_remove: HashSet<RemovedFileIdentity>,
+    /// Whether a file to remove that is not live in any manifest fails the
+    /// attempt. Off lets a retry succeed after a concurrent commit removed the
+    /// same file; the action decides which it needs.
+    fail_missing_delete_paths: bool,
+    /// Absolute paths of the data files the commit removes. A deletion vector
+    /// referencing one of them is dangling and is marked `Deleted` too. Not
+    /// required to be found, unlike `files_to_remove`. Only set on the delete
+    /// filter; see [`Self::with_dangling_dvs_for`].
+    removed_data_file_paths: HashSet<String>,
+    /// Source manifest → rewritten result.
+    filtered: HashMap<ManifestKey, FilteredManifest>,
+    /// Format version the rewrites were written under. Per spec, v1 entries
+    /// cannot inherit sequence numbers, so an upgrade invalidates them.
+    format_version: Option<FormatVersion>,
+}
+
+/// One rewritten manifest and the files it marked as deleted.
+#[derive(Clone)]
+struct FilteredManifest {
+    manifest: ManifestFile,
+    removed_files: Vec<DataFile>,
+}
+
+/// The result of one filter pass.
+pub(crate) struct Filtered {
+    /// The resulting manifests, in input order.
+    pub manifests: Vec<ManifestFile>,
+    /// The files that were live and are now marked deleted, including their
+    /// metrics as read from the source manifests.
+    pub removed_files: Vec<DataFile>,
+}
+
+impl ManifestFilterManager {
+    pub(crate) fn new(
+        content: ManifestContentType,
+        files_to_remove: &[DataFile],
+        fail_missing_delete_paths: bool,
+    ) -> Self {
+        Self {
+            content,
+            files_to_remove: files_to_remove
+                .iter()
+                .map(RemovedFileIdentity::of)
+                .collect(),
+            fail_missing_delete_paths,
+            removed_data_file_paths: HashSet::new(),
+            filtered: HashMap::new(),
+            format_version: None,
+        }
+    }
+
+    /// Also marks `Deleted` any deletion vector whose referenced data file is
+    /// among `removed_data_files`, as Java's `removeDanglingDeletesFor` does.
+    /// Only deletion vectors qualify: a position delete file's
+    /// `referenced_data_file` is a hint, not a guarantee of its contents.
+    pub(crate) fn with_dangling_dvs_for(mut self, removed_data_files: 
&[DataFile]) -> Self {

Review Comment:
   This will lead to invalid api call. A MainfestFilterManager should be 
constructed with filter conditions(files to delete, delete expression etc), and 
then call filter methods. I think we should create a builder for 
MainfestFilterManager, later calls should only change it bu calling `filter` or 
consume results.



##########
crates/iceberg/src/transaction/snapshot/manifest_filter.rs:
##########
@@ -0,0 +1,316 @@
+// 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.
+
+//! Rewrites existing manifests to mark files as deleted.
+
+use std::collections::{HashMap, HashSet};
+
+use uuid::Uuid;
+
+use super::{manifest_path, new_manifest_writer};
+use crate::error::{Result, invalid_data};
+use crate::io::object_cache::ManifestKey;
+use crate::spec::{DataFile, DataFileFormat, FormatVersion, 
ManifestContentType, ManifestFile};
+use crate::table::Table;
+
+/// Identifies one entry to mark as `Deleted`, a data file or a delete file.
+///
+/// A path alone is not enough: a Puffin file may hold several deletion
+/// vectors, each its own entry at a distinct blob offset. Data files and
+/// non-DV delete files have no offset, so for them this is the path.
+#[derive(Clone, Debug, PartialEq, Eq, Hash)]
+struct RemovedFileIdentity {
+    /// The absolute path, as stored in the manifest entry. Comparison is
+    /// textual, so a relative path would not match the entry it names.
+    path: String,
+    content_offset: Option<i64>,
+    content_size_in_bytes: Option<i64>,
+}
+
+impl RemovedFileIdentity {
+    fn of(file: &DataFile) -> Self {
+        Self {
+            path: file.file_path().to_string(),
+            content_offset: file.content_offset(),
+            content_size_in_bytes: file.content_size_in_bytes(),
+        }
+    }
+}
+
+impl std::fmt::Display for RemovedFileIdentity {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        match (self.content_offset, self.content_size_in_bytes) {
+            (Some(offset), Some(size)) => write!(f, "{}@{offset}+{size}", 
self.path),
+            _ => f.write_str(&self.path),
+        }
+    }
+}
+
+/// Removes a fixed set of files from the manifests of one content type.
+///
+/// One manager lives for one logical execution of an action and is driven
+/// once per attempt via [`ManifestFilterManager::filter`]. A manifest that
+/// references none of the files passes through untouched. One that does is
+/// rewritten with those entries marked `Deleted` and the rest `Existing`.
+///
+/// A rewrite is reused across attempts while its inputs are unchanged. Its
+/// entries carry the sequence numbers and row ids the source's entries
+/// inherited from the manifest list when they were read, so the reuse key is
+/// the source's [`ManifestKey`], not its path alone: a transaction-local
+/// source manifest keeps its path across attempts but inherits new values
+/// after a rebase.
+pub(crate) struct ManifestFilterManager {
+    content: ManifestContentType,
+    /// The files to remove, by absolute path (and blob range for deletion
+    /// vectors). Fixed for the execution.
+    files_to_remove: HashSet<RemovedFileIdentity>,
+    /// Whether a file to remove that is not live in any manifest fails the
+    /// attempt. Off lets a retry succeed after a concurrent commit removed the
+    /// same file; the action decides which it needs.
+    fail_missing_delete_paths: bool,
+    /// Absolute paths of the data files the commit removes. A deletion vector
+    /// referencing one of them is dangling and is marked `Deleted` too. Not
+    /// required to be found, unlike `files_to_remove`. Only set on the delete
+    /// filter; see [`Self::with_dangling_dvs_for`].
+    removed_data_file_paths: HashSet<String>,
+    /// Source manifest → rewritten result.
+    filtered: HashMap<ManifestKey, FilteredManifest>,
+    /// Format version the rewrites were written under. Per spec, v1 entries
+    /// cannot inherit sequence numbers, so an upgrade invalidates them.
+    format_version: Option<FormatVersion>,
+}
+
+/// One rewritten manifest and the files it marked as deleted.
+#[derive(Clone)]
+struct FilteredManifest {
+    manifest: ManifestFile,
+    removed_files: Vec<DataFile>,
+}
+
+/// The result of one filter pass.
+pub(crate) struct Filtered {
+    /// The resulting manifests, in input order.
+    pub manifests: Vec<ManifestFile>,
+    /// The files that were live and are now marked deleted, including their
+    /// metrics as read from the source manifests.
+    pub removed_files: Vec<DataFile>,
+}
+
+impl ManifestFilterManager {
+    pub(crate) fn new(
+        content: ManifestContentType,
+        files_to_remove: &[DataFile],
+        fail_missing_delete_paths: bool,
+    ) -> Self {
+        Self {
+            content,
+            files_to_remove: files_to_remove
+                .iter()
+                .map(RemovedFileIdentity::of)
+                .collect(),
+            fail_missing_delete_paths,
+            removed_data_file_paths: HashSet::new(),
+            filtered: HashMap::new(),
+            format_version: None,
+        }
+    }
+
+    /// Also marks `Deleted` any deletion vector whose referenced data file is
+    /// among `removed_data_files`, as Java's `removeDanglingDeletesFor` does.
+    /// Only deletion vectors qualify: a position delete file's
+    /// `referenced_data_file` is a hint, not a guarantee of its contents.
+    pub(crate) fn with_dangling_dvs_for(mut self, removed_data_files: 
&[DataFile]) -> Self {
+        debug_assert_eq!(self.content, ManifestContentType::Deletes);
+        self.removed_data_file_paths = removed_data_files
+            .iter()
+            .map(|f| f.file_path().to_string())
+            .collect();
+        self
+    }
+
+    /// Applies the removals to `manifests`, rewriting those of this manager's
+    /// content type that reference a file to remove.
+    ///
+    /// With `fail_missing_delete_paths`, fails if a file to remove is not live
+    /// in any manifest: it was never in the table, or a concurrent commit
+    /// already removed it. Otherwise such files are skipped.
+    ///
+    /// Rewritten manifests take their paths from `next_manifest_number` and 
are
+    /// recorded in `owned_artifacts` before being written, so a failed write
+    /// still leaves its path tracked for cleanup.
+    pub(crate) async fn filter(
+        &mut self,
+        table: &Table,
+        snapshot_id: i64,
+        commit_uuid: Uuid,
+        manifests: Vec<ManifestFile>,
+        next_manifest_number: &mut u64,
+        owned_artifacts: &mut HashSet<String>,
+    ) -> Result<Filtered> {
+        let format_version = table.metadata().format_version();
+        // The delete filter must still scan when no delete file is named but a
+        // removed data file may leave a DV dangling. DVs exist from v3, so on
+        // older tables nothing can dangle.
+        let may_have_dangling_dvs =
+            !matches!(format_version, FormatVersion::V1 | FormatVersion::V2)
+                && !self.removed_data_file_paths.is_empty();
+        if self.files_to_remove.is_empty() && !may_have_dangling_dvs {
+            return Ok(Filtered {
+                manifests,
+                removed_files: Vec::new(),
+            });
+        }
+
+        if self.format_version != Some(format_version) {

Review Comment:
   This is actually odd to me. I think `Table` should be passed as an argument 
of `ManifestFilterManager`?



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