mxm commented on code in PR #15996: URL: https://github.com/apache/iceberg/pull/15996#discussion_r3124493470
########## 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; + } Review Comment: I addressed this. We now trigger reading from main to eargerly refresh the index. -- 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]
