mxm commented on code in PR #15996: URL: https://github.com/apache/iceberg/pull/15996#discussion_r3099918952
########## flink/v2.1/flink/src/main/java/org/apache/iceberg/flink/maintenance/operator/EqualityConvertPlanner.java: ########## @@ -0,0 +1,601 @@ +/* + * 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.Collections; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +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.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.OneInputStreamOperator; +import org.apache.flink.streaming.api.watermark.Watermark; +import org.apache.flink.streaming.runtime.streamrecord.StreamRecord; +import org.apache.flink.util.OutputTag; +import org.apache.iceberg.DataFile; +import org.apache.iceberg.DataOperations; +import org.apache.iceberg.DeleteFile; +import org.apache.iceberg.FileContent; +import org.apache.iceberg.ManifestFile; +import org.apache.iceberg.ManifestFiles; +import org.apache.iceberg.ManifestReader; +import org.apache.iceberg.Snapshot; +import org.apache.iceberg.SnapshotChanges; +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.Maps; +import org.apache.iceberg.relocated.com.google.common.collect.Sets; +import org.apache.iceberg.util.SnapshotUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Scans the staging branch for new data files and equality delete files, and emits {@link + * ReadCommand}s for parallel readers to process. Assigns phase-based event timestamps and emits + * watermarks between phases to guarantee ordering: data rows from prior phases are fully processed + * before equality deletes are resolved. + * + * <p>An {@link EqualityConvertPlanResult} with the new data files is emitted via the {@link + * #METADATA_STREAM} side output. + * + * <p>Processes each staging snapshot individually in order (oldest first), so that equality deletes + * are scoped to data files visible at that snapshot. Supports multiple equality field sets. + */ +@Internal +public class EqualityConvertPlanner extends AbstractStreamOperator<ReadCommand> + implements OneInputStreamOperator<Trigger, ReadCommand> { + + private static final Logger LOG = LoggerFactory.getLogger(EqualityConvertPlanner.class); + + public static final OutputTag<EqualityConvertPlanResult> METADATA_STREAM = + new OutputTag<>("metadata-stream") {}; + + private static final String PROCESSED_EQ_DELETE_FILE_NUM_METRIC = "processedEqDeleteFileNum"; + private static final String PROCESSED_STAGING_SNAPSHOT_NUM_METRIC = "processedStagingSnapshotNum"; + private static final String SKIPPED_NO_OP_CYCLES_METRIC = "skippedNoOpCycles"; + private static final String REINDEX_COUNT_METRIC = "reindexCount"; + + private final String tableName; + private final String taskName; + private final int taskIndex; + private final TableLoader tableLoader; + private final String stagingBranch; + private final String targetBranch; + private final int maxSnapshotsPerTrigger; + + private transient Table table; + + private transient ListState<Long> lastStagingSnapshotState; + private transient ListState<Long> lastMainSnapshotState; + private transient ListState<List<Integer>> mainIndexEmittedState; + private transient ListState<Long> lastDoneTsState; + private transient ListState<Long> indexSnapshotState; + + // Mutable phase counter, reset at the start of each emitReadCommandsForSnapshots call. + private transient int nextPhaseOffset; + + private transient Long lastStagingSnapshotId; + private transient Long lastMainSnapshotId; + private transient Set<List<Integer>> mainIndexEmittedSet; + private transient long lastDoneTs; + private transient Long indexSnapshotId; + + // Set at end of processElement, promoted to lastStagingSnapshotId only when the next trigger + // arrives (confirming the previous cycle completed and was checkpointed). Not persisted in + // state, so a crash replays the last cycle. + private transient Long pendingStagingSnapshotId; + + private transient Counter processedEqDeleteFileNumCounter; + private transient Counter processedStagingSnapshotNumCounter; + private transient Counter skippedNoOpCyclesCounter; + private transient Counter reindexCounter; + + public EqualityConvertPlanner( + String tableName, + String taskName, + int taskIndex, + TableLoader tableLoader, + String stagingBranch, + String targetBranch, + int maxSnapshotsPerTrigger) { + this.tableName = tableName; + this.taskName = taskName; + this.taskIndex = taskIndex; + this.tableLoader = tableLoader; + this.stagingBranch = stagingBranch; + this.targetBranch = targetBranch; + this.maxSnapshotsPerTrigger = maxSnapshotsPerTrigger; + } + + @Override + public void open() throws Exception { + super.open(); + if (!tableLoader.isOpen()) { + tableLoader.open(); + } + + table = tableLoader.loadTable(); + + MetricGroup taskMetricGroup = + TableMaintenanceMetrics.groupFor(getRuntimeContext(), tableName, taskName, taskIndex); + this.processedEqDeleteFileNumCounter = + taskMetricGroup.counter(PROCESSED_EQ_DELETE_FILE_NUM_METRIC); + this.processedStagingSnapshotNumCounter = + taskMetricGroup.counter(PROCESSED_STAGING_SNAPSHOT_NUM_METRIC); + this.skippedNoOpCyclesCounter = taskMetricGroup.counter(SKIPPED_NO_OP_CYCLES_METRIC); + this.reindexCounter = taskMetricGroup.counter(REINDEX_COUNT_METRIC); + } + + @Override + public void initializeState(StateInitializationContext context) throws Exception { + super.initializeState(context); + lastStagingSnapshotState = + context + .getOperatorStateStore() + .getListState(new ListStateDescriptor<>("lastStagingSnapshotId", Types.LONG)); + lastMainSnapshotState = + context + .getOperatorStateStore() + .getListState(new ListStateDescriptor<>("lastMainSnapshotId", Types.LONG)); + mainIndexEmittedState = + context + .getOperatorStateStore() + .getListState(new ListStateDescriptor<>("mainIndexEmitted", Types.LIST(Types.INT))); + lastDoneTsState = + context + .getOperatorStateStore() + .getListState(new ListStateDescriptor<>("lastDoneTs", Types.LONG)); + indexSnapshotState = + context + .getOperatorStateStore() + .getListState(new ListStateDescriptor<>("indexSnapshotId", Types.LONG)); + + for (Long id : lastStagingSnapshotState.get()) { + lastStagingSnapshotId = id; + } + + for (Long id : lastMainSnapshotState.get()) { + lastMainSnapshotId = id; + } + + mainIndexEmittedSet = Sets.newHashSet(); + for (List<Integer> fieldSet : mainIndexEmittedState.get()) { + mainIndexEmittedSet.add(fieldSet); + } + + for (Long ts : lastDoneTsState.get()) { + lastDoneTs = ts; + } + + for (Long id : indexSnapshotState.get()) { + indexSnapshotId = id; + } + } + + @Override + public void snapshotState(StateSnapshotContext context) throws Exception { + super.snapshotState(context); + + lastStagingSnapshotState.clear(); + if (lastStagingSnapshotId != null) { + lastStagingSnapshotState.add(lastStagingSnapshotId); + } + + lastMainSnapshotState.clear(); + if (lastMainSnapshotId != null) { + lastMainSnapshotState.add(lastMainSnapshotId); + } + + mainIndexEmittedState.clear(); + for (List<Integer> fieldSet : mainIndexEmittedSet) { + mainIndexEmittedState.add(Lists.newArrayList(fieldSet)); + } + + lastDoneTsState.clear(); + lastDoneTsState.add(lastDoneTs); + + indexSnapshotState.clear(); + if (indexSnapshotId != null) { + indexSnapshotState.add(indexSnapshotId); + } + } + + @Override + public void processElement(StreamRecord<Trigger> element) throws Exception { + // Confirm the pending snapshot ID from the previous cycle. If we reach this point, + // the previous cycle completed successfully and was checkpointed. + if (pendingStagingSnapshotId != null) { + lastStagingSnapshotId = pendingStagingSnapshotId; + pendingStagingSnapshotId = null; + } + + long triggerTs = element.getTimestamp(); + long baseTs = Math.max(triggerTs, lastDoneTs + 1); + + try { + table.refresh(); + + Snapshot stagingSnapshot = table.snapshot(stagingBranch); + if (stagingSnapshot == null) { + LOG.info("No snapshot on staging branch '{}', nothing to convert.", stagingBranch); + emitNoOpResult(triggerTs, baseTs); + return; + } + + if (lastStagingSnapshotId != null && stagingSnapshot.snapshotId() == lastStagingSnapshotId) { + LOG.info( + "Staging branch '{}' snapshot {} already processed, skipping.", + stagingBranch, + stagingSnapshot.snapshotId()); + emitNoOpResult(triggerTs, baseTs); + return; + } + + Snapshot mainSnapshot = table.snapshot(targetBranch); + Long currentMainSnapshotId = mainSnapshot != null ? mainSnapshot.snapshotId() : null; + handleMainBranchChange(currentMainSnapshotId); + lastMainSnapshotId = currentMainSnapshotId; + + if (indexSnapshotId == null) { + indexSnapshotId = currentMainSnapshotId; + } + + List<Snapshot> stagingSnapshots = + collectStagingSnapshots(stagingSnapshot, lastStagingSnapshotId, mainSnapshot); + + if (stagingSnapshots.isEmpty()) { + LOG.info("No new staging snapshots to process on branch '{}'.", stagingBranch); + pendingStagingSnapshotId = stagingSnapshot.snapshotId(); + emitNoOpResult(triggerTs, baseTs); + return; + } + + if (stagingSnapshots.size() > maxSnapshotsPerTrigger) { + stagingSnapshots = stagingSnapshots.subList(0, maxSnapshotsPerTrigger); + } + + emitReadCommandsForSnapshots(stagingSnapshots, baseTs, triggerTs); + } catch (Exception e) { + LOG.error( + "Error processing equality deletes for table {} task {}[{}]", + tableName, + taskName, + taskIndex, + e); + output.collect(TaskResultAggregator.ERROR_STREAM, new StreamRecord<>(e)); + emitNoOpResult(triggerTs, baseTs); + } + } + + private void handleMainBranchChange(Long currentMainSnapshotId) { + boolean mainChanged = + lastMainSnapshotId != null && !Objects.equals(lastMainSnapshotId, currentMainSnapshotId); + if (!mainChanged) { + return; + } + + if (currentMainSnapshotId == null) { + mainIndexEmittedSet.clear(); + indexSnapshotId = null; + LOG.info("Main branch '{}' was deleted, clearing index.", targetBranch); + return; + } + + boolean needsReindex = false; + for (Snapshot s : + SnapshotUtil.ancestorsBetween(table, currentMainSnapshotId, lastMainSnapshotId)) { + if (DataOperations.REPLACE.equals(s.operation())) { + needsReindex = true; + break; + } Review Comment: The mode of operation which I had in mind is that we run compaction via the Flink maintenance framework which prevents concurrent execution of maintenance tasks. If there is no locking, then there will a conflict during committing and the task will fail. When it runs again, it will pick up the changes from the main branch. ########## flink/v2.1/flink/src/main/java/org/apache/iceberg/flink/maintenance/operator/EqualityFieldSerializer.java: ########## @@ -0,0 +1,83 @@ +/* + * 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.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.ByteBuffer; +import java.util.List; +import org.apache.iceberg.StructLike; +import org.apache.iceberg.types.Conversions; +import org.apache.iceberg.types.Type; +import org.apache.iceberg.types.Types; + +/** + * Serializes equality field values into an {@link SerializedEqualityValues} for use as a Flink + * keyed state key. Using the full serialized key (rather than a hash) eliminates + * hash-collision-induced data loss. + * + * <p>Supports multiple equality field sets by prefixing the serialized key with the sorted field + * IDs. + */ +class EqualityFieldSerializer { + + private final ByteArrayOutputStream baos = new ByteArrayOutputStream(); + private final DataOutputStream dos = new DataOutputStream(baos); + + /** + * Serializes a primary key to an {@link SerializedEqualityValues}. The field ID prefix keeps keys + * from different equality field sets separate. Reuses internal buffers, so this instance must not + * be shared across threads. + */ + public SerializedEqualityValues serializeKey(StructLike key, Types.StructType keyType) { + baos.reset(); + try { + List<Types.NestedField> fields = keyType.fields(); + dos.writeInt(fields.size()); + for (int i = 0; i < fields.size(); i++) { + dos.writeInt(fields.get(i).fieldId()); + } + + for (int i = 0; i < fields.size(); i++) { + serializeField(key, i, fields.get(i).type()); + } + + dos.flush(); + } catch (IOException e) { + throw new UncheckedIOException("Failed to serialize PK index key", e); + } + + return new SerializedEqualityValues(baos.toByteArray()); + } + + private void serializeField(StructLike key, int pos, Type fieldType) throws IOException { + Object value = key.get(pos, Object.class); + if (value == null) { + dos.writeBoolean(true); + return; + } + + dos.writeBoolean(false); + ByteBuffer buf = Conversions.toByteBuffer(fieldType, value); + dos.writeInt(buf.limit()); + dos.write(buf.array(), buf.arrayOffset() + buf.position(), buf.limit()); Review Comment: You're right, we should use `remaining()` just to prevent `position() != 0`. ########## flink/v2.1/flink/src/main/java/org/apache/iceberg/flink/maintenance/api/ConvertEqualityDeletes.java: ########## @@ -0,0 +1,251 @@ +/* + * 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.api; + +import java.io.IOException; +import java.io.UncheckedIOException; +import org.apache.flink.api.common.typeinfo.TypeInformation; +import org.apache.flink.streaming.api.datastream.DataStream; +import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator; +import org.apache.iceberg.HasTableOperations; +import org.apache.iceberg.SnapshotRef; +import org.apache.iceberg.Table; +import org.apache.iceberg.flink.TableLoader; +import org.apache.iceberg.flink.maintenance.operator.DVMergeCommand; +import org.apache.iceberg.flink.maintenance.operator.DVMergeResult; +import org.apache.iceberg.flink.maintenance.operator.DVPosition; +import org.apache.iceberg.flink.maintenance.operator.EqualityConvertCommitter; +import org.apache.iceberg.flink.maintenance.operator.EqualityConvertDVMerger; +import org.apache.iceberg.flink.maintenance.operator.EqualityConvertDVResolver; +import org.apache.iceberg.flink.maintenance.operator.EqualityConvertPlanResult; +import org.apache.iceberg.flink.maintenance.operator.EqualityConvertPlanner; +import org.apache.iceberg.flink.maintenance.operator.EqualityConvertReader; +import org.apache.iceberg.flink.maintenance.operator.EqualityConvertWorker; +import org.apache.iceberg.flink.maintenance.operator.IndexCommand; +import org.apache.iceberg.flink.maintenance.operator.ReadCommand; +import org.apache.iceberg.flink.maintenance.operator.SerializedEqualityValues; +import org.apache.iceberg.flink.maintenance.operator.TaskResultAggregator; +import org.apache.iceberg.relocated.com.google.common.base.Preconditions; + +/** + * Creates the equality delete to DV conversion data stream. Runs a single iteration of the + * conversion for every {@link Trigger} event. + * + * <p>The pipeline reads equality delete files from a staging branch, converts them to deletion + * vectors (DVs) using a primary key index stored in Flink state, and commits the data files and DVs + * to the main branch. + * + * <p>The conversion is split into parallel stages: + * + * <ol> + * <li>Planner (p=1): scans staging branch, emits file-level ReadCommands with phase timestamps + * <li>Reader (p=N): reads files, emits row-level IndexCommands + * <li>Worker (p=N): maintains PK index shards, resolves equality deletes to DV positions + * <li>DVResolver (p=1): groups positions by data file, resolves partition info and existing DVs + * <li>DVMerger (p=N): writes merged deletion vector files + * <li>Committer (p=1): commits data files and DVs to main branch + * </ol> + * + * <p>Mutual exclusion with concurrent maintenance tasks (e.g. compaction) is enforced by the Flink + * maintenance framework lock. The lock is acquired before the maintenance task runs and released + * after each cycle completes, ensuring no conflicting commits occur on the target branch. + */ +public class ConvertEqualityDeletes { + static final String PLANNER_TASK_NAME = "EqConvert Planner"; + static final String READER_TASK_NAME = "EqConvert Reader"; + static final String WORKER_TASK_NAME = "EqConvert Worker"; + static final String DV_RESOLVER_TASK_NAME = "EqConvert DVResolver"; + static final String DV_MERGER_TASK_NAME = "EqConvert DVMerger"; + static final String COMMIT_TASK_NAME = "EqConvert Commit"; + static final String AGGREGATOR_TASK_NAME = "EqConvert Aggregator"; + + private ConvertEqualityDeletes() {} + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends MaintenanceTaskBuilder<Builder> { + private String stagingBranch; + private String targetBranch = SnapshotRef.MAIN_BRANCH; + private int maxSnapshotsPerTrigger = Integer.MAX_VALUE; + + @Override + String maintenanceTaskName() { + return "ConvertEqualityDeletes"; + } + + /** Sets the staging branch name that holds the equality delete files and data files. */ + public Builder stagingBranch(String newStagingBranch) { + this.stagingBranch = newStagingBranch; + return this; + } + + /** + * Sets the target branch where converted data files and DVs are committed. Defaults to the main + * branch. + */ + public Builder targetBranch(String newTargetBranch) { + this.targetBranch = newTargetBranch; + return this; + } + + /** + * Sets the maximum number of staging snapshots to process per trigger. Defaults to {@link + * Integer#MAX_VALUE} (process all pending snapshots). + */ + public Builder maxSnapshotsPerTrigger(int newMaxSnapshotsPerTrigger) { + this.maxSnapshotsPerTrigger = newMaxSnapshotsPerTrigger; + return this; + } + + @Override + DataStream<TaskResult> append(DataStream<Trigger> trigger) { + Preconditions.checkNotNull(stagingBranch, "stagingBranch must be set"); + Preconditions.checkArgument( + !stagingBranch.equals(targetBranch), + "stagingBranch and targetBranch must be different, but both are '%s'", + stagingBranch); + validateFormatVersion(); + + // Planner (p=1): emits ReadCommands with phase timestamps and watermarks + SingleOutputStreamOperator<ReadCommand> planned = + trigger + .transform( + operatorName(PLANNER_TASK_NAME), + TypeInformation.of(ReadCommand.class), + new EqualityConvertPlanner( + tableName(), + taskName(), + index(), + tableLoader(), + stagingBranch, + targetBranch, + maxSnapshotsPerTrigger)) + .uid(PLANNER_TASK_NAME + uidSuffix()) + .slotSharingGroup(slotSharingGroup()) + .forceNonParallel(); + + // Reader (p=N): reads files, emits IndexCommands + SingleOutputStreamOperator<IndexCommand> indexed = + planned + .rebalance() + .process(new EqualityConvertReader(tableLoader())) + .name(operatorName(READER_TASK_NAME)) + .uid(READER_TASK_NAME + uidSuffix()) + .slotSharingGroup(slotSharingGroup()) + .setParallelism(parallelism()); + + // Worker (p=N): keyed by full PK, phase-aware buffering + SingleOutputStreamOperator<DVPosition> dvPositions = + indexed + .keyBy(IndexCommand::key, TypeInformation.of(SerializedEqualityValues.class)) + .process(new EqualityConvertWorker()) + .name(operatorName(WORKER_TASK_NAME)) + .uid(WORKER_TASK_NAME + uidSuffix()) + .slotSharingGroup(slotSharingGroup()) + .setParallelism(parallelism()); + + // Metadata side output from planner + DataStream<EqualityConvertPlanResult> metadata = + planned.getSideOutput(EqualityConvertPlanner.METADATA_STREAM); + + // DVResolver (p=1): groups positions, collects partition/DV info + SingleOutputStreamOperator<DVMergeCommand> resolved = + dvPositions + .connect(metadata) + .transform( + operatorName(DV_RESOLVER_TASK_NAME), + TypeInformation.of(DVMergeCommand.class), + new EqualityConvertDVResolver( + tableName(), taskName(), index(), tableLoader(), targetBranch)) + .uid(DV_RESOLVER_TASK_NAME + uidSuffix()) + .slotSharingGroup(slotSharingGroup()) + .forceNonParallel(); + + // DVMerger (p=N): writes merged DV files + SingleOutputStreamOperator<DVMergeResult> merged = + resolved + .rebalance() + .transform( + operatorName(DV_MERGER_TASK_NAME), + TypeInformation.of(DVMergeResult.class), + new EqualityConvertDVMerger(tableName(), taskName(), index(), tableLoader())) + .uid(DV_MERGER_TASK_NAME + uidSuffix()) + .slotSharingGroup(slotSharingGroup()) + .setParallelism(parallelism()); + + // Committer (p=1): commits data files + DVs to main. + // Receives EqualityConvertPlanResult directly from the planner (not via DVResolver) so the + // plan result arrives before pipeline watermarks and can absorb them until the commit. + SingleOutputStreamOperator<Trigger> committed = + merged + .connect(metadata) + .transform( + operatorName(COMMIT_TASK_NAME), + TypeInformation.of(Trigger.class), + new EqualityConvertCommitter( + tableName(), taskName(), index(), tableLoader(), targetBranch)) + .uid(COMMIT_TASK_NAME + uidSuffix()) + .slotSharingGroup(slotSharingGroup()) + .forceNonParallel(); + + // Aggregator (p=1): collects errors and emits TaskResult. + // Uses only the committed stream (not trigger.union(committed)) because the + // Committer emits Trigger records. This prevents the trigger's watermark from + // advancing the Aggregator before the pipeline completes a cycle. + return committed + .connect( + planned + .getSideOutput(TaskResultAggregator.ERROR_STREAM) + .union(resolved.getSideOutput(TaskResultAggregator.ERROR_STREAM)) + .union(merged.getSideOutput(TaskResultAggregator.ERROR_STREAM)) + .union(committed.getSideOutput(TaskResultAggregator.ERROR_STREAM))) Review Comment: We don't currently have an error stream for `EqualityDeleteWorker` which creates `dvPositions`, but we probably want that to prevent errors to fail the entire job. ########## flink/v2.1/flink/src/main/java/org/apache/iceberg/flink/maintenance/operator/EqualityConvertDVMerger.java: ########## @@ -0,0 +1,176 @@ +/* + * 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.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.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.IOUtil; +import org.apache.iceberg.io.InputFile; +import org.apache.iceberg.io.OutputFileFactory; +import org.apache.iceberg.relocated.com.google.common.base.Preconditions; +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; + + 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(); + bufferedCommands = Lists.newArrayList(); + } + + @Override + public void processElement(StreamRecord<DVMergeCommand> record) { + bufferedCommands.add(record.getValue()); + } + + @Override + public void processWatermark(Watermark mark) throws Exception { + if (!bufferedCommands.isEmpty()) { + 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(); + result = dvWriter.result(); + } + + LOG.info( + "Wrote {} DV files (rewriting {}) for table {} task {}[{}].", + result.deleteFiles().size(), + result.rewrittenDeleteFiles().size(), + tableName, + taskName, + taskIndex); + + output.collect( + new StreamRecord<>( + new DVMergeResult( + Lists.newArrayList(result.deleteFiles()), + Lists.newArrayList(result.rewrittenDeleteFiles())))); + } catch (Exception e) { + LOG.error( + "Failed to write DV files for table {} task {}[{}]", tableName, taskName, taskIndex, e); + output.collect(TaskResultAggregator.ERROR_STREAM, new StreamRecord<>(e)); + // Signal the committer to abort this cycle rather than committing data files without DVs. + output.collect(new StreamRecord<>(DVMergeResult.abort())); + } + + bufferedCommands.clear(); + } + + super.processWatermark(mark); + } + + @Override + public void close() throws Exception { + super.close(); + tableLoader.close(); + } + + private PositionDeleteIndex loadPreviousDV( + String dataFilePath, Map<String, DeleteFile> existingDVs) { + DeleteFile existingDV = existingDVs.get(dataFilePath); + if (existingDV == null) { + return null; + } Review Comment: That's a great suggestion. We need to support positional deletes as per Peter's comments and it looks like `BaseDeleteLoader` which Spark uses also supports that. ########## flink/v2.1/flink/src/main/java/org/apache/iceberg/flink/maintenance/operator/EqualityConvertPlanner.java: ########## @@ -0,0 +1,601 @@ +/* + * 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.Collections; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +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.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.OneInputStreamOperator; +import org.apache.flink.streaming.api.watermark.Watermark; +import org.apache.flink.streaming.runtime.streamrecord.StreamRecord; +import org.apache.flink.util.OutputTag; +import org.apache.iceberg.DataFile; +import org.apache.iceberg.DataOperations; +import org.apache.iceberg.DeleteFile; +import org.apache.iceberg.FileContent; +import org.apache.iceberg.ManifestFile; +import org.apache.iceberg.ManifestFiles; +import org.apache.iceberg.ManifestReader; +import org.apache.iceberg.Snapshot; +import org.apache.iceberg.SnapshotChanges; +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.Maps; +import org.apache.iceberg.relocated.com.google.common.collect.Sets; +import org.apache.iceberg.util.SnapshotUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Scans the staging branch for new data files and equality delete files, and emits {@link + * ReadCommand}s for parallel readers to process. Assigns phase-based event timestamps and emits + * watermarks between phases to guarantee ordering: data rows from prior phases are fully processed + * before equality deletes are resolved. + * + * <p>An {@link EqualityConvertPlanResult} with the new data files is emitted via the {@link + * #METADATA_STREAM} side output. + * + * <p>Processes each staging snapshot individually in order (oldest first), so that equality deletes + * are scoped to data files visible at that snapshot. Supports multiple equality field sets. + */ +@Internal +public class EqualityConvertPlanner extends AbstractStreamOperator<ReadCommand> + implements OneInputStreamOperator<Trigger, ReadCommand> { + + private static final Logger LOG = LoggerFactory.getLogger(EqualityConvertPlanner.class); + + public static final OutputTag<EqualityConvertPlanResult> METADATA_STREAM = + new OutputTag<>("metadata-stream") {}; + + private static final String PROCESSED_EQ_DELETE_FILE_NUM_METRIC = "processedEqDeleteFileNum"; + private static final String PROCESSED_STAGING_SNAPSHOT_NUM_METRIC = "processedStagingSnapshotNum"; + private static final String SKIPPED_NO_OP_CYCLES_METRIC = "skippedNoOpCycles"; + private static final String REINDEX_COUNT_METRIC = "reindexCount"; + + private final String tableName; + private final String taskName; + private final int taskIndex; + private final TableLoader tableLoader; + private final String stagingBranch; + private final String targetBranch; + private final int maxSnapshotsPerTrigger; + + private transient Table table; + + private transient ListState<Long> lastStagingSnapshotState; + private transient ListState<Long> lastMainSnapshotState; + private transient ListState<List<Integer>> mainIndexEmittedState; + private transient ListState<Long> lastDoneTsState; + private transient ListState<Long> indexSnapshotState; + + // Mutable phase counter, reset at the start of each emitReadCommandsForSnapshots call. + private transient int nextPhaseOffset; + + private transient Long lastStagingSnapshotId; + private transient Long lastMainSnapshotId; + private transient Set<List<Integer>> mainIndexEmittedSet; + private transient long lastDoneTs; + private transient Long indexSnapshotId; + + // Set at end of processElement, promoted to lastStagingSnapshotId only when the next trigger + // arrives (confirming the previous cycle completed and was checkpointed). Not persisted in + // state, so a crash replays the last cycle. + private transient Long pendingStagingSnapshotId; + + private transient Counter processedEqDeleteFileNumCounter; + private transient Counter processedStagingSnapshotNumCounter; + private transient Counter skippedNoOpCyclesCounter; + private transient Counter reindexCounter; + + public EqualityConvertPlanner( + String tableName, + String taskName, + int taskIndex, + TableLoader tableLoader, + String stagingBranch, + String targetBranch, + int maxSnapshotsPerTrigger) { + this.tableName = tableName; + this.taskName = taskName; + this.taskIndex = taskIndex; + this.tableLoader = tableLoader; + this.stagingBranch = stagingBranch; + this.targetBranch = targetBranch; + this.maxSnapshotsPerTrigger = maxSnapshotsPerTrigger; + } + + @Override + public void open() throws Exception { + super.open(); + if (!tableLoader.isOpen()) { + tableLoader.open(); + } + + table = tableLoader.loadTable(); + + MetricGroup taskMetricGroup = + TableMaintenanceMetrics.groupFor(getRuntimeContext(), tableName, taskName, taskIndex); + this.processedEqDeleteFileNumCounter = + taskMetricGroup.counter(PROCESSED_EQ_DELETE_FILE_NUM_METRIC); + this.processedStagingSnapshotNumCounter = + taskMetricGroup.counter(PROCESSED_STAGING_SNAPSHOT_NUM_METRIC); + this.skippedNoOpCyclesCounter = taskMetricGroup.counter(SKIPPED_NO_OP_CYCLES_METRIC); + this.reindexCounter = taskMetricGroup.counter(REINDEX_COUNT_METRIC); + } + + @Override + public void initializeState(StateInitializationContext context) throws Exception { + super.initializeState(context); + lastStagingSnapshotState = + context + .getOperatorStateStore() + .getListState(new ListStateDescriptor<>("lastStagingSnapshotId", Types.LONG)); + lastMainSnapshotState = + context + .getOperatorStateStore() + .getListState(new ListStateDescriptor<>("lastMainSnapshotId", Types.LONG)); + mainIndexEmittedState = + context + .getOperatorStateStore() + .getListState(new ListStateDescriptor<>("mainIndexEmitted", Types.LIST(Types.INT))); + lastDoneTsState = + context + .getOperatorStateStore() + .getListState(new ListStateDescriptor<>("lastDoneTs", Types.LONG)); + indexSnapshotState = + context + .getOperatorStateStore() + .getListState(new ListStateDescriptor<>("indexSnapshotId", Types.LONG)); + + for (Long id : lastStagingSnapshotState.get()) { + lastStagingSnapshotId = id; + } + + for (Long id : lastMainSnapshotState.get()) { + lastMainSnapshotId = id; + } + + mainIndexEmittedSet = Sets.newHashSet(); + for (List<Integer> fieldSet : mainIndexEmittedState.get()) { + mainIndexEmittedSet.add(fieldSet); + } + + for (Long ts : lastDoneTsState.get()) { + lastDoneTs = ts; + } + + for (Long id : indexSnapshotState.get()) { + indexSnapshotId = id; + } + } + + @Override + public void snapshotState(StateSnapshotContext context) throws Exception { + super.snapshotState(context); + + lastStagingSnapshotState.clear(); + if (lastStagingSnapshotId != null) { + lastStagingSnapshotState.add(lastStagingSnapshotId); + } + + lastMainSnapshotState.clear(); + if (lastMainSnapshotId != null) { + lastMainSnapshotState.add(lastMainSnapshotId); + } + + mainIndexEmittedState.clear(); + for (List<Integer> fieldSet : mainIndexEmittedSet) { + mainIndexEmittedState.add(Lists.newArrayList(fieldSet)); + } + + lastDoneTsState.clear(); + lastDoneTsState.add(lastDoneTs); + + indexSnapshotState.clear(); + if (indexSnapshotId != null) { + indexSnapshotState.add(indexSnapshotId); + } + } + + @Override + public void processElement(StreamRecord<Trigger> element) throws Exception { + // Confirm the pending snapshot ID from the previous cycle. If we reach this point, + // the previous cycle completed successfully and was checkpointed. + if (pendingStagingSnapshotId != null) { + lastStagingSnapshotId = pendingStagingSnapshotId; + pendingStagingSnapshotId = null; + } + + long triggerTs = element.getTimestamp(); + long baseTs = Math.max(triggerTs, lastDoneTs + 1); + + try { + table.refresh(); + + Snapshot stagingSnapshot = table.snapshot(stagingBranch); + if (stagingSnapshot == null) { + LOG.info("No snapshot on staging branch '{}', nothing to convert.", stagingBranch); + emitNoOpResult(triggerTs, baseTs); + return; + } + + if (lastStagingSnapshotId != null && stagingSnapshot.snapshotId() == lastStagingSnapshotId) { + LOG.info( + "Staging branch '{}' snapshot {} already processed, skipping.", + stagingBranch, + stagingSnapshot.snapshotId()); + emitNoOpResult(triggerTs, baseTs); + return; + } + + Snapshot mainSnapshot = table.snapshot(targetBranch); + Long currentMainSnapshotId = mainSnapshot != null ? mainSnapshot.snapshotId() : null; + handleMainBranchChange(currentMainSnapshotId); + lastMainSnapshotId = currentMainSnapshotId; + + if (indexSnapshotId == null) { + indexSnapshotId = currentMainSnapshotId; + } + + List<Snapshot> stagingSnapshots = + collectStagingSnapshots(stagingSnapshot, lastStagingSnapshotId, mainSnapshot); + + if (stagingSnapshots.isEmpty()) { + LOG.info("No new staging snapshots to process on branch '{}'.", stagingBranch); + pendingStagingSnapshotId = stagingSnapshot.snapshotId(); + emitNoOpResult(triggerTs, baseTs); + return; + } + + if (stagingSnapshots.size() > maxSnapshotsPerTrigger) { + stagingSnapshots = stagingSnapshots.subList(0, maxSnapshotsPerTrigger); + } + + emitReadCommandsForSnapshots(stagingSnapshots, baseTs, triggerTs); + } catch (Exception e) { + LOG.error( + "Error processing equality deletes for table {} task {}[{}]", + tableName, + taskName, + taskIndex, + e); + output.collect(TaskResultAggregator.ERROR_STREAM, new StreamRecord<>(e)); + emitNoOpResult(triggerTs, baseTs); + } + } + + private void handleMainBranchChange(Long currentMainSnapshotId) { + boolean mainChanged = + lastMainSnapshotId != null && !Objects.equals(lastMainSnapshotId, currentMainSnapshotId); + if (!mainChanged) { + return; + } + + if (currentMainSnapshotId == null) { + mainIndexEmittedSet.clear(); + indexSnapshotId = null; + LOG.info("Main branch '{}' was deleted, clearing index.", targetBranch); + return; + } + + boolean needsReindex = false; + for (Snapshot s : + SnapshotUtil.ancestorsBetween(table, currentMainSnapshotId, lastMainSnapshotId)) { + if (DataOperations.REPLACE.equals(s.operation())) { + needsReindex = true; + break; + } + + String commitProp = + s.summary().get(EqualityConvertCommitter.COMMITTED_STAGING_SNAPSHOT_PROPERTY); + if (commitProp == null) { + needsReindex = true; + break; + } + } + + if (needsReindex) { + mainIndexEmittedSet.clear(); + indexSnapshotId = currentMainSnapshotId; + reindexCounter.inc(); + LOG.info( + "External or compaction change detected on main branch '{}' ({} -> {}). " + + "Will re-emit main data for index rebuild.", + targetBranch, + lastMainSnapshotId, + currentMainSnapshotId); + } else { + LOG.info( + "Main branch '{}' advanced ({} -> {}), only own commits detected.", + targetBranch, + lastMainSnapshotId, + currentMainSnapshotId); + } + } + + private void emitReadCommandsForSnapshots( + List<Snapshot> stagingSnapshots, long baseTs, long triggerTs) { + nextPhaseOffset = 0; + + List<DataFile> allNewDataFiles = Lists.newArrayList(); + List<DeleteFile> allStagingDeleteFiles = Lists.newArrayList(); + Set<List<Integer>> activeFieldSets = Sets.newHashSet(); + boolean hasEqDeletes = false; + + // Per staging snapshot, emit read commands in three phases with ascending timestamps + // and watermarks between phases to guarantee ordering: + // Phase 0 (baseTs + offset): main data files (index refresh) + // Phase 1 (baseTs + offset+1): equality delete files (resolution against the index) + // Phase 2 (baseTs + offset+2): staging data files (index update for next snapshot) + for (Snapshot snapshot : stagingSnapshots) { + List<DataFile> snapshotDataFiles = Lists.newArrayList(); + Map<List<Integer>, List<DeleteFile>> deletesByFieldIds = Maps.newHashMap(); + SnapshotChanges changes = SnapshotChanges.builderFor(table).snapshot(snapshot).build(); + + for (DataFile dataFile : changes.addedDataFiles()) { + snapshotDataFiles.add(dataFile.copy()); + } + + for (DeleteFile deleteFile : changes.addedDeleteFiles()) { + if (deleteFile.content() == FileContent.EQUALITY_DELETES) { + deletesByFieldIds + .computeIfAbsent(deleteFile.equalityFieldIds(), k -> Lists.newArrayList()) + .add(deleteFile.copy()); + } else { + allStagingDeleteFiles.add(deleteFile.copy()); + } + } + + allNewDataFiles.addAll(snapshotDataFiles); + + if (!deletesByFieldIds.isEmpty()) { + hasEqDeletes = true; + } + + emitMainDataPhase(deletesByFieldIds, baseTs); + emitEqDeletePhase(deletesByFieldIds, baseTs, activeFieldSets); + emitSnapshotDataPhase(snapshotDataFiles, activeFieldSets, baseTs); Review Comment: That's correct. Thanks for spotting this. We need to build the set of equality deletes across all staging snapshots first. Alternatively, we could backfill the data for newly discovered equality fields. -- 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]
