Copilot commented on code in PR #7486: URL: https://github.com/apache/paimon/pull/7486#discussion_r2963845143
########## paimon-core/src/main/java/org/apache/paimon/operation/BucketSelector.java: ########## @@ -0,0 +1,230 @@ +/* + * 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.BucketFunctionType; +import org.apache.paimon.bucket.BucketFunction; +import org.apache.paimon.data.BinaryRow; +import org.apache.paimon.data.GenericRow; +import org.apache.paimon.data.serializer.InternalRowSerializer; +import org.apache.paimon.predicate.Equal; +import org.apache.paimon.predicate.FieldRef; +import org.apache.paimon.predicate.In; +import org.apache.paimon.predicate.LeafPredicate; +import org.apache.paimon.predicate.PartitionValuePredicateVisitor; +import org.apache.paimon.predicate.Predicate; +import org.apache.paimon.types.RowType; +import org.apache.paimon.utils.BiFilter; +import org.apache.paimon.utils.TriFilter; + +import org.apache.paimon.shade.guava30.com.google.common.collect.ImmutableSet; + +import javax.annotation.concurrent.ThreadSafe; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Consumer; +import java.util.stream.Collectors; + +import static org.apache.paimon.predicate.PredicateBuilder.and; +import static org.apache.paimon.predicate.PredicateBuilder.pickTransformFieldMapping; +import static org.apache.paimon.predicate.PredicateBuilder.splitAnd; +import static org.apache.paimon.predicate.PredicateBuilder.splitOr; + +/** Selector to select bucket from {@link Predicate}. */ +@ThreadSafe +public class BucketSelector implements TriFilter<BinaryRow, Integer, Integer> { + + public static final int MAX_VALUES = 1000; + + private final BucketFunctionType bucketFunctionType; + private final RowType rowType; + private final RowType partitionType; + private final RowType bucketKeyType; + private final Predicate predicate; + private final Map<BinaryRow, Optional<PartitionSelector>> partitionSelectors; + + public BucketSelector( + Predicate predicate, + BucketFunctionType bucketFunctionType, + RowType rowType, + RowType partitionType, + RowType bucketKeyType) { + this.predicate = predicate; + this.bucketFunctionType = bucketFunctionType; + this.rowType = rowType; + this.partitionType = partitionType; + this.bucketKeyType = bucketKeyType; + this.partitionSelectors = new ConcurrentHashMap<>(); + } + + @Override + public boolean test(BinaryRow partition, Integer bucket, Integer numBucket) { + return partitionSelectors + .computeIfAbsent(partition, this::createPartitionSelector) + .map(selector -> selector.test(bucket, numBucket)) + .orElse(true); + } + + private Optional<PartitionSelector> createPartitionSelector(BinaryRow partition) { + Optional<Predicate> partRemoved = + predicate.visit( + new PartitionValuePredicateVisitor(rowType, partitionType, partition)); + if (!partRemoved.isPresent()) { + return Optional.empty(); + } + + List<Predicate> bucketFilters = + pickTransformFieldMapping( + splitAnd(partRemoved.get()), + rowType.getFieldNames(), + bucketKeyType.getFieldNames()); + if (bucketFilters.isEmpty()) { + return Optional.empty(); + } + + return createPartitionSelector(and(bucketFilters)); + } + + private Optional<PartitionSelector> createPartitionSelector(Predicate bucketPredicate) { + @SuppressWarnings("unchecked") + List<Object>[] bucketValues = new List[bucketKeyType.getFieldCount()]; + + BucketFunction bucketFunction = BucketFunction.create(bucketFunctionType, bucketKeyType); + + nextAnd: + for (Predicate andPredicate : splitAnd(bucketPredicate)) { + Integer reference = null; + List<Object> values = new ArrayList<>(); + for (Predicate orPredicate : splitOr(andPredicate)) { + if (orPredicate instanceof LeafPredicate) { + LeafPredicate leaf = (LeafPredicate) orPredicate; + Optional<FieldRef> fieldRefOptional = leaf.fieldRefOptional(); + if (fieldRefOptional.isPresent()) { + FieldRef fieldRef = fieldRefOptional.get(); + if (reference == null || reference == fieldRef.index()) { + reference = fieldRef.index(); + if (leaf.function().equals(Equal.INSTANCE) + || leaf.function().equals(In.INSTANCE)) { + values.addAll( + leaf.literals().stream() + .filter(Objects::nonNull) + .collect(Collectors.toList())); + continue; + } + } + } + } + + // failed, go to next predicate + continue nextAnd; + } + if (reference != null) { + if (bucketValues[reference] != null) { + // Same field appears in multiple AND branches, + // compute intersection to narrow down possible values + bucketValues[reference].retainAll(new HashSet<>(values)); + if (bucketValues[reference].isEmpty()) { + // Empty intersection: contradictory conditions, no match + return Optional.empty(); + } + } else { + bucketValues[reference] = values; + } + } + } + + int rowCount = 1; + for (List<Object> values : bucketValues) { + if (values == null) { + return Optional.empty(); + } + + rowCount *= values.size(); + if (rowCount > MAX_VALUES) { + return Optional.empty(); + } Review Comment: In BucketSelector, `rowCount *= values.size()` uses `int` multiplication and can overflow into a negative value (e.g., two large IN-lists on a composite bucket key). That can bypass the `rowCount > MAX_VALUES` guard and then `assembleRows` may attempt to enumerate an enormous Cartesian product, risking hangs/OOM. Consider switching `rowCount` to `long` (or using checked multiplication) and short-circuiting as soon as the product exceeds `MAX_VALUES` (ideally also cap/dedup per-column value collection early to avoid holding huge literal lists). ```suggestion long rowCount = 1L; for (List<Object> values : bucketValues) { if (values == null) { return Optional.empty(); } int size = values.size(); if (size <= 0) { // No possible values for this column, no matching rows return Optional.empty(); } // Check for overflow and limit total number of combinations if (rowCount > (long) MAX_VALUES / size) { return Optional.empty(); } rowCount *= size; ``` ########## paimon-common/src/main/java/org/apache/paimon/utils/TriFilter.java: ########## @@ -0,0 +1,33 @@ +/* + * 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.utils; + +/** Represents a filter (boolean-valued function) of three argument. */ Review Comment: Typo/grammar in the Javadoc: "filter ... of three argument" should be "... of three arguments". ```suggestion /** Represents a filter (boolean-valued function) of three arguments. */ ``` ########## paimon-core/src/test/java/org/apache/paimon/table/BucketFilterScanTest.java: ########## @@ -0,0 +1,250 @@ +/* + * 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.table; + +import org.apache.paimon.catalog.Identifier; +import org.apache.paimon.data.GenericRow; +import org.apache.paimon.predicate.Predicate; +import org.apache.paimon.predicate.PredicateBuilder; +import org.apache.paimon.schema.Schema; +import org.apache.paimon.table.source.DataSplit; +import org.apache.paimon.types.DataTypes; + +import org.junit.jupiter.api.Test; + +import java.util.Set; +import java.util.stream.Collectors; + +import static org.apache.paimon.CoreOptions.BUCKET; +import static org.apache.paimon.CoreOptions.BUCKET_KEY; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Tests bucket filtering with compound predicates on a partitioned, fixed-bucket, append-only + * table. + */ +public class BucketFilterScanTest extends TableTestBase { + + @Test + public void testBucketFilterWithCompoundPredicateOnAppendTable() throws Exception { + testBucketFilterWithCompoundPredicate(false); + } + + @Test + public void testBucketFilterWithCompoundPredicateOnPkTable() throws Exception { + testBucketFilterWithCompoundPredicate(true); + } + + @Test + public void testCompositeBucketFilterWithCompoundPredicateOnAppendTable() throws Exception { + testCompositeBucketFilterWithCompoundPredicate(false); + } + + @Test + public void testCompositeBucketFilterWithCompoundPredicateOnPkTable() throws Exception { + testCompositeBucketFilterWithCompoundPredicate(true); + } + + /** + * Tests bucket filtering with compound predicates on a single-field bucket key. + * + * <p>Table schema: + * + * <ul> + * <li>Partition key: column 'a' (INT) + * <li>Bucket key: column 'b' (INT) + * <li>Bucket count: 10 + * </ul> + * + * <p>Data distribution: 5 partitions (a=1 to 5) × 20 b-values (b=1 to 20) = 100 rows. + * + * <p>Test scenarios: + * + * <ol> + * <li>Predicate: (a < 3 AND b = 5) OR (a = 3 AND b = 7) - Tests partition range filter + * with bucket equality, combined with OR. Expected: buckets for partition 1,2 with b=5 + * and partition 3 with b=7. + * <li>Predicate: (a < 3 AND b = 5) OR (a = 3 AND b < 100) - Tests partition range with + * bucket equality, OR partition equality with bucket range. Expected: mixed buckets from + * partition 3 and specific buckets from partitions 1,2. + * <li>Predicate: (a = 2 AND b = 5) OR (a = 3 AND b = 7) - Tests partition equality with + * bucket equality in both OR branches. Expected: exact bucket matching for each + * partition-b combination. + * </ol> + */ + private void testBucketFilterWithCompoundPredicate(boolean pk) throws Exception { + // ---- schema & table ---- + Schema.Builder builder = + Schema.newBuilder() + .column("a", DataTypes.INT()) + .column("b", DataTypes.INT()) + .column("c", DataTypes.INT()) + .partitionKeys("a") + .option(BUCKET.key(), "10"); + if (pk) { + builder.primaryKey("a", "b"); + } else { + builder.option(BUCKET_KEY.key(), "b"); + } + Schema schema = builder.build(); + + Identifier tableId = identifier("test_bucket_filter"); + catalog.createTable(tableId, schema, false); + Table table = catalog.getTable(tableId); + + // ---- write data: 5 partitions × 20 b-values = 100 rows ---- + GenericRow[] rows = new GenericRow[100]; + int idx = 0; Review Comment: These assertions hard-code specific bucket IDs (e.g., "3,1", "1,6"). That makes the test brittle to changes in the bucket hash implementation / BucketFunctionType defaults, even if bucket-level pruning is still correct. Consider computing expected bucket IDs using the same BucketFunction as production (and asserting on those), so the test validates pruning behavior without depending on a particular hash result. ########## paimon-core/src/test/java/org/apache/paimon/table/BucketFilterScanTest.java: ########## @@ -0,0 +1,250 @@ +/* + * 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.table; + +import org.apache.paimon.catalog.Identifier; +import org.apache.paimon.data.GenericRow; +import org.apache.paimon.predicate.Predicate; +import org.apache.paimon.predicate.PredicateBuilder; +import org.apache.paimon.schema.Schema; +import org.apache.paimon.table.source.DataSplit; +import org.apache.paimon.types.DataTypes; + +import org.junit.jupiter.api.Test; + +import java.util.Set; +import java.util.stream.Collectors; + +import static org.apache.paimon.CoreOptions.BUCKET; +import static org.apache.paimon.CoreOptions.BUCKET_KEY; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Tests bucket filtering with compound predicates on a partitioned, fixed-bucket, append-only + * table. + */ +public class BucketFilterScanTest extends TableTestBase { + + @Test + public void testBucketFilterWithCompoundPredicateOnAppendTable() throws Exception { + testBucketFilterWithCompoundPredicate(false); + } + + @Test + public void testBucketFilterWithCompoundPredicateOnPkTable() throws Exception { + testBucketFilterWithCompoundPredicate(true); + } + + @Test + public void testCompositeBucketFilterWithCompoundPredicateOnAppendTable() throws Exception { + testCompositeBucketFilterWithCompoundPredicate(false); + } + + @Test + public void testCompositeBucketFilterWithCompoundPredicateOnPkTable() throws Exception { + testCompositeBucketFilterWithCompoundPredicate(true); + } + + /** + * Tests bucket filtering with compound predicates on a single-field bucket key. + * + * <p>Table schema: + * + * <ul> + * <li>Partition key: column 'a' (INT) + * <li>Bucket key: column 'b' (INT) + * <li>Bucket count: 10 + * </ul> + * + * <p>Data distribution: 5 partitions (a=1 to 5) × 20 b-values (b=1 to 20) = 100 rows. + * + * <p>Test scenarios: + * + * <ol> + * <li>Predicate: (a < 3 AND b = 5) OR (a = 3 AND b = 7) - Tests partition range filter + * with bucket equality, combined with OR. Expected: buckets for partition 1,2 with b=5 + * and partition 3 with b=7. + * <li>Predicate: (a < 3 AND b = 5) OR (a = 3 AND b < 100) - Tests partition range with + * bucket equality, OR partition equality with bucket range. Expected: mixed buckets from + * partition 3 and specific buckets from partitions 1,2. + * <li>Predicate: (a = 2 AND b = 5) OR (a = 3 AND b = 7) - Tests partition equality with + * bucket equality in both OR branches. Expected: exact bucket matching for each + * partition-b combination. + * </ol> + */ + private void testBucketFilterWithCompoundPredicate(boolean pk) throws Exception { + // ---- schema & table ---- + Schema.Builder builder = + Schema.newBuilder() + .column("a", DataTypes.INT()) + .column("b", DataTypes.INT()) + .column("c", DataTypes.INT()) + .partitionKeys("a") + .option(BUCKET.key(), "10"); + if (pk) { + builder.primaryKey("a", "b"); + } else { + builder.option(BUCKET_KEY.key(), "b"); + } + Schema schema = builder.build(); + + Identifier tableId = identifier("test_bucket_filter"); + catalog.createTable(tableId, schema, false); + Table table = catalog.getTable(tableId); + + // ---- write data: 5 partitions × 20 b-values = 100 rows ---- + GenericRow[] rows = new GenericRow[100]; + int idx = 0; + for (int a = 1; a <= 5; a++) { + for (int b = 1; b <= 20; b++) { + rows[idx++] = GenericRow.of(a, b, a * 100 + b); + } + } + write(table, rows); + PredicateBuilder pb = new PredicateBuilder(table.rowType()); + + // ---- build predicate: (a < 3 AND b = 5) OR (a = 3 AND b = 7) ---- + Predicate predicate1 = + PredicateBuilder.or( + PredicateBuilder.and(pb.lessThan(0, 3), pb.equal(1, 5)), + PredicateBuilder.and(pb.equal(0, 3), pb.equal(1, 7))); + assertThat(plan(table, predicate1)).containsExactlyInAnyOrder("3,1", "1,6", "2,6"); + + // ---- build predicate: (a < 3 AND b = 5) OR (a = 3 AND b < 100) ---- + Predicate predicate2 = + PredicateBuilder.or( + PredicateBuilder.and(pb.lessThan(0, 3), pb.equal(1, 5)), + PredicateBuilder.and(pb.equal(0, 3), pb.lessThan(1, 100))); + assertThat(plan(table, predicate2)) + .containsExactlyInAnyOrder( + "3,0", "3,1", "1,6", "3,4", "3,5", "2,6", "3,6", "3,7", "3,8"); + + // ---- build predicate: (a = 2 AND b = 5) OR (a = 3 AND b = 7) ---- + Predicate predicate3 = + PredicateBuilder.or( + PredicateBuilder.and(pb.equal(0, 2), pb.equal(1, 5)), + PredicateBuilder.and(pb.equal(0, 3), pb.equal(1, 7))); + assertThat(plan(table, predicate3)).containsExactlyInAnyOrder("3,1", "2,6"); + } + + /** + * Tests bucket filtering with compound predicates on a composite (multi-field) bucket key. + * + * <p>Table schema: + * + * <ul> + * <li>Partition key: column 'a' (INT) + * <li>Bucket key: columns 'b' and 'c' (composite, INT) + * <li>Bucket count: 10 + * </ul> + * + * <p>Data distribution: 5 partitions (a=1 to 5) × 20 b-values (b=1 to 20) × 10 c-values (c=0 to + * 9) = 1000 rows. + * + * <p>Test scenarios: + * + * <ol> + * <li>Predicate: ((a < 3 AND b = 5) OR (a = 3 AND b = 7)) AND c = 5 - Tests nested OR + * within AND, with partition range, bucket field equality, and additional bucket field + * filter. The 'c = 5' condition is part of the composite bucket key, affecting bucket + * selection. + * <li>Predicate: ((a < 3 AND b = 5) OR (a = 3 AND b < 100)) AND c = 5 - Tests range + * predicate on one bucket field (b) combined with equality on another (c). Validates + * handling of multiple bucket key fields with different predicate types. + * <li>Predicate: ((a = 2 AND b = 5) OR (a = 3 AND b = 7)) AND c = 5 - Tests exact matching on + * both partition and bucket fields. The composite bucket key (b,c) ensures precise bucket + * targeting. + * </ol> + */ + private void testCompositeBucketFilterWithCompoundPredicate(boolean pk) throws Exception { + // ---- schema & table ---- + Schema.Builder builder = + Schema.newBuilder() + .column("a", DataTypes.INT()) + .column("b", DataTypes.INT()) + .column("c", DataTypes.INT()) + .partitionKeys("a") + .option(BUCKET.key(), "10"); + if (pk) { + builder.primaryKey("a", "b", "c"); + } else { + builder.option(BUCKET_KEY.key(), "b,c"); + } + Schema schema = builder.build(); + + Identifier tableId = identifier("test_composite_bucket_filter"); + catalog.createTable(tableId, schema, false); + Table table = catalog.getTable(tableId); + + // ---- write data: 5 partitions × 20 b-values x 10 c-values = 1000 rows ---- + GenericRow[] rows = new GenericRow[1000]; + int idx = 0; + for (int a = 1; a <= 5; a++) { + for (int b = 1; b <= 20; b++) { + for (int c = 0; c < 10; c++) { Review Comment: Same brittleness here: the expected results are hard-coded bucket IDs for composite keys (e.g., "3,9", "3,0"...). To keep the test stable across bucket hash / BucketFunction changes, consider deriving expected bucket IDs via BucketFunction from the (b,c) literals instead of asserting specific numeric buckets. -- 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]
