mxm commented on code in PR #16220:
URL: https://github.com/apache/iceberg/pull/16220#discussion_r4666126515
##########
spark/v4.2/spark/src/main/java/org/apache/iceberg/spark/actions/RewriteTablePathSparkAction.java:
##########
@@ -326,10 +326,32 @@ private Result rebuildMetadata() {
// rebuild manifest files
RewriteContentFileResult rewriteManifestResult =
rewriteManifests(
- deltaSnapshots,
- endMetadata,
- manifestFiles,
- sparkContext().broadcast(rewrittenDeleteFileSizes));
+ endMetadata, manifestFiles,
sparkContext().broadcast(rewrittenDeleteFileSizes));
+
+ // For incremental copies, filter out files that were already copied by a
previous replication.
+ // Prefer the target copy of the start version (dedup by target path),
which retains everything
+ // previously replicated even when source snapshots have since been
expired. If the target is
+ // not readable (e.g. files were not physically copied), fall back to the
start version on the
+ // source (dedup by source path).
+ if (startMetadata != null && !rewriteManifestResult.copyPlan().isEmpty()) {
Review Comment:
Do we need the dedup? Incremental copies seem fine with the snapshot ID
filter, since all snapshots after the start version are in the metadata log.
Only full copies can lose files, once versions are removed. Could we skip the
filter only when `startVersion` is not set?
##########
spark/v4.2/spark/src/main/java/org/apache/iceberg/spark/actions/RewriteTablePathSparkAction.java:
##########
@@ -326,10 +326,32 @@ private Result rebuildMetadata() {
// rebuild manifest files
RewriteContentFileResult rewriteManifestResult =
rewriteManifests(
- deltaSnapshots,
- endMetadata,
- manifestFiles,
- sparkContext().broadcast(rewrittenDeleteFileSizes));
+ endMetadata, manifestFiles,
sparkContext().broadcast(rewrittenDeleteFileSizes));
+
+ // For incremental copies, filter out files that were already copied by a
previous replication.
+ // Prefer the target copy of the start version (dedup by target path),
which retains everything
+ // previously replicated even when source snapshots have since been
expired. If the target is
+ // not readable (e.g. files were not physically copied), fall back to the
start version on the
+ // source (dedup by source path).
+ if (startMetadata != null && !rewriteManifestResult.copyPlan().isEmpty()) {
+ try {
+ String targetStartVersion =
+ RewriteTablePathUtil.newPath(startVersionName, sourcePrefix,
targetPrefix);
+ Set<String> targetPaths = readContentFilePaths(targetStartVersion);
+ rewriteManifestResult.copyPlan().removeIf(pair ->
targetPaths.contains(pair.second()));
+ } catch (Exception fromTarget) {
+ try {
+ Set<String> sourcePaths = readContentFilePaths(startVersionName);
+ rewriteManifestResult.copyPlan().removeIf(pair ->
sourcePaths.contains(pair.first()));
Review Comment:
For position delete files and DVs `pair.first()` is the staging path, so
`removeIf` never matches and always copies them. Could we map `sourcePaths`
with `newPath` and compare `pair.second()` as in the target branch?
##########
spark/v4.2/spark/src/main/java/org/apache/iceberg/spark/actions/RewriteTablePathSparkAction.java:
##########
@@ -366,6 +388,16 @@ private Result rebuildMetadata() {
return builder.fileListLocation(fileListLocation).build();
}
+ /**
+ * Read the set of content file paths referenced by the given metadata
version. Used to dedup
+ * incremental copies against files that were already replicated.
+ */
+ private Set<String> readContentFilePaths(String metadataFileLocation) {
+ Table startTable = newStaticTable(metadataFileLocation, table.io());
+ return Sets.newHashSet(
+
contentFileDS(startTable).select("path").as(Encoders.STRING()).collectAsList());
Review Comment:
Is this OK for tables with hundreds of millions of files? The driver now
holds the paths of all live files of the start version (all snapshots), and the
plan before the dedup has every live entry of the rewritten manifests. Before,
an incremental copy only held the delta. Could we do the anti-join in Spark?
##########
spark/v4.2/spark/src/test/java/org/apache/iceberg/spark/actions/TestRewriteTablePathsAction.java:
##########
@@ -1026,8 +1134,9 @@ public void
testFullTableRewritePathWithDeletedVersionFiles() throws Exception {
// the first snapshot
// from the version file history
int missingVersionFile = 1;
- // since first snapshot cannot be found, first data files will also be
skipped
- int missingDataFile = 1;
+ // the first snapshot was expired, but its data file is still live and
+ // included in the copy plan
+ int missingDataFile = 0;
Review Comment:
NIT: `missingDataFile` is always 0 now. Could we drop it and its term in the
`checkFileNum` expression below?
##########
spark/v4.2/spark/src/test/java/org/apache/iceberg/spark/actions/TestRewriteTablePathsAction.java:
##########
@@ -370,6 +370,114 @@ public void testIncrementalRewrite() throws Exception {
assertEquals("Rows should match after copy", expected, actual);
}
+ @TestTemplate
+ public void testIncrementalRewriteWithRewriteManifestsAndExpire() throws
Exception {
+ String location = newTableLocation();
+ Table sourceTable =
+ TABLES.create(SCHEMA, PartitionSpec.unpartitioned(),
Maps.newHashMap(), location);
+
+ // Write 2 initial snapshots
+ List<ThreeColumnRecord> recordsA =
+ Lists.newArrayList(new ThreeColumnRecord(1, "AAAAAAAAAA", "AAAA"));
+ Dataset<Row> dfA = spark.createDataFrame(recordsA,
ThreeColumnRecord.class).coalesce(1);
+ dfA.select("c1", "c2",
"c3").write().format("iceberg").mode("append").save(location);
+
+ List<ThreeColumnRecord> recordsB =
+ Lists.newArrayList(new ThreeColumnRecord(2, "BBBBBBBBBB", "BBBB"));
+ Dataset<Row> dfB = spark.createDataFrame(recordsB,
ThreeColumnRecord.class).coalesce(1);
+ dfB.select("c1", "c2",
"c3").write().format("iceberg").mode("append").save(location);
+ sourceTable.refresh();
+
+ // Full replication
+ RewriteTablePath.Result initialResult =
+ actions()
+ .rewriteTablePath(sourceTable)
+ .rewriteLocationPrefix(sourceTable.location(),
targetTableLocation())
+ .stagingLocation(stagingLocation())
+ .execute();
+ copyTableFiles(initialResult);
+
assertThat(spark.read().format("iceberg").load(targetTableLocation()).collectAsList())
+ .hasSize(2);
+
+ // Append new data
+ List<ThreeColumnRecord> recordsC =
+ Lists.newArrayList(new ThreeColumnRecord(3, "CCCCCCCCCC", "CCCC"));
+ Dataset<Row> dfC = spark.createDataFrame(recordsC,
ThreeColumnRecord.class).coalesce(1);
+ dfC.select("c1", "c2",
"c3").write().format("iceberg").mode("append").save(location);
+ sourceTable.refresh();
+
+ // RewriteManifests merges all manifests
+ actions().rewriteManifests(sourceTable).execute();
+ sourceTable.refresh();
+
+ // Expire old snapshots including the one that added file C
+ actions()
+ .expireSnapshots(sourceTable)
+ .retainLast(1)
+ .expireOlderThan(sourceTable.currentSnapshot().timestampMillis() + 1)
+ .execute();
+ sourceTable.refresh();
+
+ // Incremental replication should still copy file C
+ Table targetTable = TABLES.load(targetTableLocation());
+ String startVersion =
fileName(currentMetadata(targetTable).metadataFileLocation());
+ RewriteTablePath.Result incrementalResult =
+ actions()
+ .rewriteTablePath(sourceTable)
+ .rewriteLocationPrefix(sourceTable.location(),
targetTableLocation())
+ .stagingLocation(stagingLocation())
+ .startVersion(startVersion)
+ .execute();
+ copyTableFiles(incrementalResult);
+
+ // Dedup check: files A and B were already replicated by the initial copy,
so the incremental
+ // copy plan must contain only the newly appended data file (C).
+ List<Tuple2<String, String>> incrementalPaths =
+ readPathPairList(incrementalResult.fileListLocation());
+ assertThat(
+ incrementalPaths.stream()
+ .filter(p -> p._1().contains("/data/") &&
p._1().endsWith(".parquet")))
+ .as("Only the newly appended data file (C) should be copied
incrementally")
+ .hasSize(1);
+
+ List<Object[]> actual = rowsSorted(targetTableLocation(), "c1");
+ List<Object[]> expected = rowsSorted(location, "c1");
+ assertEquals(
+ "Rows should match after incremental copy with expired snapshots",
expected, actual);
+ }
+
+ @TestTemplate
+ public void testFullCopyWithRewriteManifestsAndExpire() throws Exception {
Review Comment:
This test also passes without the main change, because the version files in
the metadata log still list the expired snapshots. Could we truncate the log,
e.g. `write.metadata.previous-versions-max` of 1 and one more commit after the
expire, so it fails without the fix?
##########
core/src/main/java/org/apache/iceberg/RewriteTablePathUtil.java:
##########
@@ -461,6 +489,46 @@ public static RewriteResult<DeleteFile>
rewriteDeleteManifest(
return result;
}
+ /**
+ * Rewrite a delete manifest, replacing path references. All live entries
are included in the copy
+ * plan regardless of the snapshot that added them.
+ *
+ * @param manifestFile source delete manifest to rewrite
+ * @param outputFile output file to rewrite manifest file to
+ * @param io file io
+ * @param format format of the manifest file
+ * @param specsById map of partition specs by id
+ * @param sourcePrefix source prefix that will be replaced
+ * @param targetPrefix target prefix that will replace it
+ * @param stagingLocation staging location for rewritten position delete
files
+ * @param rewrittenDeleteFileSizes map from source position delete file path
to the actual size of
+ * the rewritten file; entries absent from the map keep their original
size
+ * @return a copy plan of content files in the manifest that was rewritten
+ */
+ public static RewriteResult<DeleteFile> rewriteDeleteManifest(
Review Comment:
Do we need the new public overloads? This one has the same arity as the
overload removed in #18334, which is why it needs six revapi entries. Could the
existing methods accept `null` for `snapshotIds` as no filter, alongside a java
doc?
##########
core/src/main/java/org/apache/iceberg/RewriteTablePathUtil.java:
##########
@@ -480,15 +548,22 @@ private static RewriteResult<DataFile> writeDataFileEntry(
DataFile newDataFile =
DataFiles.builder(spec).copy(entry.file()).withPath(targetDataFilePath).build();
appendEntryWithFile(entry, writer, newDataFile);
- // keep the following entries in metadata but exclude them from copyPlan
- // 1) deleted data files
- // 2) entries not changed by snapshotIds
- if (entry.isLive() && snapshotIds.contains(entry.snapshotId())) {
+ if (includeInCopyPlan(entry, snapshotIds)) {
result.copyPlan().add(Pair.of(sourceDataFilePath,
newDataFile.location()));
}
return result;
}
+ /**
+ * Whether a manifest entry should be added to the copy plan. Every live
entry is included; when
Review Comment:
NIT: Could we drop this Javadoc? It is a private method, the "legacy
filtering" is described in other places, and the snapshotIds parameter can be
annotated `@Nullable`.
##########
spark/v4.2/spark/src/main/java/org/apache/iceberg/spark/actions/RewriteTablePathSparkAction.java:
##########
@@ -326,10 +326,32 @@ private Result rebuildMetadata() {
// rebuild manifest files
RewriteContentFileResult rewriteManifestResult =
rewriteManifests(
- deltaSnapshots,
- endMetadata,
- manifestFiles,
- sparkContext().broadcast(rewrittenDeleteFileSizes));
+ endMetadata, manifestFiles,
sparkContext().broadcast(rewrittenDeleteFileSizes));
+
+ // For incremental copies, filter out files that were already copied by a
previous replication.
+ // Prefer the target copy of the start version (dedup by target path),
which retains everything
+ // previously replicated even when source snapshots have since been
expired. If the target is
+ // not readable (e.g. files were not physically copied), fall back to the
start version on the
+ // source (dedup by source path).
+ if (startMetadata != null && !rewriteManifestResult.copyPlan().isEmpty()) {
+ try {
+ String targetStartVersion =
+ RewriteTablePathUtil.newPath(startVersionName, sourcePrefix,
targetPrefix);
+ Set<String> targetPaths = readContentFilePaths(targetStartVersion);
+ rewriteManifestResult.copyPlan().removeIf(pair ->
targetPaths.contains(pair.second()));
+ } catch (Exception fromTarget) {
Review Comment:
We should log the fallback behavior here. Also, let's decide on either
inferring already-copied files from the source or the target directory. Doing
both is doing a bit too much.
##########
spark/v4.2/spark/src/test/java/org/apache/iceberg/spark/actions/TestRewriteTablePathsAction.java:
##########
@@ -370,6 +370,114 @@ public void testIncrementalRewrite() throws Exception {
assertEquals("Rows should match after copy", expected, actual);
}
+ @TestTemplate
+ public void testIncrementalRewriteWithRewriteManifestsAndExpire() throws
Exception {
Review Comment:
Could we add an incremental test with a position delete file or a DV? No
`startVersion` test uses delete files, and this PR changes the delete manifest
path.
##########
core/src/main/java/org/apache/iceberg/RewriteTablePathUtil.java:
##########
@@ -527,11 +599,7 @@ private static RewriteResult<DeleteFile>
writeDeleteFileEntry(
case EQUALITY_DELETES:
DeleteFile eqDeleteFile = newEqualityDeleteEntry(file, spec,
sourcePrefix, targetPrefix);
appendEntryWithFile(entry, writer, eqDeleteFile);
- // keep the following entries in metadata but exclude them from
copyPlan
- // 1) deleted equality delete files
- // 2) entries not changed by snapshotIds
- if (entry.isLive() && snapshotIds.contains(entry.snapshotId())) {
- // No need to rewrite equality delete files as they do not contain
absolute file paths.
+ if (includeInCopyPlan(entry, snapshotIds)) {
result.copyPlan().add(Pair.of(file.location(),
eqDeleteFile.location()));
Review Comment:
NIT: Could we keep the comment `No need to rewrite equality delete files as
they do not contain absolute file paths.`? It is still accurate.
##########
spark/v4.2/spark/src/main/java/org/apache/iceberg/spark/actions/RewriteTablePathSparkAction.java:
##########
@@ -326,10 +326,32 @@ private Result rebuildMetadata() {
// rebuild manifest files
RewriteContentFileResult rewriteManifestResult =
rewriteManifests(
- deltaSnapshots,
- endMetadata,
- manifestFiles,
- sparkContext().broadcast(rewrittenDeleteFileSizes));
+ endMetadata, manifestFiles,
sparkContext().broadcast(rewrittenDeleteFileSizes));
+
+ // For incremental copies, filter out files that were already copied by a
previous replication.
+ // Prefer the target copy of the start version (dedup by target path),
which retains everything
+ // previously replicated even when source snapshots have since been
expired. If the target is
+ // not readable (e.g. files were not physically copied), fall back to the
start version on the
+ // source (dedup by source path).
+ if (startMetadata != null && !rewriteManifestResult.copyPlan().isEmpty()) {
+ try {
+ String targetStartVersion =
+ RewriteTablePathUtil.newPath(startVersionName, sourcePrefix,
targetPrefix);
+ Set<String> targetPaths = readContentFilePaths(targetStartVersion);
Review Comment:
Is the target opened with the source `FileIO`? That may not always work.
--
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]