XuQianJin-Stars commented on code in PR #3518:
URL: https://github.com/apache/fluss/pull/3518#discussion_r3465663399


##########
fluss-lake/fluss-lake-hudi/src/main/java/org/apache/fluss/lake/hudi/tiering/HudiCompactionService.java:
##########
@@ -0,0 +1,465 @@
+/*
+ * 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.fluss.lake.hudi.tiering;
+
+import org.apache.fluss.metadata.TableBucket;
+
+import org.apache.flink.configuration.Configuration;
+import org.apache.hudi.avro.model.HoodieCompactionOperation;
+import org.apache.hudi.avro.model.HoodieCompactionPlan;
+import org.apache.hudi.client.HoodieFlinkWriteClient;
+import org.apache.hudi.client.WriteStatus;
+import org.apache.hudi.common.data.HoodieListData;
+import org.apache.hudi.common.engine.HoodieReaderContext;
+import org.apache.hudi.common.model.CompactionOperation;
+import org.apache.hudi.common.model.HoodieCommitMetadata;
+import org.apache.hudi.common.model.HoodieWriteStat;
+import org.apache.hudi.common.table.HoodieTableMetaClient;
+import org.apache.hudi.common.table.timeline.HoodieInstant;
+import org.apache.hudi.common.table.timeline.HoodieTimeline;
+import org.apache.hudi.common.table.timeline.InstantGenerator;
+import org.apache.hudi.common.util.CompactionUtils;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.common.util.collection.Pair;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.configuration.FlinkOptions;
+import org.apache.hudi.exception.HoodieException;
+import org.apache.hudi.index.bucket.BucketIdentifier;
+import org.apache.hudi.sink.compact.FlinkCompactionConfig;
+import org.apache.hudi.sink.compact.strategy.CompactionPlanStrategies;
+import org.apache.hudi.storage.StorageConfiguration;
+import org.apache.hudi.table.HoodieFlinkTable;
+import org.apache.hudi.table.action.compact.CompactHelpers;
+import 
org.apache.hudi.table.action.compact.HoodieFlinkMergeOnReadTableCompactor;
+import org.apache.hudi.table.format.FlinkRowDataReaderContext;
+import org.apache.hudi.table.format.InternalSchemaManager;
+import org.apache.hudi.util.CompactionUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+
+import static org.apache.fluss.utils.Preconditions.checkNotNull;
+
+/** Coordinates Hudi compaction scheduling, execution, and commit for tiering 
writers. */
+public class HudiCompactionService {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(HudiCompactionService.class);
+
+    private final HudiWriteTableInfo hudiTableInfo;
+    private final HoodieFlinkWriteClient<?> writeClient;
+    private final HoodieTableMetaClient metaClient;
+    private final HoodieFlinkTable<?> table;
+    private final Configuration conf;
+    @Nullable private final TableBucket tableBucket;
+    @Nullable private final String partition;
+
+    private InternalSchemaManager internalSchemaManager;
+
+    public HudiCompactionService(
+            HudiWriteTableInfo hudiTableInfo,
+            @Nullable TableBucket tableBucket,
+            @Nullable String partition) {
+        this.hudiTableInfo = checkNotNull(hudiTableInfo, "Hudi write table 
info must not be null.");
+        this.writeClient = hudiTableInfo.getWriteClient();
+        this.metaClient = hudiTableInfo.getMetaClient();
+        this.table = writeClient.getHoodieTable();
+        this.conf = hudiTableInfo.getFlinkConfig();
+        this.tableBucket = tableBucket;
+        this.partition = partition;
+    }
+
+    public boolean scheduleCompaction() {
+        LOG.info("Scheduling Hudi compaction for table {}.", 
hudiTableInfo.getTablePath());
+        metaClient.reloadActiveTimeline();
+        try {
+            boolean scheduled = 
writeClient.scheduleCompaction(Option.empty()).isPresent();
+            metaClient.reloadActiveTimeline();
+            if (!scheduled) {
+                LOG.info(
+                        "No Hudi compaction plan was scheduled for table {}.",
+                        hudiTableInfo.getTablePath());
+            }
+            return scheduled;
+        } catch (Exception e) {
+            LOG.warn(
+                    "Failed to schedule Hudi compaction for table {}.",
+                    hudiTableInfo.getTablePath(),
+                    e);
+            return false;
+        }
+    }
+
+    public void markSelectedCompactionsInflight() {
+        List<String> compactionInstantTimes = 
getSelectedCompactionInstantTimes();
+        if (compactionInstantTimes.isEmpty()) {
+            return;
+        }
+
+        HoodieTimeline pendingCompactionTimeline =
+                table.getActiveTimeline().filterPendingCompactionTimeline();
+        InstantGenerator instantGenerator = table.getInstantGenerator();
+
+        for (String timestamp : compactionInstantTimes) {
+            HoodieInstant inflightInstant =
+                    instantGenerator.getCompactionInflightInstant(timestamp);
+            if (pendingCompactionTimeline.containsInstant(inflightInstant)) {
+                LOG.info("Rollback stale inflight Hudi compaction instant 
{}.", timestamp);
+                table.rollbackInflightCompaction(
+                        inflightInstant, writeClient.getTransactionManager());
+                metaClient.reloadActiveTimeline();
+            }
+        }
+
+        pendingCompactionTimeline = 
table.getActiveTimeline().filterPendingCompactionTimeline();
+        for (String timestamp : compactionInstantTimes) {
+            HoodieInstant requestedInstant =
+                    instantGenerator.getCompactionRequestedInstant(timestamp);
+            if (pendingCompactionTimeline.containsInstant(requestedInstant)) {
+                
table.getActiveTimeline().transitionCompactionRequestedToInflight(requestedInstant);
+                LOG.info("Marked Hudi compaction instant {} as inflight.", 
timestamp);
+            }
+        }
+        metaClient.reloadActiveTimeline();
+    }
+
+    public List<String> getInflightCompactionInstantTimes() {
+        List<String> compactionInstantTimes = 
getSelectedCompactionInstantTimes();
+        if (compactionInstantTimes.isEmpty()) {
+            return Collections.emptyList();
+        }
+
+        HoodieTimeline pendingCompactionTimeline =
+                
metaClient.getActiveTimeline().filterPendingCompactionTimeline();
+        InstantGenerator instantGenerator = table.getInstantGenerator();
+
+        List<String> inflightCompactionInstantTimes = new ArrayList<>();
+        for (String timestamp : compactionInstantTimes) {
+            HoodieInstant inflightInstant =
+                    instantGenerator.getCompactionInflightInstant(timestamp);
+            if (pendingCompactionTimeline.containsInstant(inflightInstant)) {
+                
inflightCompactionInstantTimes.add(inflightInstant.requestedTime());
+            }
+        }
+        LOG.info(
+                "Found {} inflight Hudi compaction instants for table {}.",
+                inflightCompactionInstantTimes.size(),
+                hudiTableInfo.getTablePath());
+        return inflightCompactionInstantTimes;
+    }
+
+    public List<Pair<String, HoodieCompactionPlan>> getCompactionPlans(
+            List<String> compactionInstantTimes) {
+        if (compactionInstantTimes == null || 
compactionInstantTimes.isEmpty()) {
+            return Collections.emptyList();
+        }
+
+        List<Pair<String, HoodieCompactionPlan>> compactionPlans =
+                compactionInstantTimes.stream()
+                        .map(
+                                timestamp -> {
+                                    try {
+                                        return Pair.of(
+                                                timestamp,
+                                                
CompactionUtils.getCompactionPlan(
+                                                        metaClient, 
timestamp));
+                                    } catch (Exception e) {
+                                        throw new HoodieException(
+                                                "Failed to get Hudi compaction 
plan " + timestamp,
+                                                e);
+                                    }
+                                })
+                        .filter(pair -> isValidCompactionPlan(pair.getRight()))
+                        .collect(Collectors.toList());
+
+        LOG.info(
+                "Loaded {} Hudi compaction plans for table {}.",
+                compactionPlans.size(),
+                hudiTableInfo.getTablePath());
+        return compactionPlans;
+    }
+
+    public Map<String, List<WriteStatus>> executeCompaction(
+            List<Pair<String, HoodieCompactionPlan>> compactionPlans) throws 
IOException {
+        if (compactionPlans == null || compactionPlans.isEmpty()) {
+            return Collections.emptyMap();
+        }
+        TableBucket currentBucket =
+                checkNotNull(tableBucket, "Hudi compaction execution requires 
a table bucket.");
+
+        Map<String, List<WriteStatus>> writeStatusesByInstant = new 
HashMap<>();
+        HoodieWriteConfig writeConfig = writeClient.getConfig();
+        String hudiPartitionPath = toHudiPartitionPath(partition);
+
+        for (Pair<String, HoodieCompactionPlan> planPair : compactionPlans) {
+            String instantTime = planPair.getLeft();
+            HoodieCompactionPlan compactionPlan = planPair.getRight();
+            for (HoodieCompactionOperation operation : 
compactionPlan.getOperations()) {
+                if (!belongsToCurrentWriter(operation, hudiPartitionPath, 
currentBucket)) {
+                    continue;
+                }
+
+                HoodieFlinkMergeOnReadTableCompactor<?> compactor =
+                        new HoodieFlinkMergeOnReadTableCompactor<>();
+                CompactionOperation compactionOperation =
+                        
CompactionOperation.convertFromAvroRecordInstance(operation);
+
+                metaClient.reload();
+                try {
+                    CompactionUtil.setAvroSchema(writeConfig, metaClient);
+                    List<WriteStatus> writeStatuses =
+                            compactor.compact(
+                                    writeConfig,
+                                    compactionOperation,
+                                    instantTime,
+                                    table.getTaskContextSupplier(),
+                                    createReaderContext(true),
+                                    table);
+                    writeStatusesByInstant
+                            .computeIfAbsent(instantTime, ignored -> new 
ArrayList<>())

Review Comment:
   If `compactor.compact(...)` fails partway through, the writeStatuses already 
added to `writeStatusesByInstant` for prior operations of the same instant are 
silently dropped (we throw and the map never reaches `commitCompaction`), but 
the inflight instant on the timeline is **not** rolled back here. That can 
leave half-written log/base files on storage and an inflight instant that will 
be re-attempted later with stale data.
   
   Please either roll back the inflight instant in a `catch`/`finally` (via 
`CompactionUtil.rollbackCompaction(table, instantTime, txnManager)`) before 
rethrowing, or document very clearly that recovery is delegated to the next 
round (and add an integration test that exercises it).



##########
fluss-lake/fluss-lake-hudi/src/main/java/org/apache/fluss/lake/hudi/tiering/HudiCompactionService.java:
##########
@@ -0,0 +1,465 @@
+/*
+ * 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.fluss.lake.hudi.tiering;
+
+import org.apache.fluss.metadata.TableBucket;
+
+import org.apache.flink.configuration.Configuration;
+import org.apache.hudi.avro.model.HoodieCompactionOperation;
+import org.apache.hudi.avro.model.HoodieCompactionPlan;
+import org.apache.hudi.client.HoodieFlinkWriteClient;
+import org.apache.hudi.client.WriteStatus;
+import org.apache.hudi.common.data.HoodieListData;
+import org.apache.hudi.common.engine.HoodieReaderContext;
+import org.apache.hudi.common.model.CompactionOperation;
+import org.apache.hudi.common.model.HoodieCommitMetadata;
+import org.apache.hudi.common.model.HoodieWriteStat;
+import org.apache.hudi.common.table.HoodieTableMetaClient;
+import org.apache.hudi.common.table.timeline.HoodieInstant;
+import org.apache.hudi.common.table.timeline.HoodieTimeline;
+import org.apache.hudi.common.table.timeline.InstantGenerator;
+import org.apache.hudi.common.util.CompactionUtils;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.common.util.collection.Pair;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.configuration.FlinkOptions;
+import org.apache.hudi.exception.HoodieException;
+import org.apache.hudi.index.bucket.BucketIdentifier;
+import org.apache.hudi.sink.compact.FlinkCompactionConfig;
+import org.apache.hudi.sink.compact.strategy.CompactionPlanStrategies;
+import org.apache.hudi.storage.StorageConfiguration;
+import org.apache.hudi.table.HoodieFlinkTable;
+import org.apache.hudi.table.action.compact.CompactHelpers;
+import 
org.apache.hudi.table.action.compact.HoodieFlinkMergeOnReadTableCompactor;
+import org.apache.hudi.table.format.FlinkRowDataReaderContext;
+import org.apache.hudi.table.format.InternalSchemaManager;
+import org.apache.hudi.util.CompactionUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+
+import static org.apache.fluss.utils.Preconditions.checkNotNull;
+
+/** Coordinates Hudi compaction scheduling, execution, and commit for tiering 
writers. */
+public class HudiCompactionService {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(HudiCompactionService.class);
+
+    private final HudiWriteTableInfo hudiTableInfo;
+    private final HoodieFlinkWriteClient<?> writeClient;
+    private final HoodieTableMetaClient metaClient;
+    private final HoodieFlinkTable<?> table;
+    private final Configuration conf;
+    @Nullable private final TableBucket tableBucket;
+    @Nullable private final String partition;
+
+    private InternalSchemaManager internalSchemaManager;
+
+    public HudiCompactionService(
+            HudiWriteTableInfo hudiTableInfo,
+            @Nullable TableBucket tableBucket,
+            @Nullable String partition) {
+        this.hudiTableInfo = checkNotNull(hudiTableInfo, "Hudi write table 
info must not be null.");
+        this.writeClient = hudiTableInfo.getWriteClient();
+        this.metaClient = hudiTableInfo.getMetaClient();
+        this.table = writeClient.getHoodieTable();
+        this.conf = hudiTableInfo.getFlinkConfig();
+        this.tableBucket = tableBucket;
+        this.partition = partition;
+    }
+
+    public boolean scheduleCompaction() {
+        LOG.info("Scheduling Hudi compaction for table {}.", 
hudiTableInfo.getTablePath());
+        metaClient.reloadActiveTimeline();
+        try {
+            boolean scheduled = 
writeClient.scheduleCompaction(Option.empty()).isPresent();
+            metaClient.reloadActiveTimeline();
+            if (!scheduled) {
+                LOG.info(
+                        "No Hudi compaction plan was scheduled for table {}.",
+                        hudiTableInfo.getTablePath());
+            }
+            return scheduled;
+        } catch (Exception e) {
+            LOG.warn(
+                    "Failed to schedule Hudi compaction for table {}.",
+                    hudiTableInfo.getTablePath(),
+                    e);
+            return false;
+        }
+    }
+
+    public void markSelectedCompactionsInflight() {
+        List<String> compactionInstantTimes = 
getSelectedCompactionInstantTimes();
+        if (compactionInstantTimes.isEmpty()) {
+            return;
+        }
+
+        HoodieTimeline pendingCompactionTimeline =
+                table.getActiveTimeline().filterPendingCompactionTimeline();
+        InstantGenerator instantGenerator = table.getInstantGenerator();
+
+        for (String timestamp : compactionInstantTimes) {
+            HoodieInstant inflightInstant =
+                    instantGenerator.getCompactionInflightInstant(timestamp);
+            if (pendingCompactionTimeline.containsInstant(inflightInstant)) {
+                LOG.info("Rollback stale inflight Hudi compaction instant 
{}.", timestamp);
+                table.rollbackInflightCompaction(
+                        inflightInstant, writeClient.getTransactionManager());
+                metaClient.reloadActiveTimeline();
+            }
+        }
+
+        pendingCompactionTimeline = 
table.getActiveTimeline().filterPendingCompactionTimeline();
+        for (String timestamp : compactionInstantTimes) {
+            HoodieInstant requestedInstant =
+                    instantGenerator.getCompactionRequestedInstant(timestamp);
+            if (pendingCompactionTimeline.containsInstant(requestedInstant)) {
+                
table.getActiveTimeline().transitionCompactionRequestedToInflight(requestedInstant);
+                LOG.info("Marked Hudi compaction instant {} as inflight.", 
timestamp);
+            }
+        }
+        metaClient.reloadActiveTimeline();
+    }
+
+    public List<String> getInflightCompactionInstantTimes() {
+        List<String> compactionInstantTimes = 
getSelectedCompactionInstantTimes();
+        if (compactionInstantTimes.isEmpty()) {
+            return Collections.emptyList();
+        }
+
+        HoodieTimeline pendingCompactionTimeline =
+                
metaClient.getActiveTimeline().filterPendingCompactionTimeline();
+        InstantGenerator instantGenerator = table.getInstantGenerator();
+
+        List<String> inflightCompactionInstantTimes = new ArrayList<>();
+        for (String timestamp : compactionInstantTimes) {
+            HoodieInstant inflightInstant =
+                    instantGenerator.getCompactionInflightInstant(timestamp);
+            if (pendingCompactionTimeline.containsInstant(inflightInstant)) {
+                
inflightCompactionInstantTimes.add(inflightInstant.requestedTime());
+            }
+        }
+        LOG.info(
+                "Found {} inflight Hudi compaction instants for table {}.",
+                inflightCompactionInstantTimes.size(),
+                hudiTableInfo.getTablePath());
+        return inflightCompactionInstantTimes;
+    }
+
+    public List<Pair<String, HoodieCompactionPlan>> getCompactionPlans(
+            List<String> compactionInstantTimes) {
+        if (compactionInstantTimes == null || 
compactionInstantTimes.isEmpty()) {
+            return Collections.emptyList();
+        }
+
+        List<Pair<String, HoodieCompactionPlan>> compactionPlans =
+                compactionInstantTimes.stream()
+                        .map(
+                                timestamp -> {
+                                    try {
+                                        return Pair.of(
+                                                timestamp,
+                                                
CompactionUtils.getCompactionPlan(
+                                                        metaClient, 
timestamp));
+                                    } catch (Exception e) {
+                                        throw new HoodieException(
+                                                "Failed to get Hudi compaction 
plan " + timestamp,
+                                                e);
+                                    }
+                                })
+                        .filter(pair -> isValidCompactionPlan(pair.getRight()))
+                        .collect(Collectors.toList());
+
+        LOG.info(
+                "Loaded {} Hudi compaction plans for table {}.",
+                compactionPlans.size(),
+                hudiTableInfo.getTablePath());
+        return compactionPlans;
+    }
+
+    public Map<String, List<WriteStatus>> executeCompaction(
+            List<Pair<String, HoodieCompactionPlan>> compactionPlans) throws 
IOException {
+        if (compactionPlans == null || compactionPlans.isEmpty()) {
+            return Collections.emptyMap();
+        }
+        TableBucket currentBucket =
+                checkNotNull(tableBucket, "Hudi compaction execution requires 
a table bucket.");
+
+        Map<String, List<WriteStatus>> writeStatusesByInstant = new 
HashMap<>();
+        HoodieWriteConfig writeConfig = writeClient.getConfig();
+        String hudiPartitionPath = toHudiPartitionPath(partition);
+
+        for (Pair<String, HoodieCompactionPlan> planPair : compactionPlans) {
+            String instantTime = planPair.getLeft();
+            HoodieCompactionPlan compactionPlan = planPair.getRight();
+            for (HoodieCompactionOperation operation : 
compactionPlan.getOperations()) {
+                if (!belongsToCurrentWriter(operation, hudiPartitionPath, 
currentBucket)) {
+                    continue;
+                }
+
+                HoodieFlinkMergeOnReadTableCompactor<?> compactor =
+                        new HoodieFlinkMergeOnReadTableCompactor<>();
+                CompactionOperation compactionOperation =
+                        
CompactionOperation.convertFromAvroRecordInstance(operation);
+
+                metaClient.reload();
+                try {
+                    CompactionUtil.setAvroSchema(writeConfig, metaClient);
+                    List<WriteStatus> writeStatuses =
+                            compactor.compact(
+                                    writeConfig,
+                                    compactionOperation,
+                                    instantTime,
+                                    table.getTaskContextSupplier(),
+                                    createReaderContext(true),
+                                    table);
+                    writeStatusesByInstant
+                            .computeIfAbsent(instantTime, ignored -> new 
ArrayList<>())
+                            .addAll(writeStatuses);
+                    LOG.info(
+                            "Compacted Hudi file id {} for table {}, partition 
{}, bucket {}, instant {}.",
+                            operation.getFileId(),
+                            hudiTableInfo.getTablePath(),
+                            hudiPartitionPath,
+                            currentBucket.getBucket(),
+                            instantTime);
+                } catch (Exception e) {
+                    throw new IOException(
+                            String.format(
+                                    "Failed to execute Hudi compaction for 
table %s, partition %s, bucket %s, instant %s.",
+                                    hudiTableInfo.getTablePath(),
+                                    hudiPartitionPath,
+                                    currentBucket.getBucket(),
+                                    instantTime),
+                            e);
+                }
+            }
+        }
+        return writeStatusesByInstant;
+    }
+
+    public String commitCompaction(
+            Map<String, HudiWriteStats> compactionWriteStats,
+            Map<String, String> snapshotProperties)
+            throws IOException {
+        if (compactionWriteStats == null || compactionWriteStats.isEmpty()) {
+            return null;
+        }
+
+        String latestInstant = null;
+        List<String> compactionInstants = new 
ArrayList<>(compactionWriteStats.keySet());
+        Collections.sort(compactionInstants);
+        for (String compactionInstant : compactionInstants) {
+            HudiWriteStats writeStats = 
compactionWriteStats.get(compactionInstant);
+
+            if (writeStats.getTotalErrorRecords() > 0 && 
!conf.get(FlinkOptions.IGNORE_FAILED)) {

Review Comment:
   `throw new IOException(...)` here will reach 
`HudiLakeCommitter#commitCompactionAndSchedule` (line 228) which only logs a 
WARN and continues. The error-record check therefore has no real effect on the 
main commit. Either:
   - propagate the failure all the way up so the data commit also fails 
(preferred), or
   - remove this `throw` and only roll back, since the current behaviour is 
misleading.
   Otherwise users running with `IGNORE_FAILED=false` will silently get partial 
compaction results.



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

Reply via email to