Skip to content

Core: Extract commit-conflict validations into SnapshotValidator - #18699

Open
anoopj wants to merge 9 commits into
apache:mainfrom
anoopj:snapshot-validator
Open

anoopj wants to merge 9 commits into
apache:mainfrom
anoopj:snapshot-validator

Conversation

@anoopj

@anoopj anoopj commented Oct 29, 2026

Copy link
Copy Markdown
Member

Relocate the conflict validations out of MergingSnapshotProducer into a new SnapshotValidator class.

The protected validate* methods become thin delegators, so this is a behavior-preserving relocation.

Follow-up: migrate the producer call sites to build a single SnapshotValidator and reuse it across the commit retry loop instead of constructing one per call.

Relocate the conflict validations out of `MergingSnapshotProducer`
into a new `SnapshotValidator` class.

The protected validate* methods become thin delegators, so this
is a behavior-preserving relocation.

Follow-up: migrate the producer call sites to build a single
`SnapshotValidator` and reuse it across the commit retry loop
instead of constructing one per call.
Rewrap the forWindow Javadoc so spotlessJavaCheck passes.
* @param skipDeletes when true, removals by delete operations are ignored
*/
@SuppressWarnings("CollectionUndefinedEquality")
void validateDataFilesExist(CharSequenceSet requiredDataFiles, boolean skipDeletes) {

@anoopj anoopj Oct 29, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be nice to change this into a Set<String> instead, but could be done in the followup PR. Right now this PR is behavior preserving.

import org.apache.iceberg.util.PartitionSet;
import org.apache.iceberg.util.Tasks;

class SnapshotValidator {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This isn't validating a single snapshot, it is responsible for validating the assumptions of a commit. I think that CommitValidator would be a better name. I'm also fine with Validator.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree that CommitValidator is a better name. Validator is a bit ambiguous. I have renamed.

.startingSnapshotId(startingSnapshotId)
.caseSensitive(caseSensitive)
.forWindow(base, parent)
.validateAddedDataFiles(partitionSet);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is partitionSet an alternative to conflictDetectionFilter? Should it be configured the same way so that there is just one validateAddedDataFiles() call instead of two? Having two means that the conflict detection filter is ignored by the validator when the partition set version is called. I see that it is not set in actual uses, but the API allows you to set conflictDetectionFilter and also call validateAddedDataFiles(PartitionSet).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, they are alternatives, so allowing both can be a footgun. I am planning to remove the use of the PartitionSet though because we can derive it from the files. The only consumer of this API is ReplacePartition, so this is doable.

For this PR, I can make a change such that these are mutually exclusive. Please let me know.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it should be mutually exclusive. That should work for now given that all of the calls produce separate validators.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just made them mutually exclusive.

* Validates that no data files matching the conflict detection filter have been added to the
* table since the starting snapshot.
*/
void validateAddedDataFiles() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd like to make sure that the names of the validations are very clear. This one doesn't seem clear enough since it is not saying what constitutes a failure. Maybe it should be validateNoConflictingAddedDataFiles()? I think we should come up with a few options.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One alternative is validateNoConcurrentlyAddedDataFiles or we can just keep the "no new" convention and do validateNoNewMatchingDataFiles. I personally prefer validateNoConflictingAddedDataFiles.

For now, I renamed the checks as: validateNoConflictingAddedDataFiles, validateNoConflictingDeletedDataFiles, validateNoConflictingAddedDeleteFiles, validateNoConflictingDeletesForDataFiles, and validateNoConflictingAddedDVs. I used AddedDeleteFiles rather than DeleteFiles so it doesn't collide with the existing public RowDelta.validateNoConflictingDeleteFiles.

I left validateDataFilesExist since it looks like a reasonable name. Open to suggestions.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like "conflicting" because it implies the conflict detection filter was used. "New" makes it sound like any new file may cause a validation failure. I agree that validateDataFilesExist still makes sense.

For some of the others "NoConflicting" doesn't seem quite right. validateNoConflictingDeletedDataFiles in particular. It is not obvious to me how that differs from validateDataFilesExist since both cover that data files have not been deleted. I'll spend some time thinking through this.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! Let me know when you have an alternate suggestion.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I went through all of the validations and looked at what they are doing and where they are used. Here's a brief summary:

Logical checks that operating data has not changed:

  • Data files were added
    • Data files matching conflict filter (validateAddedDataFiles)
  • Data files are missing
    • Deletes matching conflict filter (validateDeletedDataFiles) - used for read/union/overwrite
    • Deleted files are missing (failMissingDeleteFiles) - also reference integrity
  • Delete files were added
    • Delete files matching conflict filter (validateNoNewDeleteFiles)
    • Delete files matching replaced data files (validateNoNewDeletesForDataFiles)

Physical checks for reference integrity

  • Data and delete files to remove were not already (failMissingDeletePaths)
  • New/updated DVs reference valid data files (validateDataFilesExist)
  • New/updated DVs are still valid (validateAddedDVs)

There are quite a few validations for row-level deletes, but I think that they are all distinct. validateAddedDVs is needed to check reference integrity, even if validateNoNewDeleteFiles is a broader validation because the logical check is only run when requested by the caller. That's why it is always used when there are DVs. I think that all 6 checks are currently needed.

To name these checks, I think that using validate is a little confusing. The original validation, validateAddedDataFiles checks that there are no concurrently added data files conflict (match the filter). But "validate" doesn't tell a reader what is being validated, just some logic for added data files is being run.

I think a better name is assert because it is clear for a reader that something should be true, just like in tests. For example, I think assertNoAddedDataFiles is a better name than validateAddedDataFiles. I recommend renaming the validation methods like this:

  • validateAddedDataFiles -> assertNoAddedDataFiles (matching the conflict filter is implied by config)
  • validateDeletedDataFiles -> assertNoDeletedDataFiles
  • validateDataFilesExist(Set<String>) -> assertDataFilesExist(Set<String>)
  • validateNoNewDeleteFiles -> assertNoNewPositionDeletes / assertNoNewRowDeletes
  • validateNoNewDeletesForDataFiles(Iterable<DataFile>) -> assertNoNewDeletesFor(Iterable<DataFile>)
  • validateAddedDVs -> assertNoNewPositionDeletesFor(String...)

Also, some of these assertions can use or validate one another. For instance, assertNoNewDeletesFor can be satisfied by assertNoNewPositionDeletesFor in v3 and later because the referenced data file is required.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for the detailed analysis on this. The naming makes sense to me. In fact, the assert* is what I also came up with originally, but I switched back to validate methods to be consistent with the current code and the Validator class name.

I will update them.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

BTW assertDataFilesExist still takes in a CharSequenceSet because the callers need to be migrated. I had noted that in a comment, and will do it in a followup.

# Conflicts:
#	core/src/main/java/org/apache/iceberg/MergingSnapshotProducer.java
return newSnapshots;
}

private static void addNewManifests(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Methods should do one thing and avoid side-effects. This one is doing too many things and makes the code that uses it hard to read.

A better alternative is to replace this with newDataManifests(snapshot) and newDeleteManifests(snapshot):

  private Iterable<ManifestFile> newDeleteManifests(Snapshot snapshot) {
    return Iterables.filter(
        snapshot.deleteManifests(io), manifest -> manifest.snapshotId() == snapshot.snapshotId());
  }

  private Iterable<ManifestFile> newDataManifests(Snapshot snapshot) {
    return Iterables.filter(
        snapshot.dataManifests(io), manifest -> manifest.snapshotId() == snapshot.snapshotId());
  }

Alternatively, you could pass DATA or DELETE like before, but that is just longer. Adding these methods allows the caller to use either method to get the correct list of manifests from a snapshot to add to the accumulated list, instead of using the method to filter by snapshot ID combined with adding them to a list.

Here's the cleaner end result for a caller:

    List<ManifestFile> addedDeleteManifests = Lists.newArrayList();
    validationHistory(
        VALIDATE_ADDED_DELETE_FILES_OPERATIONS,
        snapshot -> Iterables.addAll(addedDeleteManifests, newDeleteManifests(snapshot)));

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is is much nicer. Applied. Thanks!

});
}

