Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import static org.apache.hudi.common.table.timeline.TimelineMetadataUtils.deserializeAvroMetadata;
Expand Down Expand Up @@ -169,10 +170,20 @@ public Map<HoodieFileGroupId, String> getFileGroupIdAndFullPaths(String basePath
*/
public Map<String, StoragePathInfo> getFullPathToInfo(HoodieStorage storage,
String basePath) {
return getFullPathToInfo(storage, basePath, partition -> true);
}

/**
* Returns file statuses for the selected partitions, keyed by full path.
*/
public Map<String, StoragePathInfo> getFullPathToInfo(HoodieStorage storage, String basePath,
Predicate<String> partitionFilter) {
Map<String, StoragePathInfo> fullPathToInfoMap = new HashMap<>();
for (List<HoodieWriteStat> stats : getPartitionToWriteStats().values()) {
// Iterate through all the written files.
for (HoodieWriteStat stat : stats) {
for (Map.Entry<String, List<HoodieWriteStat>> partition : getPartitionToWriteStats().entrySet()) {
if (!partitionFilter.test(partition.getKey())) {
continue;
}
for (HoodieWriteStat stat : partition.getValue()) {
String relativeFilePath = stat.getPath();
StoragePath fullPath = relativeFilePath != null
? FSUtils.constructAbsolutePath(basePath, relativeFilePath) : null;
Expand Down Expand Up @@ -200,10 +211,19 @@ public Map<String, StoragePathInfo> getFullPathToInfo(HoodieStorage storage,
* @return the file ID to file status mapping
*/
public Map<String, StoragePathInfo> getFileIdToInfo(String basePath) {
return getFileIdToInfo(basePath, partition -> true);
}

/**
* Returns file statuses for the selected partitions, keyed by file ID.
*/
public Map<String, StoragePathInfo> getFileIdToInfo(String basePath, Predicate<String> partitionFilter) {
Map<String, StoragePathInfo> fileIdToInfoMap = new HashMap<>();
for (List<HoodieWriteStat> stats : getPartitionToWriteStats().values()) {
// Iterate through all the written files.
for (HoodieWriteStat stat : stats) {
for (Map.Entry<String, List<HoodieWriteStat>> partition : getPartitionToWriteStats().entrySet()) {
if (!partitionFilter.test(partition.getKey())) {
continue;
}
for (HoodieWriteStat stat : partition.getValue()) {
String relativeFilePath = stat.getPath();
StoragePath fullPath =
relativeFilePath != null ? FSUtils.constructAbsolutePath(basePath,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;

/**
* Factory for {@link WriteProfile}.
Expand Down Expand Up @@ -119,13 +121,28 @@ public static List<StoragePathInfo> getFilesFromMetadata(
List<HoodieCommitMetadata> metadataList,
HoodieTableType tableType,
boolean ignoreMissingFiles) {
return getFilesFromMetadata(basePath, hadoopConf, metadataList, tableType, ignoreMissingFiles, null);
}

/**
* Looks up files only in selected partitions; a null set keeps all partitions.
*/
@Nullable
public static List<StoragePathInfo> getFilesFromMetadata(
Path basePath,
Configuration hadoopConf,
List<HoodieCommitMetadata> metadataList,
HoodieTableType tableType,
boolean ignoreMissingFiles,
@Nullable Set<String> selectedPartitions) {
Predicate<String> partitionFilter = selectedPartitions == null ? partition -> true : selectedPartitions::contains;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could this overload take a Predicate<String> partitionFilter directly? Both planner callers can pass readPartitions::contains, and the existing unfiltered overload can pass partition -> true. That removes the nullable-set convention and this conversion while preserving the existing overloads.

HoodieStorage storage = HoodieStorageUtils.getStorage(basePath.toString(), HadoopFSUtils.getStorageConf(hadoopConf));
Map<String, StoragePathInfo> uniqueIdToInfoMap = new HashMap<>();
// If a file has been touched multiple times in the given commits, the return value should keep the one
// from the latest commit, so here we traverse in reverse order
for (int i = metadataList.size() - 1; i >= 0; i--) {
for (Map.Entry<String, StoragePathInfo> entry : getFilesToRead(hadoopConf, metadataList.get(i),
basePath.toString(), tableType).entrySet()) {
for (Map.Entry<String, StoragePathInfo> entry : getFilesToRead(storage, metadataList.get(i),
basePath.toString(), tableType, partitionFilter).entrySet()) {
if (StreamerUtil.isValidFile(entry.getValue())
&& !uniqueIdToInfoMap.containsKey(entry.getKey())) {
if (StreamerUtil.fileExists(storage, entry.getValue().getPath())) {
Expand All @@ -140,16 +157,17 @@ public static List<StoragePathInfo> getFilesFromMetadata(
}

private static Map<String, StoragePathInfo> getFilesToRead(
Configuration hadoopConf,
HoodieStorage storage,
HoodieCommitMetadata metadata,
String basePath,
HoodieTableType tableType
HoodieTableType tableType,
Predicate<String> partitionFilter
) {
switch (tableType) {
case COPY_ON_WRITE:
return metadata.getFileIdToInfo(basePath);
return metadata.getFileIdToInfo(basePath, partitionFilter);
case MERGE_ON_READ:
return metadata.getFullPathToInfo(HoodieStorageUtils.getStorage(basePath, HadoopFSUtils.getStorageConf(hadoopConf)), basePath);
return metadata.getFullPathToInfo(storage, basePath, partitionFilter);
default:
throw new AssertionError();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ public Result inputSplits(
}
List<StoragePathInfo> files = WriteProfiles.getFilesFromMetadata(
path, (org.apache.hadoop.conf.Configuration) metaClient.getStorageConf().unwrap(),
metadataList, metaClient.getTableType(), false);
metadataList, metaClient.getTableType(), false, readPartitions);
if (files == null) {
log.warn("Found deleted files in metadata, falling back to full table scan.");
// fallback to full table scan
Expand Down Expand Up @@ -393,7 +393,7 @@ private List<MergeOnReadInputSplit> getIncInputSplits(
return Collections.emptyList();
}
List<StoragePathInfo> pathInfoList = WriteProfiles.getFilesFromMetadata(
path, hadoopConf, metadataList, metaClient.getTableType());
path, hadoopConf, metadataList, metaClient.getTableType(), true, readPartitions);
List<FileSlice> fileSlices = getFileSlices(metaClient, commitTimeline, readPartitions, pathInfoList, queryContext.getMaxCompletionTime(), skipCompaction);

if (fileSlices.isEmpty()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,10 @@
import org.apache.hudi.common.config.HoodieMetadataConfig;
import org.apache.hudi.common.model.FileSlice;
import org.apache.hudi.common.model.HoodieCommitMetadata;
import org.apache.hudi.common.model.HoodiePartitionMetadata;
import org.apache.hudi.common.model.HoodieReplaceCommitMetadata;
import org.apache.hudi.common.model.HoodieTableType;
import org.apache.hudi.common.model.HoodieWriteStat;
import org.apache.hudi.common.model.WriteOperationType;
import org.apache.hudi.common.table.cdc.HoodieCDCFileSplit;
import org.apache.hudi.common.table.cdc.HoodieCDCInferenceCase;
Expand All @@ -32,6 +34,7 @@
import org.apache.hudi.common.table.timeline.HoodieInstant;
import org.apache.hudi.common.table.timeline.HoodieTimeline;
import org.apache.hudi.common.table.view.HoodieTableFileSystemView;
import org.apache.hudi.common.testutils.FileCreateUtils;
import org.apache.hudi.common.testutils.HoodieCommonTestHarness;
import org.apache.hudi.common.testutils.HoodieTestUtils;
import org.apache.hudi.common.util.CommitUtils;
Expand All @@ -41,6 +44,7 @@
import org.apache.hudi.sink.partitioner.profile.WriteProfiles;
import org.apache.hudi.source.prune.ColumnStatsProbe;
import org.apache.hudi.source.prune.PartitionPruners;
import org.apache.hudi.storage.StoragePath;
import org.apache.hudi.storage.StoragePathInfo;
import org.apache.hudi.table.format.cdc.CdcInputSplit;
import org.apache.hudi.table.format.mor.MergeOnReadInputSplit;
Expand All @@ -64,6 +68,7 @@
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.MockedStatic;

import java.io.IOException;
import java.lang.reflect.Method;
Expand All @@ -87,6 +92,9 @@
import static org.junit.jupiter.api.Assertions.assertIterableEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.CALLS_REAL_METHODS;
import static org.mockito.Mockito.mockStatic;

/**
* Test cases for {@link IncrementalInputSplits}.
Expand Down Expand Up @@ -364,6 +372,134 @@ void testInputSplitsWithPartitionPruner(
assertEquals(expectedPartitions, partitions);
}

@ParameterizedTest
@EnumSource(HoodieTableType.class)
void testIncrementalLookupChecksOnlySelectedPartitions(HoodieTableType tableType) throws Exception {
Configuration conf = TestConfigurations.getDefaultConf(basePath);
conf.set(FlinkOptions.TABLE_TYPE, tableType.name());
metaClient = HoodieTestUtils.init(basePath, tableType);
// The split planner only needs completed commit metadata and existing file statuses.
String olderInstant = "001";
StoragePath olderFile = new StoragePath(
FileCreateUtils.createBaseFile(metaClient, "par1", olderInstant, "file-par1", 100L));
HoodieCommitMetadata olderMetadata = new HoodieCommitMetadata();
olderMetadata.setOperationType(WriteOperationType.INSERT);
addFileToCommit(olderMetadata, "par1", "file-par1", olderFile);
writeFixtureCommit(tableType, olderInstant, olderMetadata);

String instant = "002";
HoodieCommitMetadata metadata = new HoodieCommitMetadata();
metadata.setOperationType(WriteOperationType.INSERT);
for (String partition : Arrays.asList("par1", "par2")) {
String fileId = "file-" + partition;
StoragePath file = new StoragePath(FileCreateUtils.createBaseFile(metaClient, partition, instant, fileId, 100L));
Comment on lines +397 to +399

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could the MOR case append two distinct logs to the same selected file group in successive delta commits and assert that both paths appear in the split? With one base file per file ID, the test still passed when I routed MOR through the COW getFileIdToInfo lookup. I tried the two-commit fixture and it caught that change when the earlier log disappeared from the split.

new HoodiePartitionMetadata(metaClient.getStorage(), instant, metaClient.getBasePath(),
file.getParent(), Option.empty()).trySave(partition);
addFileToCommit(metadata, partition, fileId, file);
}
writeFixtureCommit(tableType, instant, metadata);
HoodieInstant commit = metaClient.reloadActiveTimeline().getCommitsTimeline()
.filterCompletedInstants().lastInstant().get();
conf.set(FlinkOptions.READ_START_COMMIT, commit.getCompletionTime());

IncrementalInputSplits all = IncrementalInputSplits.builder()
.conf(conf).path(new Path(basePath)).rowType(TestConfigurations.ROW_TYPE).build();
IncrementalInputSplits selected = IncrementalInputSplits.builder()
.conf(conf).path(new Path(basePath)).rowType(TestConfigurations.ROW_TYPE)
.partitionPruner(partitions -> partitions.contains("par1") ? Collections.singleton("par1") : Collections.emptySet())
.build();

List<StoragePath> probes = new ArrayList<>();
try (MockedStatic<StreamerUtil> streamerUtil = mockStatic(StreamerUtil.class, CALLS_REAL_METHODS)) {
streamerUtil.when(() -> StreamerUtil.fileExists(any(), any())).thenAnswer(invocation -> {
StoragePath file = invocation.getArgument(1);
probes.add(file);
return invocation.callRealMethod();
});

assertEquals(Arrays.asList("par1", "par2"), getFilteredPartitions(all.inputSplits(metaClient, false)));
assertEquals(Arrays.asList("par1", "par2"), getFilteredPartitions(all.inputSplits(metaClient, null, false)));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could these two assertions compare the partition names in any order, while still checking that each occurs exactly once? Both splits have the same latest commit, so their relative order comes from iterating the partition set. Sorting the actual names before comparing would keep the duplicate-split check and allow either valid order.

List<StoragePath> excludedFiles = probes.stream().distinct()
.filter(file -> file.getParent().getName().equals("par2")).collect(Collectors.toList());
assertFalse(excludedFiles.isEmpty());
for (StoragePath file : excludedFiles) {
assertTrue(metaClient.getStorage().deleteFile(file));
}

probes.clear();
assertEquals(Collections.singletonList("par1"), getFilteredPartitions(selected.inputSplits(metaClient, false)));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we add a second file group to par1 in commit 001 and leave it untouched in 002? I forced the bounded planner to take the full-scan fallback after a successful filtered lookup, and all three new cases still passed. With the extra group, the incremental lookup returns one split here and the full scan returns two. I tried that fixture on Flink 1.20.1. Both COW and MOR caught the forced fallback, and all three cases passed on the PR head after updating the later fallback assertion to expect both older files.

assertEquals(Collections.singletonList("par1"), getFilteredPartitions(selected.inputSplits(metaClient, null, false)));
assertFalse(probes.isEmpty());
assertTrue(probes.stream().allMatch(file -> file.getParent().getName().equals("par1")), probes::toString);

List<StoragePath> selectedFiles = probes.stream().distinct().collect(Collectors.toList());
for (StoragePath file : selectedFiles) {
assertTrue(metaClient.getStorage().deleteFile(file));
}
probes.clear();
List<MergeOnReadInputSplit> bounded = selected.inputSplits(metaClient, false).getInputSplits();
assertEquals(1, bounded.size());
assertEquals(olderFile.getName(), new StoragePath(bounded.get(0).getBasePath().get()).getName());
assertTrue(selected.inputSplits(metaClient, null, false).isEmpty());
assertFalse(probes.isEmpty());
assertTrue(probes.stream().allMatch(file -> file.getParent().getName().equals("par1")), probes::toString);
}
}

@Test
void testIncrementalLookupPreservesMultipleMorLogsForOneFileGroup() throws Exception {
String partition = "par1";
String fileId = "file-par1";
HoodieTableType tableType = HoodieTableType.MERGE_ON_READ;
Configuration conf = TestConfigurations.getDefaultConf(basePath);
conf.set(FlinkOptions.TABLE_TYPE, tableType.name());
metaClient = HoodieTestUtils.init(basePath, tableType);
List<String> expectedNames = new ArrayList<>();
for (String instant : Arrays.asList("001", "002")) {
StoragePath log = new StoragePath(FileCreateUtils.createLogFile(metaClient, partition, instant, fileId, 1, 100));
new HoodiePartitionMetadata(metaClient.getStorage(), instant, metaClient.getBasePath(),
log.getParent(), Option.empty()).trySave(partition);
expectedNames.add(log.getName());
HoodieCommitMetadata metadata = new HoodieCommitMetadata();
metadata.setOperationType(WriteOperationType.UPSERT);
addFileToCommit(metadata, partition, fileId, log);
writeFixtureCommit(tableType, instant, metadata);
metaClient.reloadActiveTimeline();
}
String firstCompletionTime = metaClient.getActiveTimeline().getCommitsTimeline()
.filterCompletedInstants().firstInstant().get().getCompletionTime();
conf.set(FlinkOptions.READ_START_COMMIT, firstCompletionTime);
IncrementalInputSplits selected = IncrementalInputSplits.builder()
.conf(conf).path(new Path(basePath)).rowType(TestConfigurations.ROW_TYPE)
.partitionPruner(partitions -> Collections.singleton(partition))
.build();
for (IncrementalInputSplits.Result result :
Arrays.asList(selected.inputSplits(metaClient, false), selected.inputSplits(metaClient, null, false))) {
List<MergeOnReadInputSplit> splits = result.getInputSplits();
assertEquals(1, splits.size());
assertEquals(expectedNames.stream().sorted().collect(Collectors.toList()),
splits.get(0).getLogPaths().get().stream().map(path -> new StoragePath(path).getName())
.sorted().collect(Collectors.toList()));
}
}

private static void addFileToCommit(HoodieCommitMetadata metadata, String partition, String fileId, StoragePath file) {
HoodieWriteStat stat = new HoodieWriteStat();
stat.setFileId(fileId);
stat.setPartitionPath(partition);
stat.setPath(partition + "/" + file.getName());
stat.setFileSizeInBytes(100L);
metadata.addWriteStat(partition, stat);
}

private void writeFixtureCommit(HoodieTableType tableType, String instant, HoodieCommitMetadata metadata) throws Exception {
if (tableType == HoodieTableType.COPY_ON_WRITE) {
FileCreateUtils.createCommit(metaClient, metaClient.getCommitMetadataSerDe(), instant, Option.of(metadata));
} else {
FileCreateUtils.createDeltaCommit(metaClient, metaClient.getCommitMetadataSerDe(), instant, Option.empty(), metadata);
}
}

@ParameterizedTest
@EnumSource(value = HoodieTableType.class)
void testInputSplitsWithPartitionStatsPruner(HoodieTableType tableType) throws Exception {
Expand Down