Skip to content
Open
Show file tree
Hide file tree
Changes from 3 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 @@ -35,7 +35,12 @@
import org.apache.paimon.manifest.PartitionEntry;
import org.apache.paimon.options.Options;
import org.apache.paimon.partition.Partition;
import org.apache.paimon.predicate.Equal;
import org.apache.paimon.predicate.In;
import org.apache.paimon.predicate.LeafPredicate;
import org.apache.paimon.predicate.LeafPredicateExtractor;
import org.apache.paimon.predicate.Predicate;
import org.apache.paimon.predicate.PredicateBuilder;
import org.apache.paimon.reader.RecordReader;
import org.apache.paimon.table.FileStoreTable;
import org.apache.paimon.table.ReadonlyTable;
Expand All @@ -56,15 +61,19 @@
import org.apache.paimon.utils.InternalRowUtils;
import org.apache.paimon.utils.IteratorRecordReader;
import org.apache.paimon.utils.JsonSerdeUtil;
import org.apache.paimon.utils.PartitionPredicateHelper;
import org.apache.paimon.utils.ProjectedRow;
import org.apache.paimon.utils.SerializationUtils;

import org.apache.paimon.shade.guava30.com.google.common.collect.Iterators;

import javax.annotation.Nullable;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
Expand Down Expand Up @@ -140,32 +149,95 @@ public Table copy(Map<String, String> dynamicOptions) {

private static class PartitionsScan extends ReadOnceTableScan {

@Nullable private LeafPredicate partitionPredicate;

@Override
public InnerTableScan withFilter(Predicate predicate) {
if (predicate == null) {
return this;
}

Map<String, LeafPredicate> leafPredicates =
predicate.visit(LeafPredicateExtractor.INSTANCE);
this.partitionPredicate = leafPredicates.get("partition");

// Handle Or(Equal, Equal...) pattern from PredicateBuilder.in() with <=20 literals
if (this.partitionPredicate == null) {
for (Predicate andChild : PredicateBuilder.splitAnd(predicate)) {
LeafPredicate inPred = convertOrEqualsToIn(andChild, "partition");
if (inPred != null) {
this.partitionPredicate = inPred;
break;
}
}
}
return this;
}

@Nullable
private static LeafPredicate convertOrEqualsToIn(Predicate predicate, String targetField) {
List<Predicate> orChildren = PredicateBuilder.splitOr(predicate);
if (orChildren.size() <= 1) {
return null;
}
List<Object> literals = new ArrayList<>();
String fieldName = null;
int fieldIndex = -1;
DataType fieldType = null;
for (Predicate child : orChildren) {
if (!(child instanceof LeafPredicate)) {
return null;
}
LeafPredicate leaf = (LeafPredicate) child;
if (!(leaf.function() instanceof Equal)) {
return null;
}
if (fieldName == null) {
fieldName = leaf.fieldName();
fieldIndex = leaf.index();
fieldType = leaf.type();
} else if (!fieldName.equals(leaf.fieldName())) {
return null;
}
literals.addAll(leaf.literals());
}
if (!targetField.equals(fieldName)) {
return null;
}
return new LeafPredicate(In.INSTANCE, fieldType, fieldIndex, fieldName, literals);
}

@Override
public Plan innerPlan() {
return () -> Collections.singletonList(new PartitionsSplit());
return () -> Collections.singletonList(new PartitionsSplit(partitionPredicate));
}
}

private static class PartitionsSplit extends SingletonSplit {

private static final long serialVersionUID = 1L;

@Nullable private final LeafPredicate partitionPredicate;

private PartitionsSplit(@Nullable LeafPredicate partitionPredicate) {
this.partitionPredicate = partitionPredicate;
}

@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
return o != null && getClass() == o.getClass();
if (o == null || getClass() != o.getClass()) {
return false;
}
PartitionsSplit that = (PartitionsSplit) o;
return Objects.equals(partitionPredicate, that.partitionPredicate);
}

@Override
public int hashCode() {
return 1;
return Objects.hash(partitionPredicate);
}

@Override
Expand All @@ -186,7 +258,7 @@ public PartitionsRead(FileStoreTable table) {

@Override
public InnerTableRead withFilter(Predicate predicate) {
// TODO
// filter pushdown is handled at the Scan layer through PartitionsSplit
return this;
}

Expand All @@ -207,7 +279,8 @@ public RecordReader<InternalRow> createReader(Split split) throws IOException {
throw new IllegalArgumentException("Unsupported split: " + split.getClass());
}

List<Partition> partitions = listPartitions();
PartitionsSplit partitionsSplit = (PartitionsSplit) split;
List<Partition> partitions = listPartitions(partitionsSplit.partitionPredicate);

List<DataType> fieldTypes =
fileStoreTable.schema().logicalPartitionType().getFieldTypes();
Expand Down Expand Up @@ -320,17 +393,17 @@ private Timestamp toTimestamp(Long epochMillis) {
Instant.ofEpochMilli(epochMillis), ZoneId.systemDefault()));
}

