mxm commented on code in PR #15996:
URL: https://github.com/apache/iceberg/pull/15996#discussion_r3147260722


##########
flink/v2.1/flink/src/main/java/org/apache/iceberg/flink/maintenance/operator/EqualityConvertCommitter.java:
##########
@@ -0,0 +1,407 @@
+/*
+ * 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.
+ */
+package org.apache.iceberg.flink.maintenance.operator;
+
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.api.common.state.ListState;
+import org.apache.flink.api.common.state.ListStateDescriptor;
+import org.apache.flink.api.common.typeinfo.TypeInformation;
+import org.apache.flink.api.common.typeinfo.Types;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.MetricGroup;
+import org.apache.flink.runtime.state.StateInitializationContext;
+import org.apache.flink.runtime.state.StateSnapshotContext;
+import org.apache.flink.streaming.api.operators.AbstractStreamOperator;
+import org.apache.flink.streaming.api.operators.TwoInputStreamOperator;
+import org.apache.flink.streaming.api.watermark.Watermark;
+import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
+import org.apache.iceberg.DataFile;
+import org.apache.iceberg.DeleteFile;
+import org.apache.iceberg.RowDelta;
+import org.apache.iceberg.Snapshot;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.flink.TableLoader;
+import org.apache.iceberg.flink.maintenance.api.Trigger;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.util.ContentFileUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Commits data files and DVs to the main branch. Receives {@link 
DVMergeResult}s from parallel
+ * {@link EqualityConvertDVMerger} instances (input 1) and an {@link 
EqualityConvertPlanResult} from
+ * the planner (input 2). Assembles the final file lists and commits using a 
{@link RowDelta}
+ * operation once the plan result and done-timestamp watermark have both 
arrived.
+ *
+ * <p>Watermarks are absorbed while a cycle is active.
+ *
+ * <p>Emits a {@link Trigger} after each cycle (commit, no-op, or error) so 
the downstream {@link
+ * TaskResultAggregator} can track task completion. This is the sole source of 
Trigger records for
+ * the Aggregator.
+ */
+@Internal
+public class EqualityConvertCommitter extends AbstractStreamOperator<Trigger>
+    implements TwoInputStreamOperator<DVMergeResult, 
EqualityConvertPlanResult, Trigger> {
+
+  private static final Logger LOG = 
LoggerFactory.getLogger(EqualityConvertCommitter.class);
+
+  static final String COMMITTED_STAGING_SNAPSHOT_PROPERTY = 
"equality-convert-staging-snapshot";
+
+  private static final String ADDED_DV_NUM_METRIC = "addedDvNum";
+  private static final String COMMIT_DURATION_MS_METRIC = "commitDurationMs";
+
+  private final String tableName;
+  private final String taskName;
+  private final int taskIndex;
+  private final TableLoader tableLoader;
+  private final String targetBranch;
+
+  private transient Table table;
+  private transient List<DVMergeResult> bufferedResults;
+  private transient EqualityConvertPlanResult planResult;
+  private transient Watermark pendingMark;
+
+  private transient ListState<Long> lastCommittedMainSnapshotListState;
+  private transient ListState<DVMergeResult> bufferedResultsState;
+  private transient ListState<EqualityConvertPlanResult> planResultState;
+  private transient Long lastCommittedMainSnapshotId;
+
+  private transient Counter errorCounter;
+  private transient Counter addedDataFileNumCounter;
+  private transient Counter addedDataFileSizeCounter;
+  private transient Counter addedDvNumCounter;
+  private transient Counter commitDurationMsCounter;
+
+  public EqualityConvertCommitter(
+      String tableName,
+      String taskName,
+      int taskIndex,
+      TableLoader tableLoader,
+      String targetBranch) {
+    this.tableName = tableName;
+    this.taskName = taskName;
+    this.taskIndex = taskIndex;
+    this.tableLoader = tableLoader;
+    this.targetBranch = targetBranch;
+  }
+
+  @Override
+  public void open() throws Exception {
+    super.open();
+    if (!tableLoader.isOpen()) {
+      tableLoader.open();
+    }
+
+    this.table = tableLoader.loadTable();
+
+    MetricGroup taskMetricGroup =
+        TableMaintenanceMetrics.groupFor(getRuntimeContext(), tableName, 
taskName, taskIndex);
+    this.errorCounter = 
taskMetricGroup.counter(TableMaintenanceMetrics.ERROR_COUNTER);
+    this.addedDataFileNumCounter =
+        
taskMetricGroup.counter(TableMaintenanceMetrics.ADDED_DATA_FILE_NUM_METRIC);
+    this.addedDataFileSizeCounter =
+        
taskMetricGroup.counter(TableMaintenanceMetrics.ADDED_DATA_FILE_SIZE_METRIC);
+    this.addedDvNumCounter = taskMetricGroup.counter(ADDED_DV_NUM_METRIC);
+    this.commitDurationMsCounter = 
taskMetricGroup.counter(COMMIT_DURATION_MS_METRIC);
+
+    // Bound isAlreadyCommitted history walk on fresh start (no restored 
state).
+    if (lastCommittedMainSnapshotId == null) {
+      Snapshot mainSnapshot = table.snapshot(targetBranch);
+      if (mainSnapshot != null) {
+        lastCommittedMainSnapshotId = mainSnapshot.snapshotId();
+      }
+    }
+  }
+
+  @Override
+  public void initializeState(StateInitializationContext context) throws 
Exception {
+    super.initializeState(context);
+    lastCommittedMainSnapshotListState =
+        context
+            .getOperatorStateStore()
+            .getListState(new 
ListStateDescriptor<>("lastCommittedMainSnapshotId", Types.LONG));
+    bufferedResultsState =
+        context
+            .getOperatorStateStore()
+            .getListState(
+                new ListStateDescriptor<>(
+                    "bufferedResults", 
TypeInformation.of(DVMergeResult.class)));
+    planResultState =
+        context
+            .getOperatorStateStore()
+            .getListState(
+                new ListStateDescriptor<>(
+                    "planResult", 
TypeInformation.of(EqualityConvertPlanResult.class)));
+
+    for (Long id : lastCommittedMainSnapshotListState.get()) {
+      lastCommittedMainSnapshotId = id;
+    }
+
+    bufferedResults = Lists.newArrayList(bufferedResultsState.get());
+    for (EqualityConvertPlanResult result : planResultState.get()) {
+      planResult = result;
+    }
+  }
+
+  @Override
+  public void snapshotState(StateSnapshotContext context) throws Exception {
+    super.snapshotState(context);
+    lastCommittedMainSnapshotListState.clear();
+    if (lastCommittedMainSnapshotId != null) {
+      lastCommittedMainSnapshotListState.add(lastCommittedMainSnapshotId);
+    }
+
+    bufferedResultsState.update(bufferedResults);
+    planResultState.clear();
+    if (planResult != null) {
+      planResultState.add(planResult);
+    }
+  }
+
+  @Override
+  public void processElement1(StreamRecord<DVMergeResult> record) {
+    bufferedResults.add(record.getValue());
+  }
+
+  @Override
+  public void processElement2(StreamRecord<EqualityConvertPlanResult> record) 
throws Exception {
+    planResult = record.getValue();
+    tryCommitAndForward();
+  }
+
+  @Override
+  public void processWatermark(Watermark mark) throws Exception {
+    pendingMark = mark;
+    tryCommitAndForward();
+
+    // Forward watermarks when no active cycle to prevent stalling downstream.
+    if (planResult == null && pendingMark != null) {
+      Watermark toForward = pendingMark;
+      pendingMark = null;
+      super.processWatermark(toForward);
+    }
+  }
+
+  @Override
+  public void close() throws Exception {
+    super.close();
+    tableLoader.close();
+  }
+
+  private void tryCommitAndForward() throws Exception {
+    if (planResult == null || pendingMark == null) {
+      return;
+    }
+
+    if (pendingMark.getTimestamp() < planResult.doneTimestamp()) {
+      return;
+    }
+
+    try {
+      commitIfNeeded();
+    } catch (Exception e) {
+      LOG.error(
+          "Failed to commit equality convert result for table {} task {}[{}]",
+          tableName,
+          taskName,
+          taskIndex,
+          e);
+      output.collect(TaskResultAggregator.ERROR_STREAM, new StreamRecord<>(e));
+      errorCounter.inc();
+    }
+
+    // Emit Trigger for the Aggregator (even on error or no-op).
+    output.collect(new 
StreamRecord<>(Trigger.create(planResult.triggerTimestamp(), taskIndex)));
+
+    Watermark mark = pendingMark;
+    bufferedResults.clear();
+    planResult = null;
+    pendingMark = null;
+
+    super.processWatermark(mark);
+  }
+
+  private void commitIfNeeded() {
+    for (DVMergeResult result : bufferedResults) {

Review Comment:
   I'm going to change the logic here to be stateless. The planner will decide 
which snaphots were already converted and committed. All other snapshots, 
including partially processed, will be processed again.



##########
flink/v2.1/flink/src/main/java/org/apache/iceberg/flink/maintenance/operator/EqualityConvertDVMerger.java:
##########
@@ -0,0 +1,191 @@
+/*
+ * 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.
+ */
+package org.apache.iceberg.flink.maintenance.operator;
+
+import java.util.List;
+import java.util.Map;
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.api.common.state.ListState;
+import org.apache.flink.api.common.state.ListStateDescriptor;
+import org.apache.flink.api.common.typeinfo.TypeInformation;
+import org.apache.flink.runtime.state.StateInitializationContext;
+import org.apache.flink.runtime.state.StateSnapshotContext;
+import org.apache.flink.streaming.api.operators.AbstractStreamOperator;
+import org.apache.flink.streaming.api.operators.OneInputStreamOperator;
+import org.apache.flink.streaming.api.watermark.Watermark;
+import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
+import org.apache.iceberg.DeleteFile;
+import org.apache.iceberg.FileFormat;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.data.BaseDeleteLoader;
+import org.apache.iceberg.data.DeleteLoader;
+import org.apache.iceberg.deletes.BaseDVFileWriter;
+import org.apache.iceberg.deletes.PositionDeleteIndex;
+import org.apache.iceberg.flink.TableLoader;
+import org.apache.iceberg.io.DeleteWriteResult;
+import org.apache.iceberg.io.OutputFileFactory;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.relocated.com.google.common.collect.Maps;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Parallel DV writer that receives {@link DVMergeCommand}s from the {@link
+ * EqualityConvertDVResolver} and writes merged deletion vector files. Each 
instance processes a
+ * subset of data files (distributed via rebalance) and writes its own Puffin 
file.
+ */
+@Internal
+public class EqualityConvertDVMerger extends 
AbstractStreamOperator<DVMergeResult>
+    implements OneInputStreamOperator<DVMergeCommand, DVMergeResult> {
+
+  private static final Logger LOG = 
LoggerFactory.getLogger(EqualityConvertDVMerger.class);
+
+  private final String tableName;
+  private final String taskName;
+  private final int taskIndex;
+  private final TableLoader tableLoader;
+
+  private transient Table table;
+  private transient OutputFileFactory fileFactory;
+  private transient List<DVMergeCommand> bufferedCommands;
+  private transient DeleteLoader deleteLoader;
+  private transient ListState<DVMergeCommand> bufferedCommandsState;
+
+  public EqualityConvertDVMerger(
+      String tableName, String taskName, int taskIndex, TableLoader 
tableLoader) {
+    this.tableName = tableName;
+    this.taskName = taskName;
+    this.taskIndex = taskIndex;
+    this.tableLoader = tableLoader;
+  }
+
+  @Override
+  public void open() throws Exception {
+    super.open();
+    if (!tableLoader.isOpen()) {
+      tableLoader.open();
+    }
+
+    table = tableLoader.loadTable();
+    fileFactory =
+        OutputFileFactory.builderFor(table, taskIndex, 
0L).format(FileFormat.PUFFIN).build();
+    deleteLoader = new BaseDeleteLoader(deleteFile -> 
table.io().newInputFile(deleteFile));
+  }
+
+  @Override
+  public void initializeState(StateInitializationContext context) throws 
Exception {
+    super.initializeState(context);
+    bufferedCommandsState =
+        context
+            .getOperatorStateStore()
+            .getListState(
+                new ListStateDescriptor<>(
+                    "bufferedCommands", 
TypeInformation.of(DVMergeCommand.class)));
+    bufferedCommands = Lists.newArrayList(bufferedCommandsState.get());
+  }
+
+  @Override
+  public void snapshotState(StateSnapshotContext context) throws Exception {
+    super.snapshotState(context);
+    bufferedCommandsState.update(bufferedCommands);
+  }
+
+  @Override
+  public void processElement(StreamRecord<DVMergeCommand> record) {
+    bufferedCommands.add(record.getValue());
+  }
+
+  @Override
+  public void processWatermark(Watermark mark) throws Exception {
+    if (!bufferedCommands.isEmpty()) {
+      if (bufferedCommands.stream().anyMatch(DVMergeCommand::isAbort)) {
+        output.collect(new StreamRecord<>(DVMergeResult.abort()));
+      } else {
+        try {
+          Map<String, DeleteFile> existingDVs = Maps.newHashMap();
+          for (DVMergeCommand cmd : bufferedCommands) {
+            if (cmd.existingDV() != null) {
+              existingDVs.put(cmd.dataFilePath(), cmd.existingDV());
+            }
+          }
+
+          DeleteWriteResult result;
+          try (BaseDVFileWriter dvWriter =
+              new BaseDVFileWriter(fileFactory, path -> loadPreviousDV(path, 
existingDVs))) {
+
+            for (DVMergeCommand cmd : bufferedCommands) {
+              for (long pos : cmd.positions()) {
+                dvWriter.delete(
+                    cmd.dataFilePath(), pos, table.specs().get(cmd.specId()), 
cmd.partition());
+              }
+            }
+
+            dvWriter.close();

Review Comment:
   This is due to `dvWriter` creating the Puffin file on close(). Will move the 
object creation to before the `try` block to avoid this.



##########
flink/v2.1/flink/src/main/java/org/apache/iceberg/flink/maintenance/operator/EqualityConvertDVResolver.java:
##########
@@ -0,0 +1,302 @@
+/*
+ * 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.
+ */
+package org.apache.iceberg.flink.maintenance.operator;
+
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.util.List;
+import java.util.Map;
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.api.common.state.ListState;
+import org.apache.flink.api.common.state.ListStateDescriptor;
+import org.apache.flink.api.common.typeinfo.TypeInformation;
+import org.apache.flink.api.common.typeinfo.Types;
+import org.apache.flink.runtime.state.StateInitializationContext;
+import org.apache.flink.runtime.state.StateSnapshotContext;
+import org.apache.flink.streaming.api.operators.AbstractStreamOperator;
+import org.apache.flink.streaming.api.operators.TwoInputStreamOperator;
+import org.apache.flink.streaming.api.watermark.Watermark;
+import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
+import org.apache.iceberg.DataFile;
+import org.apache.iceberg.DeleteFile;
+import org.apache.iceberg.ManifestFile;
+import org.apache.iceberg.ManifestFiles;
+import org.apache.iceberg.ManifestReader;
+import org.apache.iceberg.PartitionSpec;
+import org.apache.iceberg.Snapshot;
+import org.apache.iceberg.StructLike;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.flink.TableLoader;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.relocated.com.google.common.collect.Maps;
+import org.apache.iceberg.util.ContentFileUtil;
+import org.apache.iceberg.util.StructLikeUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Collects {@link DVPosition}s from {@link EqualityConvertWorker} instances 
(input 1) and an {@link
+ * EqualityConvertPlanResult} from the planner (input 2). On watermark 
advancement, groups DVs, and
+ * emits {@link DVMergeCommand}s for parallel {@link EqualityConvertDVMerger} 
instances.
+ */
+@Internal
+public class EqualityConvertDVResolver extends 
AbstractStreamOperator<DVMergeCommand>
+    implements TwoInputStreamOperator<DVPosition, EqualityConvertPlanResult, 
DVMergeCommand> {
+
+  private static final Logger LOG = 
LoggerFactory.getLogger(EqualityConvertDVResolver.class);
+
+  private final String tableName;
+  private final String taskName;
+  private final int taskIndex;
+  private final TableLoader tableLoader;
+  private final String targetBranch;
+
+  private transient Table table;
+  private transient List<DVPosition> bufferedPositions;

Review Comment:
   Storing the filenames multiple times is quite costly.



##########
flink/v2.1/flink/src/main/java/org/apache/iceberg/flink/maintenance/operator/EqualityConvertReader.java:
##########
@@ -0,0 +1,129 @@
+/*
+ * 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.
+ */
+package org.apache.iceberg.flink.maintenance.operator;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.api.common.functions.OpenContext;
+import org.apache.flink.streaming.api.functions.ProcessFunction;
+import org.apache.flink.util.Collector;
+import org.apache.flink.util.OutputTag;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.data.Record;
+import org.apache.iceberg.flink.TableLoader;
+import org.apache.iceberg.formats.FormatModelRegistry;
+import org.apache.iceberg.formats.ReadBuilder;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.DeleteSchemaUtil;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.types.TypeUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Parallel reader that processes {@link ReadCommand}s from the planner and 
emits {@link
+ * IndexCommand}s. Each instance reads a subset of files and emits row-level 
index commands for the
+ * workers.
+ */
+@Internal
+public class EqualityConvertReader extends ProcessFunction<ReadCommand, 
IndexCommand> {
+
+  private static final Logger LOG = 
LoggerFactory.getLogger(EqualityConvertReader.class);
+
+  public static final OutputTag<DVPosition> DV_POSITION_STREAM =
+      new OutputTag<>("dv-position-stream") {};
+
+  private final TableLoader tableLoader;
+
+  private transient Table table;
+  private transient EqualityFieldSerializer fieldSerializer;
+
+  public EqualityConvertReader(TableLoader tableLoader) {
+    this.tableLoader = tableLoader;
+  }
+
+  @Override
+  public void open(OpenContext openContext) throws Exception {
+    super.open(openContext);
+    if (!tableLoader.isOpen()) {
+      tableLoader.open();
+    }
+
+    table = tableLoader.loadTable();
+    fieldSerializer = new EqualityFieldSerializer();
+  }
+
+  @Override
+  public void processElement(ReadCommand cmd, Context ctx, 
Collector<IndexCommand> out)
+      throws Exception {
+    try {
+      if (cmd.type() == ReadCommand.Type.POS_DELETE_FILE) {
+        readPosDeleteFile(cmd, ctx);
+        return;
+      }

Review Comment:
   They are emitted as part of the PlanResult by the Planner and sent directly 
to the DvResolver.



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