private Object conflictScope() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Returning Object is a red flag.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed. Inlined the ternary at call sites.

* @param skipDeletes when true, removals by delete operations are ignored
*/
@SuppressWarnings("CollectionUndefinedEquality")
void validateDataFilesExist(CharSequenceSet requiredDataFiles, boolean skipDeletes) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was previously co-located with validateAddedDVs. I think it should still be just above that since that matches the order in MergingSnapshotProducer. Those two are related because they are both physical validations that DVs are correct and only used by RowDelta.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. assertDataFilesExist now sits directly above assertNoNewPositionDeletesFor matching MergingSnapshotProducer

return builder.build();
}

private static Set<String> referencedDeleteFileLocations(List<DeleteFileIndex> deleteIndexes) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's move private static methods to the bottom of the class to conform to the more typical class layout.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved.

.validateNoConflictingDeletedDataFiles();
}

protected void setNewDataFilesDataSequenceNumber(long sequenceNumber) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is strange to leave this method in the middle of validations. I'd relocate it to just after the other configuration methods and before the validations, or co-locate it with add(DataFile).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved it out of the validation methods: to before the validations

* Validates that no data files matching the conflict detection scope have been deleted from the
* table since the starting snapshot.
*/
void validateNoConflictingDeletedDataFiles() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This one also seems out of order to me. I'm checking methods in MergingSnapshotProducer and these are in a different order.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reordered to match MergingSnapshotProducer.


} catch (IOException e) {
throw new UncheckedIOException(
String.format("Failed to validate no deleted data files matching %s", conflictScope()),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why use conflictScope here but build a string just above? There isn't a benefit to lazily building the string because this is already in a block so it doesn't run unless the exception will be thrown. I think this should embed the null check to select which one will be used so that it is clear and avoids a method that returns Object.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. Inlined the null check here and removed conflictScope()

}
}