private List<Partition> listPartitions() {
private List<Partition> listPartitions(@Nullable LeafPredicate partitionPredicate) {
CatalogLoader catalogLoader = fileStoreTable.catalogEnvironment().catalogLoader();
if (TimeTravelUtil.hasTimeTravelOptions(new Options(fileStoreTable.options()))
|| catalogLoader == null) {
return listPartitionEntries();
return listPartitionEntries(partitionPredicate);
}

try (Catalog catalog = catalogLoader.load()) {
Identifier baseIdentifier = fileStoreTable.catalogEnvironment().identifier();
if (baseIdentifier == null) {
return listPartitionEntries();
return listPartitionEntries(partitionPredicate);
}
String branch = fileStoreTable.coreOptions().branch();
Identifier identifier;
Expand All @@ -343,15 +416,55 @@ private List<Partition> listPartitions() {
} else {
identifier = baseIdentifier;
}
return catalog.listPartitions(identifier);
List<Partition> partitions = catalog.listPartitions(identifier);
return filterByPredicate(partitions, partitionPredicate);
} catch (Exception e) {
return listPartitionEntries();
return listPartitionEntries(partitionPredicate);
}
}

private List<Partition> filterByPredicate(
List<Partition> partitions, @Nullable LeafPredicate partitionPredicate) {
if (partitionPredicate == null) {
return partitions;
}
List<String> partitionKeys = fileStoreTable.partitionKeys();
String defaultPartitionName = fileStoreTable.coreOptions().partitionDefaultName();
return partitions.stream()
.filter(
p -> {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < partitionKeys.size(); i++) {
if (i > 0) {
sb.append("/");
}
String value = p.spec().get(partitionKeys.get(i));
sb.append(partitionKeys.get(i))
.append("=")
.append(value == null ? defaultPartitionName : value);
}
return partitionPredicate.test(
GenericRow.of(BinaryString.fromString(sb.toString())));
})
.collect(Collectors.toList());
}

