Repository navigation
Conversation
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) { |
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
I think it should be mutually exclusive. That should work for now given that all of the calls produce separate validators.
There was a problem hiding this comment.
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() { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Thanks! Let me know when you have an alternate suggestion.
There was a problem hiding this comment.
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 matching conflict filter (
- Data files are missing
- Deletes matching conflict filter (
validateDeletedDataFiles) - used for read/union/overwrite - Deleted files are missing (
failMissingDeleteFiles) - also reference integrity
- Deletes matching conflict filter (
- Delete files were added
- Delete files matching conflict filter (
validateNoNewDeleteFiles) - Delete files matching replaced data files (
validateNoNewDeletesForDataFiles)
- Delete files matching conflict filter (
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->assertNoDeletedDataFilesvalidateDataFilesExist(Set<String>)->assertDataFilesExist(Set<String>)validateNoNewDeleteFiles->assertNoNewPositionDeletes/assertNoNewRowDeletesvalidateNoNewDeletesForDataFiles(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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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)));There was a problem hiding this comment.
This is is much nicer. Applied. Thanks!
| }); | ||
| } | ||
|
|
||
| private Object conflictScope() { |
There was a problem hiding this comment.
Returning Object is a red flag.
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Done. assertDataFilesExist now sits directly above assertNoNewPositionDeletesFor matching MergingSnapshotProducer
| return builder.build(); | ||
| } | ||
|
|
||
| private static Set<String> referencedDeleteFileLocations(List<DeleteFileIndex> deleteIndexes) { |
There was a problem hiding this comment.
Let's move private static methods to the bottom of the class to conform to the more typical class layout.
| .validateNoConflictingDeletedDataFiles(); | ||
| } | ||
|
|
||
| protected void setNewDataFilesDataSequenceNumber(long sequenceNumber) { |
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
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() { |
There was a problem hiding this comment.
This one also seems out of order to me. I'm checking methods in MergingSnapshotProducer and these are in a different order.
There was a problem hiding this comment.
Reordered to match MergingSnapshotProducer.
|
|
||
| } catch (IOException e) { | ||
| throw new UncheckedIOException( | ||
| String.format("Failed to validate no deleted data files matching %s", conflictScope()), |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Done. Inlined the null check here and removed conflictScope()
| } | ||
| } | ||
|
|
||
| private CloseableIterable<ManifestEntry<DataFile>> deletedDataFiles( |
There was a problem hiding this comment.
This doesn't need to accept arguments. It is only called by validateNoConflictingDeletedDataFiles and is passed instance fields (conflictDetectionFilter and partitionSet).
There was a problem hiding this comment.
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()) { |
There was a problem hiding this comment.
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);
}
}There was a problem hiding this comment.
Thanks for catching that. Fixed.
| ValidationException.check( | ||
| locations.isEmpty(), | ||
| "Found new conflicting delete files that can apply to records matching %s: %s", | ||
| conflictScope(), |
There was a problem hiding this comment.
I'd like to remove conflictScope. If it is important to build the string lazily, then use an if rather than ValidationException.check.
| * @param partitions a partition set used to find delete files | ||
| */ | ||
| private List<DeleteFileIndex> addedDeleteFilesIndexedPerSnapshot( | ||
| Expression dataFilter, PartitionSet partitions) { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
Split into assertNoNewDeletesFor and assertNoNewPositionDeletesFor as suggested
| return deleteIndexes; | ||
| } | ||
|
|
||
| private DeleteFileIndex buildDeleteFileIndex( |
There was a problem hiding this comment.
+1 to co-locating this by addedDeleteFilesIndexedPerSnapshot.
| } | ||
| } | ||
|
|
||
| private CloseableIterable<ManifestEntry<DataFile>> addedDataFiles( |
There was a problem hiding this comment.
This is only called once and is always passed the same instance state. It can be a no-arg helper.
| */ | ||
| void validateNoConflictingAddedDataFiles() { | ||
| CloseableIterable<ManifestEntry<DataFile>> conflictEntries = | ||
| addedDataFiles(conflictDetectionFilter, partitionSet); |
There was a problem hiding this comment.
Also add this to try-with-resources.
| return this; | ||
| } | ||
|
|
||
| CommitValidator scanWith(ExecutorService newWorkerPool) { |
There was a problem hiding this comment.
This isn't passed to ManifestGroup in a few places where it could be. In a follow up, we should probably update it.
There was a problem hiding this comment.
I will fix it in a followup.
| } | ||
|
|
||
| /** | ||
| * Binds the base metadata and parent snapshot the checks run against. Needs to be invoked before |
There was a problem hiding this comment.
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!
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
Renamed to conflictDetectionPartitions.
rdblue
left a comment
There was a problem hiding this comment.
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.
nastra
left a comment
There was a problem hiding this comment.
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
Relocate the conflict validations out of
MergingSnapshotProducerinto a newSnapshotValidatorclass.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
SnapshotValidatorand reuse it across the commit retry loop instead of constructing one per call.