private CloseableIterable<ManifestEntry<DataFile>> deletedDataFiles(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't need to accept arguments. It is only called by validateNoConflictingDeletedDataFiles and is passed instance fields (conflictDetectionFilter and partitionSet).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, it's a no-arg helper reading the instance fields now.

CloseableIterable<ManifestEntry<DataFile>> conflictEntries =
deletedDataFiles(conflictDetectionFilter, partitionSet);

try (CloseableIterator<ManifestEntry<DataFile>> conflicts = conflictEntries.iterator()) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I get a warning that conflictEntries is used outside of a try-with-resources block. That's an easy fix:

  void validateNoConflictingDeletedDataFiles() {
    try (CloseableIterable<ManifestEntry<DataFile>> conflictEntries = deletedDataFiles()) {
      CloseableIterator<ManifestEntry<DataFile>> conflicts = conflictEntries.iterator();
      if (conflicts.hasNext()) {
        throw new ValidationException(
            "Found conflicting deleted files that can %s: %s",
            partitionSet != null
                ? "apply to records matching " + partitionSet
                : "contain records matching " + conflictDetectionFilter,
            Iterators.toString(
                Iterators.transform(conflicts, entry -> entry.file().location().toString())));
      }

    } catch (IOException e) {
      throw new UncheckedIOException(
          String.format("Failed to validate no deleted data files matching %s", conflictScope()),
          e);
    }
  }

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for catching that. Fixed.

ValidationException.check(
locations.isEmpty(),
"Found new conflicting delete files that can apply to records matching %s: %s",
conflictScope(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd like to remove conflictScope. If it is important to build the string lazily, then use an if rather than ValidationException.check.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed and inlined it.

* @param partitions a partition set used to find delete files
*/
private List<DeleteFileIndex> addedDeleteFilesIndexedPerSnapshot(
Expression dataFilter, PartitionSet partitions) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

validateNoConflictingAddedDeleteFiles passes both the conflict detection filter and the partition set, but validateNoConflictingDeletesForDataFiles passes the conflict detection filter and null.

I think that dataFilter is unnecessary because it is always the conflict detection filter. I also think it would be better to build a PartitionSet from the data files rather than passing null. That can be done later though.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed the dataFilter parameter. Will do the building of PartitionSet from the data files in a followup

* @param ignoreEqualityDeletes whether to ignore equality deletes during validation
*/
void validateNoConflictingDeletesForDataFiles(
Iterable<DataFile> dataFiles, boolean ignoreEqualityDeletes) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Boolean arguments like this should typically only be used for internal methods, not API methods. It would be better to break this into two API methods: validateNoConflictingPositionDeletesForDataFiles (ignore=true) and validateNoConflictingDeletesForDataFiles (ignore=false).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Split into assertNoNewDeletesFor and assertNoNewPositionDeletesFor as suggested

return deleteIndexes;
}

private DeleteFileIndex buildDeleteFileIndex(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1 to co-locating this by addedDeleteFilesIndexedPerSnapshot.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved it

}
}

private CloseableIterable<ManifestEntry<DataFile>> addedDataFiles(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is only called once and is always passed the same instance state. It can be a no-arg helper.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

*/
void validateNoConflictingAddedDataFiles() {
CloseableIterable<ManifestEntry<DataFile>> conflictEntries =
addedDataFiles(conflictDetectionFilter, partitionSet);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also add this to try-with-resources.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done.

return this;
}

CommitValidator scanWith(ExecutorService newWorkerPool) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This isn't passed to ManifestGroup in a few places where it could be. In a follow up, we should probably update it.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will fix it in a followup.

}

/**
* Binds the base metadata and parent snapshot the checks run against. Needs to be invoked before

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This isn't what we would call "binding" in most other areas of the codebase. I would use the term "set":

Sets the base metadata and parent snapshot to run checks against. Must be invoked before running validations.

Also, the "must be invoked before running validations" requirement is not enforced. For instance, validateNoConflictingAddedDataFiles immediately calls addedDataFiles and that returns CloseableIterable.empty() if parent == null. Failing to call setParent causes that validation to silently pass!

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Used your wording as-is. Also enforced it: a requireParentSet() guard runs first in every check and throws if setParent wasn't called.

return this;
}

CommitValidator partitionSet(PartitionSet newPartitionSet) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is only used by ReplacePartitions and in that case it is equivalent to conflictDetectionFilter. I think there should be a better name that makes it clear that this partition set is used to detect conflicts. What about naming this conflictDetectionPartitions or updatedPartitions?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Renamed to conflictDetectionPartitions.

@rdblue rdblue left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that this refactoring is correct, although I noted several things I'd change.

Wrap the conflict-detection reads in try-with-resources so the CloseableIterable is closed, remove the conflictScope() helper that returned Object by inlining the partition-set-or-filter choice at its use sites, and make the addedDataFiles() and deletedDataFiles() read helpers argument-light since they only read instance fields. Also reword the setParent Javadoc to say "set" and that it must be called before validations.
@anoopj
anoopj requested a review from rdblue November 4, 2026 06:41

@nastra nastra left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks for organizing the methods in a way that made it easy to review. I went through all the validations and compared them with the original ones and they look all correct to me. I left a few minor comments that would be good to address

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

Status: In review

Development

Successfully merging this pull request may close these issues.

3 participants