private List<Partition> listPartitionEntries() {
List<PartitionEntry> partitionEntries =
fileStoreTable.newScan().withLevelFilter(level -> true).listPartitionEntries();
private List<Partition> listPartitionEntries(@Nullable LeafPredicate partitionPredicate) {
InnerTableScan scan = fileStoreTable.newScan().withLevelFilter(level -> true);

if (partitionPredicate != null) {
List<String> partitionKeys = fileStoreTable.partitionKeys();
RowType partitionType = fileStoreTable.schema().logicalPartitionType();
Predicate partPred =
PartitionPredicateHelper.buildPartitionPredicate(
partitionPredicate, partitionKeys, partitionType);
if (partPred == null) {
return Collections.emptyList();
}
scan.withPartitionFilter(partPred);
}

List<PartitionEntry> partitionEntries = scan.listPartitionEntries();
RowType partitionType = fileStoreTable.schema().logicalPartitionType();
String defaultPartitionName = fileStoreTable.coreOptions().partitionDefaultName();
String[] partitionColumns = fileStoreTable.partitionKeys().toArray(new String[0]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,27 +36,36 @@

/**
* Helper for applying partition predicate pushdown in system tables (BucketsTable, FilesTable,
* FileKeyRangesTable).
* FileKeyRangesTable, PartitionsTable).
*/
public class PartitionPredicateHelper {

public static boolean applyPartitionFilter(
SnapshotReader snapshotReader,
@Nullable LeafPredicate partitionPredicate,
List<String> partitionKeys,
RowType partitionType) {
if (partitionPredicate == null) {
return true;
}

/**
* Build a partition-typed predicate from a string-based leaf predicate on the "partition"
* column.
*
* @return the predicate on partition fields, or {@code null} if the partition spec is invalid
* (indicating no results should be returned)
*/
@Nullable
public static Predicate buildPartitionPredicate(
LeafPredicate partitionPredicate, List<String> partitionKeys, RowType partitionType) {
if (partitionPredicate.function() instanceof Equal) {
LinkedHashMap<String, String> partSpec =
parsePartitionSpec(
partitionPredicate.literals().get(0).toString(), partitionKeys);
if (partSpec == null) {
return false;
return null;
}
snapshotReader.withPartitionFilter(partSpec);
PredicateBuilder partBuilder = new PredicateBuilder(partitionType);
List<Predicate> predicates = new ArrayList<>();
for (int i = 0; i < partitionKeys.size(); i++) {
Object value =
TypeUtils.castFromString(
partSpec.get(partitionKeys.get(i)), partitionType.getTypeAt(i));
predicates.add(partBuilder.equal(i, value));
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.

We should consider default partitions here. If the value is the default partition name, this should become isNull(...) rather than equal(...).

}
return PredicateBuilder.and(predicates);
} else if (partitionPredicate.function() instanceof In) {
List<Predicate> orPredicates = new ArrayList<>();
PredicateBuilder partBuilder = new PredicateBuilder(partitionType);
Expand All @@ -75,51 +84,88 @@ public static boolean applyPartitionFilter(
}
orPredicates.add(PredicateBuilder.and(andPredicates));
}
if (!orPredicates.isEmpty()) {
snapshotReader.withPartitionFilter(PredicateBuilder.or(orPredicates));
}
return orPredicates.isEmpty() ? null : PredicateBuilder.or(orPredicates);
} else if (partitionPredicate.function() instanceof LeafBinaryFunction) {
LinkedHashMap<String, String> partSpec =
parsePartitionSpec(
partitionPredicate.literals().get(0).toString(), partitionKeys);
if (partSpec != null) {
PredicateBuilder partBuilder = new PredicateBuilder(partitionType);
List<Predicate> predicates = new ArrayList<>();
for (int i = 0; i < partitionKeys.size(); i++) {
Object value =
TypeUtils.castFromString(
partSpec.get(partitionKeys.get(i)), partitionType.getTypeAt(i));
predicates.add(
new LeafPredicate(
partitionPredicate.function(),
partitionType.getTypeAt(i),
i,
partitionKeys.get(i),
Collections.singletonList(value)));
}
snapshotReader.withPartitionFilter(PredicateBuilder.and(predicates));
if (partSpec == null) {
return null;
}
PredicateBuilder partBuilder = new PredicateBuilder(partitionType);
List<Predicate> predicates = new ArrayList<>();
for (int i = 0; i < partitionKeys.size(); i++) {
Object value =
TypeUtils.castFromString(
partSpec.get(partitionKeys.get(i)), partitionType.getTypeAt(i));
predicates.add(
new LeafPredicate(
partitionPredicate.function(),
partitionType.getTypeAt(i),
i,
partitionKeys.get(i),
Collections.singletonList(value)));
}
return PredicateBuilder.and(predicates);
}
return null;
}

public static boolean applyPartitionFilter(
SnapshotReader snapshotReader,
@Nullable LeafPredicate partitionPredicate,
List<String> partitionKeys,
RowType partitionType) {
if (partitionPredicate == null) {
return true;
}

Predicate predicate =
buildPartitionPredicate(partitionPredicate, partitionKeys, partitionType);
if (predicate == null) {
return 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.

false? No record will be returned? {@code null} if the predicate cannot be pushed down (unsupported predicate type or invalid partition spec.

Copy link
Copy Markdown
Member Author

@sundapeng sundapeng Apr 13, 2026

Choose a reason for hiding this comment

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

Good catch. The issue is that buildPartitionPredicate returned null for two different reasons:

  1. Unsupported predicate type (e.g., isNotNull) → should skip pushdown, return all data
  2. Invalid partition spec (e.g., partial key [2] on a 2-column partition table) → no match, return empty is correct

Simply changing return false to return true would break FilesTableTest.testReadWithNotFullPartitionKey (case 2).

Fixed by using @Nullable Predicate with clear semantics: null means unsupported (skip pushdown), PredicateBuilder.alwaysFalse() means no match (return empty), and a normal predicate means apply pushdown. This reuses the existing AlwaysFalse predicate instead of introducing a wrapper class.

Added testBucketsTableUnsupportedPredicateFallsBackToFullScan to cover the regression.

}
snapshotReader.withPartitionFilter(predicate);
return true;
}

@Nullable
public static LinkedHashMap<String, String> parsePartitionSpec(
String partitionStr, List<String> partitionKeys) {
// Handle {value1, value2} format (BucketsTable, FilesTable, FileKeyRangesTable)
if (partitionStr.startsWith("{")) {
partitionStr = partitionStr.substring(1);
if (partitionStr.endsWith("}")) {
partitionStr = partitionStr.substring(0, partitionStr.length() - 1);
}
String[] partFields = partitionStr.split(", ");
if (partitionKeys.size() != partFields.length) {
return null;
}
LinkedHashMap<String, String> partSpec = new LinkedHashMap<>();
for (int i = 0; i < partitionKeys.size(); i++) {
partSpec.put(partitionKeys.get(i), partFields[i]);
}
return partSpec;
}
if (partitionStr.endsWith("}")) {
partitionStr = partitionStr.substring(0, partitionStr.length() - 1);
}
String[] partFields = partitionStr.split(", ");

// Handle key=value/key=value format (PartitionsTable)
String[] partFields = partitionStr.split("/");
if (partitionKeys.size() != partFields.length) {
return null;
}
LinkedHashMap<String, String> partSpec = new LinkedHashMap<>();
for (int i = 0; i < partitionKeys.size(); i++) {
partSpec.put(partitionKeys.get(i), partFields[i]);
for (String field : partFields) {
int eqIndex = field.indexOf('=');
if (eqIndex < 0) {
return null;
}
partSpec.put(field.substring(0, eqIndex), field.substring(eqIndex + 1));
}
for (String key : partitionKeys) {
if (!partSpec.containsKey(key)) {
return null;
}
}
return partSpec;
}
Expand Down
Loading