Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import org.apache.flink.annotation.Internal;
import org.apache.flink.api.connector.sink2.Committer;
import org.apache.flink.core.io.SimpleVersionedSerialization;
import org.apache.iceberg.AppendFiles;
import org.apache.iceberg.ManifestFile;
import org.apache.iceberg.ReplacePartitions;
import org.apache.iceberg.RowDelta;
Expand Down Expand Up @@ -302,30 +303,56 @@ private void commitDeltaTxn(
CommitSummary summary,
String newFlinkJobId,
String operatorId) {
for (Map.Entry<Long, List<WriteResult>> e : pendingResults.entrySet()) {
long checkpointId = e.getKey();
List<WriteResult> writeResults = e.getValue();
Copy link
Contributor

Choose a reason for hiding this comment

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

Can we keep the loop structure? We will need it for both types of snapshots. This should work:

  for (Map.Entry<Long, List<WriteResult>> e : pendingResults.entrySet()) {
    long checkpointId = e.getKey();
    List<WriteResult> writeResults = e.getValue();

    boolean appendOnly = true;
    for (WriteResult writeResult : writeResults) {
      if (writeResult.deleteFiles().length > 0) {
        appendOnly = false;
        break;
      }
    }

    final SnapshotUpdate snapshotUpdate;
    if (appendOnly) {
        AppendFiles appendFiles = table.newAppend().scanManifestsWith(workerPool);
        for (WriteResult result : writeResults) {
          Arrays.stream(result.dataFiles()).forEach(appendFiles::appendFile);
        }
        snapshotUpdate = appendFiles
    } else {
        RowDelta rowDelta = table.newRowDelta().scanManifestsWith(workerPool);
        for (WriteResult result : writeResults) {
          Arrays.stream(result.dataFiles()).forEach(rowDelta::addRows);
          Arrays.stream(result.deleteFiles()).forEach(rowDelta::addDeletes);
        }
       snapshotUpdate = rowDelta;
    }
   
    commitOperation(
          table,
          branch,
          snapshotUpdate,
          summary,
          appendOnly ? "append" : "rowDelta",
          newFlinkJobId,
          operatorId,
          checkpointId);
  }

Copy link
Author

Choose a reason for hiding this comment

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

this looks good - only thing left is the checkState for result.referencedDataFiles().length == 0 (which exists in IcebergSink) which I will add to the loop checking it is appendOnly


RowDelta rowDelta = table.newRowDelta().scanManifestsWith(workerPool);
for (WriteResult result : writeResults) {
// Row delta validations are not needed for streaming changes that write equality deletes.
// Equality deletes are applied to data in all previous sequence numbers, so retries may
// push deletes further in the future, but do not affect correctness. Position deletes
// committed to the table in this path are used only to delete rows from data files that are
// being added in this commit. There is no way for data files added along with the delete
// files to be concurrently removed, so there is no need to validate the files referenced by
// the position delete files that are being committed.
Arrays.stream(result.dataFiles()).forEach(rowDelta::addRows);
Arrays.stream(result.deleteFiles()).forEach(rowDelta::addDeletes);
if (summary.deleteFilesCount() == 0) {
Copy link
Contributor

Choose a reason for hiding this comment

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

I'm not sure about the granularity of this value, as every pending result could contain or not contain deletes. Probably best to check the WriteResults directly.

Copy link
Contributor

Choose a reason for hiding this comment

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

The deleteFilesCount should be correct.

This is how it is calculated:

And internally:

public void addAll(NavigableMap<Long, List<WriteResult>> pendingResults) {
pendingResults.values().forEach(writeResults -> writeResults.forEach(this::addWriteResult));
}
private void addWriteResult(WriteResult writeResult) {
dataFilesCount.addAndGet(writeResult.dataFiles().length);
Arrays.stream(writeResult.dataFiles())
.forEach(
dataFile -> {
dataFilesRecordCount.addAndGet(dataFile.recordCount());
dataFilesByteCount.addAndGet(dataFile.fileSizeInBytes());
});
deleteFilesCount.addAndGet(writeResult.deleteFiles().length);
Arrays.stream(writeResult.deleteFiles())
.forEach(
deleteFile -> {
deleteFilesRecordCount.addAndGet(deleteFile.recordCount());
long deleteBytes = ScanTaskUtil.contentSizeInBytes(deleteFile);
deleteFilesByteCount.addAndGet(deleteBytes);
});
}

Copy link
Contributor

@mxm mxm Nov 11, 2025

Choose a reason for hiding this comment

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

The value is correct but we commit at checkpoint level and the delete file count is done across checkpoints. Strictly speaking, there could be both append-only checkpoints and overwrite checkpoints as part of pendingResults.

Copy link
Contributor

Choose a reason for hiding this comment

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

Interesting decision.
In IcebergSink we commit multiple checkpoints together in a single commit, if we happen to accumulate multiple of them.

Copy link
Contributor

Choose a reason for hiding this comment

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

When we fixed #14182, we decided not to do that. In fact, you proposed not to do that: #14182 (comment) 🤓

IMHO this kind of optimization is a bit premature. In practice it is rare to even have multiple pending checkpoints.

Copy link
Contributor

Choose a reason for hiding this comment

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

Also, as I have mentioned in the comment, this could cause issues if "replacePartition" is used

Copy link
Contributor

Choose a reason for hiding this comment

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

So we should commit them 1-by-1

// Use append snapshot operation where possible
AppendFiles appendFiles = table.newAppend().scanManifestsWith(workerPool);
for (List<WriteResult> resultList : pendingResults.values()) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Can we move this loop up one level, as in https://github.com/apache/iceberg/pull/14559/files#r2513719871? This avoids repeating it.

for (WriteResult result : resultList) {
Preconditions.checkState(
result.referencedDataFiles().length == 0,
"Should have no referenced data files for append.");
Arrays.stream(result.dataFiles()).forEach(appendFiles::appendFile);
}
}

// Every Flink checkpoint contains a set of independent changes which can be committed
// together. While it is technically feasible to combine append-only data across checkpoints,
// for the sake of simplicity, we do not implement this (premature) optimization. Multiple
// pending checkpoints here are very rare to occur, i.e. only with very short checkpoint
// intervals or when concurrent checkpointing is enabled.
commitOperation(
table, branch, rowDelta, summary, "rowDelta", newFlinkJobId, operatorId, checkpointId);
table,
branch,
appendFiles,
summary,
"append",
newFlinkJobId,
operatorId,
pendingResults.lastKey());
} else {
for (Map.Entry<Long, List<WriteResult>> e : pendingResults.entrySet()) {
long checkpointId = e.getKey();
List<WriteResult> writeResults = e.getValue();

RowDelta rowDelta = table.newRowDelta().scanManifestsWith(workerPool);
for (WriteResult result : writeResults) {
// Row delta validations are not needed for streaming changes that write equality deletes.
// Equality deletes are applied to data in all previous sequence numbers, so retries may
// push deletes further in the future, but do not affect correctness. Position deletes
// committed to the table in this path are used only to delete rows from data files that
// are
// being added in this commit. There is no way for data files added along with the delete
// files to be concurrently removed, so there is no need to validate the files referenced
// by
// the position delete files that are being committed.
Arrays.stream(result.dataFiles()).forEach(rowDelta::addRows);
Arrays.stream(result.deleteFiles()).forEach(rowDelta::addDeletes);
}

// Every Flink checkpoint contains a set of independent changes which can be committed
// together. While it is technically feasible to combine append-only data across
// checkpoints,
// for the sake of simplicity, we do not implement this (premature) optimization. Multiple
// pending checkpoints here are very rare to occur, i.e. only with very short checkpoint
// intervals or when concurrent checkpointing is enabled.
commitOperation(
table, branch, rowDelta, summary, "rowDelta", newFlinkJobId, operatorId, checkpointId);
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -591,6 +591,71 @@ void testTableBranchAtomicCommitWithFailures() throws Exception {
.build());
}

@Test
void testCommitDeltaTxnWithAppendFiles() throws Exception {
Table table = catalog.loadTable(TableIdentifier.of(TABLE1));
assertThat(table.snapshots()).isEmpty();

DynamicWriteResultAggregator aggregator =
new DynamicWriteResultAggregator(CATALOG_EXTENSION.catalogLoader(), cacheMaximumSize);
OneInputStreamOperatorTestHarness aggregatorHarness =
new OneInputStreamOperatorTestHarness(aggregator);
aggregatorHarness.open();

WriteTarget writeTarget1 =
new WriteTarget(TABLE1, "branch1", 42, 0, true, Sets.newHashSet(1, 2));
WriteTarget writeTarget2 = new WriteTarget(TABLE1, "branch1", 23, 0, true, Sets.newHashSet());

WriteResult writeResult1 = WriteResult.builder().addDataFiles(DATA_FILE).build();
WriteResult writeResult2 = WriteResult.builder().addDataFiles(DATA_FILE_2).build();

final String jobId = JobID.generate().toHexString();
final String operatorId = new OperatorID().toHexString();
final int checkpointId = 1;

byte[] deltaManifest1 =
aggregator.writeToManifest(
writeTarget1,
Sets.newHashSet(new DynamicWriteResult(writeTarget1, writeResult1)),
checkpointId);

CommitRequest<DynamicCommittable> commitRequest1 =
new MockCommitRequest<>(
new DynamicCommittable(writeTarget1, deltaManifest1, jobId, operatorId, checkpointId));

byte[] deltaManifest2 =
aggregator.writeToManifest(
writeTarget2,
Sets.newHashSet(new DynamicWriteResult(writeTarget2, writeResult2)),
checkpointId);

CommitRequest<DynamicCommittable> commitRequest2 =
new MockCommitRequest<>(
new DynamicCommittable(writeTarget2, deltaManifest2, jobId, operatorId, checkpointId));

boolean overwriteMode = false;
int workerPoolSize = 1;
String sinkId = "sinkId";
UnregisteredMetricsGroup metricGroup = new UnregisteredMetricsGroup();
DynamicCommitterMetrics committerMetrics = new DynamicCommitterMetrics(metricGroup);
DynamicCommitter dynamicCommitter =
new DynamicCommitter(
CATALOG_EXTENSION.catalog(),
Maps.newHashMap(),
overwriteMode,
workerPoolSize,
sinkId,
committerMetrics);

dynamicCommitter.commit(Sets.newHashSet(commitRequest1, commitRequest2));

table.refresh();
assertThat(table.snapshots()).hasSize(1);

Snapshot snapshot = Iterables.getFirst(table.snapshots(), null);
assertThat(snapshot.operation()).isEqualTo("append");
}

@Test
void testReplacePartitions() throws Exception {
Table table1 = catalog.loadTable(TableIdentifier.of(TABLE1));
Expand Down