leaves12138 commented on code in PR #7842: URL: https://github.com/apache/paimon/pull/7842#discussion_r3271348809
########## paimon-core/src/main/java/org/apache/paimon/operation/ManifestFileSorter.java: ########## @@ -0,0 +1,740 @@ +/* + * 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.paimon.operation; + +import org.apache.paimon.CoreOptions; +import org.apache.paimon.codegen.CodeGenUtils; +import org.apache.paimon.codegen.RecordComparator; +import org.apache.paimon.data.BinaryRow; +import org.apache.paimon.io.RollingFileWriter; +import org.apache.paimon.manifest.FileEntry; +import org.apache.paimon.manifest.ManifestEntry; +import org.apache.paimon.manifest.ManifestFile; +import org.apache.paimon.manifest.ManifestFileMeta; +import org.apache.paimon.operation.ManifestFileMerger.FullCompactionReadResult; +import org.apache.paimon.partition.PartitionPredicate; +import org.apache.paimon.types.RowType; +import org.apache.paimon.utils.Filter; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.annotation.Nullable; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.PriorityQueue; +import java.util.Set; +import java.util.function.Function; + +import static java.util.Collections.singletonList; +import static org.apache.paimon.utils.ManifestReadThreadPool.sequentialBatchedExecute; + +/** Manifest file sorter that sorts and rewrites manifest files by a configured partition field. */ +public class ManifestFileSorter { + + private static final Logger LOG = LoggerFactory.getLogger(ManifestFileSorter.class); + + /** + * Try to sort-rewrite the merged manifest list by a configured partition field. If the sort + * field cannot be resolved, the input is returned as-is. + */ + static Optional<List<ManifestFileMeta>> trySortRewrite( + List<ManifestFileMeta> input, + List<ManifestFileMeta> newFilesForAbort, + ManifestFile manifestFile, + RowType partitionType, + CoreOptions options) + throws Exception { + // Extract configuration from options + long suggestedMetaSize = options.manifestTargetSize().getBytes(); + Integer manifestReadParallelism = options.scanManifestParallelism(); + String sortPartitionField = options.manifestSortPartitionField(); + long manifestFullCompactionThresholdSize = + options.manifestFullCompactionThresholdSize().getBytes(); + // Step 1: Resolve sort field. + String sortField = resolveSortField(sortPartitionField, partitionType); + if (sortField == null) { + throw new IllegalArgumentException( + "Cannot resolve sort field for manifest sort rewrite."); + } + int sortFieldIndex = partitionType.getFieldNames().indexOf(sortField); + RecordComparator fieldComparator = + CodeGenUtils.newRecordComparator( + partitionType.getFieldTypes(), new int[] {sortFieldIndex}); + + // Step 2: Classify manifests into defaultCompaction and LSM. + List<ManifestFileMeta> result = new ArrayList<>(); + ClassifyResult classified = + classifyManifests( + input, + result, + suggestedMetaSize, + manifestFile, + partitionType, + manifestFullCompactionThresholdSize, + manifestReadParallelism); + Map<ManifestFileMeta, Boolean> defaultCompactionMap = classified.defaultCompactionManifests; + List<ManifestFileMeta> lsmFiles = classified.lsmFiles; + Set<FileEntry.Identifier> deleteEntries = classified.deleteEntries; + + // Step 3: Build LSM Tree and assign levels (only for lsmFiles). + List<ManifestSortedRun> levelRuns = + lsmFiles.isEmpty() + ? new ArrayList<>() + : buildLevelSortedRuns(lsmFiles, fieldComparator); + + // Step 4: Pick runs to compact. + ManifestPickStrategy pickStrategy = + new ManifestPickStrategy( + options.maxSizeAmplificationPercent(), options.sortedRunSizeRatio()); + List<ManifestSortedRun> pickedRuns = pickStrategy.pick(levelRuns); + + if (pickedRuns.isEmpty() && defaultCompactionMap.isEmpty()) { + LOG.debug( + "Manifest sort rewrite skipped: no runs picked and no defaultCompaction files."); + return Optional.empty(); + } + + LOG.info( + "Manifest sort rewrite: input={} files, lsm={} runs, picked={} runs, " + + "defaultCompaction={} files.", + input.size(), + levelRuns.size(), + pickedRuns.size(), + defaultCompactionMap.size()); + + Set<ManifestSortedRun> pickedSet = new HashSet<>(pickedRuns); + List<ManifestFileMeta> reusedFiles = new ArrayList<>(); + for (ManifestSortedRun run : levelRuns) { + if (!pickedSet.contains(run)) { + reusedFiles.addAll(run.files()); + } + } + result.addAll(reusedFiles); + + // Step 5: Split picked files into sections, sort and rewrite each. + List<ManifestFileMeta> pickedFiles = new ArrayList<>(); + for (ManifestSortedRun run : pickedRuns) { + pickedFiles.addAll(run.files()); + } + pickedFiles.addAll(defaultCompactionMap.keySet()); + + List<Section> sections = + splitIntoSections(pickedFiles, fieldComparator, defaultCompactionMap); + sections = mergeSmallAdjacentSections(sections, suggestedMetaSize); + + rewriteSections( + sections, + defaultCompactionMap, + manifestFile, + fieldComparator, + deleteEntries, + suggestedMetaSize, + options.manifestMergeMinCount(), + options.manifestSortMaxRewriteSize(), + result, + newFilesForAbort, + manifestReadParallelism); + + LOG.info( + "Manifest sort rewrite completed: sections={}, newFiles={}, resultFiles={}.", + sections.size(), + newFilesForAbort.size(), + result.size()); + return Optional.of(result); + } + + /** + * Classify manifest files into default-compaction group and LSM group. + * + * <p>Full compaction: small files and files overlapping delete partitions go into + * defaultCompactionManifests; the rest stay as lsmFiles. + * + * <p>Non-full compaction: delete-overlapping files go to result, small files go to + * defaultCompactionManifests for minor-style merge. + */ + private static ClassifyResult classifyManifests( + List<ManifestFileMeta> input, + List<ManifestFileMeta> result, + long suggestedMetaSize, + ManifestFile manifestFile, + RowType partitionType, + long sizeTrigger, + @Nullable Integer manifestReadParallelism) { + // Calculate total size of files that need compaction to determine full-compaction trigger + Filter<ManifestFileMeta> mustChange = + file -> file.numDeletedFiles() > 0 || file.fileSize() < suggestedMetaSize; + long totalDeltaFileSize = 0; + for (ManifestFileMeta file : input) { + if (mustChange.test(file)) { + totalDeltaFileSize += file.fileSize(); + } + } + boolean removeAllDelete = totalDeltaFileSize >= sizeTrigger; + + // Initialize classification containers and read delete entries + Map<ManifestFileMeta, Boolean> defaultCompactionManifests = new LinkedHashMap<>(); + List<ManifestFileMeta> lsmFiles = new LinkedList<>(input); + Set<FileEntry.Identifier> deleteEntries = + FileEntry.readDeletedEntries(manifestFile, input, manifestReadParallelism); Review Comment: Split full compaction and minor compaction, don't make it mixed. Refer to ManifestFileMerge.merge -- 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]
