This is an automated email from the ASF dual-hosted git repository.

JingsongLi pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/paimon.git


The following commit(s) were added to refs/heads/master by this push:
     new b2a69a8340 [core] Optimize partition discovery with projected manifest 
scans (#9321)
b2a69a8340 is described below

commit b2a69a834008d2e44679a04da5a1184616618c57
Author: zhoulii <[email protected]>
AuthorDate: Mon Nov 23 13:34:37 2026 +0800

    [core] Optimize partition discovery with projected manifest scans (#9321)
---
 .../benchmark/PartitionEntryScanBenchmark.java     | 404 +++++++++++++++++++++
 .../java/org/apache/paimon/AbstractFileStore.java  |  31 +-
 .../apache/paimon/manifest/ManifestEntryCache.java |  36 ++
 .../org/apache/paimon/manifest/ManifestFile.java   |  51 +++
 .../paimon/operation/NormalPartitionExpire.java    |  30 +-
 .../paimon/operation/PartitionEntryScanner.java    | 215 +++++++++++
 .../PartitionUpdateTimeExpireStrategy.java         |  12 +-
 .../PartitionValuesTimeExpireStrategy.java         |  15 +
 .../apache/paimon/utils/SimpleObjectsCache.java    |  34 +-
 .../operation/PartitionEntryScannerTest.java       | 376 +++++++++++++++++++
 10 files changed, 1189 insertions(+), 15 deletions(-)

diff --git 
a/paimon-benchmark/paimon-micro-benchmarks/src/test/java/org/apache/paimon/benchmark/PartitionEntryScanBenchmark.java
 
b/paimon-benchmark/paimon-micro-benchmarks/src/test/java/org/apache/paimon/benchmark/PartitionEntryScanBenchmark.java
new file mode 100644
index 0000000000..b26b762bc0
--- /dev/null
+++ 
b/paimon-benchmark/paimon-micro-benchmarks/src/test/java/org/apache/paimon/benchmark/PartitionEntryScanBenchmark.java
@@ -0,0 +1,404 @@
+/*
+ * 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.benchmark;
+
+import org.apache.paimon.CoreOptions;
+import org.apache.paimon.Snapshot;
+import org.apache.paimon.data.BinaryRow;
+import org.apache.paimon.data.BinaryString;
+import org.apache.paimon.data.GenericRow;
+import org.apache.paimon.data.serializer.InternalRowSerializer;
+import org.apache.paimon.format.SimpleColStats;
+import org.apache.paimon.fs.Path;
+import org.apache.paimon.fs.local.LocalFileIO;
+import org.apache.paimon.io.DataFileMeta;
+import org.apache.paimon.manifest.FileKind;
+import org.apache.paimon.manifest.FileSource;
+import org.apache.paimon.manifest.ManifestEntry;
+import org.apache.paimon.manifest.ManifestFile;
+import org.apache.paimon.manifest.ManifestFileMeta;
+import org.apache.paimon.manifest.PartitionEntry;
+import org.apache.paimon.operation.AbstractFileStoreScan;
+import org.apache.paimon.operation.FileStoreScan;
+import org.apache.paimon.operation.ManifestsReader;
+import org.apache.paimon.operation.PartitionEntryScanner;
+import org.apache.paimon.options.MemorySize;
+import org.apache.paimon.options.Options;
+import org.apache.paimon.partition.PartitionPredicate;
+import org.apache.paimon.predicate.Predicate;
+import org.apache.paimon.predicate.PredicateBuilder;
+import org.apache.paimon.schema.FileSystemSchemaManager;
+import org.apache.paimon.schema.Schema;
+import org.apache.paimon.schema.TableSchema;
+import org.apache.paimon.stats.SimpleStats;
+import org.apache.paimon.stats.SimpleStatsConverter;
+import org.apache.paimon.table.CatalogEnvironment;
+import org.apache.paimon.table.FileStoreTable;
+import org.apache.paimon.table.FileStoreTableFactory;
+import org.apache.paimon.table.source.ScanMode;
+import org.apache.paimon.types.DataType;
+import org.apache.paimon.types.IntType;
+import org.apache.paimon.types.RowType;
+import org.apache.paimon.types.VarCharType;
+import org.apache.paimon.utils.SegmentsCache;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import java.lang.management.ManagementFactory;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+import java.util.function.Supplier;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * Compares the generic partition scan with the partition maintenance scanner 
on identical
+ * manifests. Manifest-list I/O and data-file I/O are excluded. "Cold" refers 
to Paimon's cache, not
+ * the OS cache.
+ *
+ * <pre>
+ * mvn -pl paimon-benchmark/paimon-micro-benchmarks -am -Pfast-build \
+ *   -DwildcardSuites=none -DfailIfNoTests=false 
-Dtest=PartitionEntryScanBenchmark test
+ * </pre>
+ *
+ * <p>Use {@code partition.scan.benchmark.manifests}, {@code entries}, {@code 
partitions}, {@code
+ * stats-columns}, {@code index-bytes}, {@code parallelism}, {@code warmups}, 
{@code iterations},
+ * {@code cache-mib}, and {@code caches} (a comma-separated list) to configure 
the experiment. The
+ * stats-columns property counts string columns in addition to the integer 
partition column.
+ */
+public class PartitionEntryScanBenchmark {
+
+    private static final RowType PARTITION_TYPE = RowType.of(new IntType());
+
+    @TempDir java.nio.file.Path tempDir;
+
+    @Test
+    void compareScanners() throws Exception {
+        int warmups = property("warmups", 2);
+        int iterations = property("iterations", 5);
+        System.out.printf(
+                "PARTITION_SCAN_CONFIG manifests=%d entries=%d partitions=%d 
statsColumns=%d stringColumns=%d "
+                        + "indexBytes=%d parallelism=%d warmups=%d 
iterations=%d cacheMiB=%d%n",
+                property("manifests", 8),
+                property("entries", 2000),
+                property("partitions", 1000),
+                createRowType().getFieldCount(),
+                property("stats-columns", 32),
+                property("index-bytes", 512),
+                property("parallelism", 1),
+                warmups,
+                iterations,
+                property("cache-mib", 512));
+        for (String cache :
+                System.getProperty(
+                                "partition.scan.benchmark.caches",
+                                
"none,whole-cold,whole-warm,blocks-cold,blocks-warm")
+                        .split(",")) {
+            for (boolean deletes : new boolean[] {false, true}) {
+                Fixture fixture = new Fixture(cache, deletes);
+                for (int selectivity : new int[] {100, 10}) {
+                    List<Sample> baseline = new ArrayList<>();
+                    List<Sample> projected = new ArrayList<>();
+                    for (int iteration = -warmups; iteration < iterations; 
iteration++) {
+                        // Alternate execution order to reduce the effect of 
JIT and machine drift.
+                        Sample full;
+                        Sample narrow;
+                        if ((iteration & 1) == 0) {
+                            full = fixture.measure(false, selectivity);
+                            narrow = fixture.measure(true, selectivity);
+                        } else {
+                            narrow = fixture.measure(true, selectivity);
+                            full = fixture.measure(false, selectivity);
+                        }
+                        assertThat(narrow.entries)
+                                
.containsExactlyInAnyOrderElementsOf(full.entries);
+                        if (iteration >= 0) {
+                            baseline.add(full);
+                            projected.add(narrow);
+                        }
+                    }
+                    report(cache, deletes, selectivity, "full", baseline);
+                    report(cache, deletes, selectivity, "projected", 
projected);
+                }
+            }
+        }
+    }
+
+    private class Fixture {
+        private final String cacheMode;
+        private final FileStoreTable table;
+        private final FileSystemSchemaManager schemaManager;
+        private final List<ManifestFileMeta> manifests = new ArrayList<>();
+
+        private Fixture(String cacheMode, boolean deletes) throws Exception {
+            this.cacheMode = cacheMode;
+            Path path = new Path(tempDir.resolve(cacheMode + "-" + 
deletes).toString());
+            Options options = new Options();
+            options.set(CoreOptions.BUCKET, -1);
+            options.set(CoreOptions.MANIFEST_SIDECAR_ENABLED, 
cacheMode.startsWith("blocks"));
+            options.set("manifest.target-file-size", "1GB");
+            LocalFileIO io = LocalFileIO.create();
+            schemaManager = new FileSystemSchemaManager(io, path);
+            RowType rowType = createRowType();
+            TableSchema schema =
+                    schemaManager.createTable(
+                            new Schema(
+                                    rowType.getFields(),
+                                    Collections.singletonList("pt"),
+                                    Collections.emptyList(),
+                                    options.toMap(),
+                                    ""));
+            table =
+                    FileStoreTableFactory.create(
+                            io, path, schema, options, 
CatalogEnvironment.empty());
+            ManifestFile file = table.store().manifestFileFactory().create();
+            List<SimpleStats> partitionStats = new ArrayList<>();
+            for (int partition = 0; partition < property("partitions", 1000); 
partition++) {
+                SimpleStats stats = createStats(rowType, partition);
+                
assertThat(stats.minValues().getFieldCount()).isEqualTo(schema.fields().size());
+                
assertThat(stats.maxValues().getFieldCount()).isEqualTo(schema.fields().size());
+                
assertThat(stats.nullCounts().size()).isEqualTo(schema.fields().size());
+                assertThat(stats.minValues().getInt(0)).isEqualTo(partition);
+                assertThat(stats.maxValues().getInt(0)).isEqualTo(partition);
+                partitionStats.add(stats);
+            }
+            byte[] index = null;
+            if (property("index-bytes", 512) > 0) {
+                index = new byte[property("index-bytes", 512)];
+                new Random(42).nextBytes(index);
+            }
+            for (int manifest = 0; manifest < property("manifests", 8); 
manifest++) {
+                List<ManifestEntry> entries = new ArrayList<>();
+                List<ManifestEntry> deleted = new ArrayList<>();
+                for (int row = 0; row < property("entries", 2000); row++) {
+                    BinaryRow partition =
+                            new InternalRowSerializer(PARTITION_TYPE)
+                                    .toBinaryRow(GenericRow.of(row % 
property("partitions", 1000)));
+                    DataFileMeta data =
+                            DataFileMeta.forAppend(
+                                    "data-" + manifest + "-" + row + 
".parquet",
+                                    131072,
+                                    1000,
+                                    partitionStats.get(partition.getInt(0)),
+                                    0,
+                                    999,
+                                    schema.id(),
+                                    Collections.emptyList(),
+                                    index,
+                                    FileSource.APPEND,
+                                    null,
+                                    null,
+                                    null,
+                                    null);
+                    entries.add(ManifestEntry.create(FileKind.ADD, partition, 
0, -1, data));
+                    if (deletes && row % 4 == 0) {
+                        deleted.add(ManifestEntry.create(FileKind.DELETE, 
partition, 0, -1, data));
+                    }
+                }
+                manifests.addAll(file.write(entries));
+                if (!deleted.isEmpty()) {
+                    manifests.addAll(file.write(deleted));
+                }
+            }
+            System.out.printf(
+                    "PARTITION_SCAN_INPUT cache=%s deletes=%s manifests=%d 
bytes=%d%n",
+                    cacheMode,
+                    deletes,
+                    manifests.size(),
+                    
manifests.stream().mapToLong(ManifestFileMeta::fileSize).sum());
+        }
+
+        private Sample measure(boolean projected, int selectivity) {
+            SegmentsCache<Path> cache =
+                    cacheMode.equals("none")
+                            ? null
+                            : new SegmentsCache<>(
+                                    32768,
+                                    
MemorySize.ofMebiBytes(property("cache-mib", 512)),
+                                    Long.MAX_VALUE,
+                                    null,
+                                    false);
+            table.store().setManifestCache(cache);
+            ManifestFile.Factory factory = table.store().manifestFileFactory();
+            ManifestsReader reader =
+                    new ManifestsReader(
+                            PARTITION_TYPE,
+                            "default",
+                            table.snapshotManager(),
+                            table.store().manifestListFactory()) {
+                        @Override
+                        public Result read(Snapshot snapshot, ScanMode 
scanMode) {
+                            return new Result(null, manifests, manifests);
+                        }
+                    };
+            if (selectivity < 100) {
+                reader.withPartitionFilter(
+                        PartitionPredicate.fromPredicate(
+                                PARTITION_TYPE,
+                                new PredicateBuilder(PARTITION_TYPE)
+                                        .lessThan(
+                                                0,
+                                                property("partitions", 1000) * 
selectivity / 100)));
+            }
+            Supplier<List<PartitionEntry>> action;
+            if (projected) {
+                PartitionEntryScanner scanner =
+                        new PartitionEntryScanner(reader, factory, 
property("parallelism", 1));
+                action = scanner::scan;
+            } else {
+                FileStoreScan scan =
+                        new AbstractFileStoreScan(
+                                reader,
+                                table.snapshotManager(),
+                                schemaManager,
+                                table.schema(),
+                                factory,
+                                property("parallelism", 1)) {
+                            @Override
+                            protected boolean filterByStats(ManifestEntry 
entry) {
+                                return true;
+                            }
+
+                            @Override
+                            public FileStoreScan withCompleteFilter(Predicate 
predicate) {
+                                throw new UnsupportedOperationException();
+                            }
+                        };
+                action = scan::readPartitionEntries;
+            }
+            if (cacheMode.endsWith("warm")) {
+                action.get();
+                if (cacheMode.equals("whole-warm")) {
+                    for (ManifestFileMeta manifest : manifests) {
+                        assertThat(
+                                        cache.getIfPresents(
+                                                new Path(
+                                                        table.location(),
+                                                        "manifest/" + 
manifest.fileName())))
+                                .as("The whole-manifest cache must fit the 
warm working set")
+                                .isNotNull();
+                    }
+                }
+            }
+            Map<Long, Long> before = allocatedBytes();
+            long start = System.nanoTime();
+            List<PartitionEntry> entries = action.get();
+            long elapsed = System.nanoTime() - start;
+            long allocated = 0;
+            for (Map.Entry<Long, Long> allocation : 
allocatedBytes().entrySet()) {
+                allocated +=
+                        Math.max(
+                                0,
+                                allocation.getValue()
+                                        - 
before.getOrDefault(allocation.getKey(), 0L));
+            }
+            return new Sample(elapsed, allocated, entries);
+        }
+    }
+
+    private static RowType createRowType() {
+        int columns = property("stats-columns", 32);
+        DataType[] types = new DataType[columns + 1];
+        String[] names = new String[columns + 1];
+        types[0] = new IntType();
+        names[0] = "pt";
+        for (int column = 0; column < columns; column++) {
+            types[column + 1] = new VarCharType();
+            names[column + 1] = "value_" + column;
+        }
+        return RowType.of(types, names);
+    }
+
+    private static SimpleStats createStats(RowType rowType, int partition) {
+        SimpleColStats[] stats = new SimpleColStats[rowType.getFieldCount()];
+        stats[0] = new SimpleColStats(partition, partition, 0L);
+        for (int column = 1; column < stats.length; column++) {
+            BinaryString value =
+                    BinaryString.fromString(
+                            "stat-column-" + column + 
"-abcdefghijklmnopqrstuvwxyz");
+            stats[column] = new SimpleColStats(value, value, 0L);
+        }
+        return new SimpleStatsConverter(rowType).toBinaryAllMode(stats);
+    }
+
+    private static Map<Long, Long> allocatedBytes() {
+        java.lang.management.ThreadMXBean bean = 
ManagementFactory.getThreadMXBean();
+        if (!(bean instanceof com.sun.management.ThreadMXBean)) {
+            throw new IllegalStateException(
+                    "Thread allocation measurement requires a HotSpot JVM.");
+        }
+        com.sun.management.ThreadMXBean allocationBean = 
(com.sun.management.ThreadMXBean) bean;
+        if (!allocationBean.isThreadAllocatedMemoryEnabled()) {
+            allocationBean.setThreadAllocatedMemoryEnabled(true);
+        }
+        long[] ids = bean.getAllThreadIds();
+        long[] bytes = allocationBean.getThreadAllocatedBytes(ids);
+        Map<Long, Long> result = new HashMap<>();
+        for (int thread = 0; thread < ids.length; thread++) {
+            if (bytes[thread] >= 0) {
+                result.put(ids[thread], bytes[thread]);
+            }
+        }
+        return result;
+    }
+
+    private static void report(
+            String cache,
+            boolean deletes,
+            int selectivity,
+            String implementation,
+            List<Sample> samples) {
+        long[] times = samples.stream().mapToLong(sample -> 
sample.nanos).sorted().toArray();
+        long[] allocations =
+                samples.stream().mapToLong(sample -> 
sample.allocated).sorted().toArray();
+        System.out.printf(
+                "PARTITION_SCAN_RESULT cache=%s deletes=%s selected=%d%% 
implementation=%s "
+                        + "medianMs=%.3f medianMiB=%.3f partitions=%d%n",
+                cache,
+                deletes,
+                selectivity,
+                implementation,
+                times[times.length / 2] / 1000000.0,
+                allocations[allocations.length / 2] / 1048576.0,
+                samples.get(0).entries.size());
+    }
+
+    private static int property(String name, int defaultValue) {
+        return Integer.parseInt(
+                System.getProperty(
+                        "partition.scan.benchmark." + name, 
Integer.toString(defaultValue)));
+    }
+
+    private static class Sample {
+        private final long nanos;
+        private final long allocated;
+        private final List<PartitionEntry> entries;
+
+        private Sample(long nanos, long allocated, List<PartitionEntry> 
entries) {
+            this.nanos = nanos;
+            this.allocated = allocated;
+            this.entries = entries;
+        }
+    }
+}
diff --git a/paimon-core/src/main/java/org/apache/paimon/AbstractFileStore.java 
b/paimon-core/src/main/java/org/apache/paimon/AbstractFileStore.java
index 8663945778..d7ddf258fb 100644
--- a/paimon-core/src/main/java/org/apache/paimon/AbstractFileStore.java
+++ b/paimon-core/src/main/java/org/apache/paimon/AbstractFileStore.java
@@ -33,6 +33,7 @@ import org.apache.paimon.index.IndexFileHandler;
 import org.apache.paimon.manifest.IndexManifestFile;
 import org.apache.paimon.manifest.ManifestFile;
 import org.apache.paimon.manifest.ManifestList;
+import org.apache.paimon.manifest.PartitionEntry;
 import org.apache.paimon.metastore.AddPartitionCommitCallback;
 import org.apache.paimon.metastore.AddPartitionTagCallback;
 import org.apache.paimon.metastore.ChainTableCommitPreCallback;
@@ -42,13 +43,16 @@ import org.apache.paimon.metastore.VisibilityWaitCallback;
 import org.apache.paimon.operation.ChainTablePartitionExpire;
 import org.apache.paimon.operation.ChangelogDeletion;
 import org.apache.paimon.operation.FileStoreCommitImpl;
+import org.apache.paimon.operation.FileStoreScan;
 import org.apache.paimon.operation.ManifestsReader;
 import org.apache.paimon.operation.NormalPartitionExpire;
+import org.apache.paimon.operation.PartitionEntryScanner;
 import org.apache.paimon.operation.PartitionExpire;
 import org.apache.paimon.operation.SnapshotDeletion;
 import org.apache.paimon.operation.commit.CommitRollback;
 import org.apache.paimon.operation.commit.ConflictDetection;
 import org.apache.paimon.partition.PartitionExpireStrategy;
+import org.apache.paimon.partition.PartitionUpdateTimeExpireStrategy;
 import org.apache.paimon.partition.PartitionValuesTimeExpireStrategy;
 import org.apache.paimon.schema.SchemaManager;
 import org.apache.paimon.schema.TableSchema;
@@ -81,10 +85,12 @@ import 
org.apache.paimon.shade.caffeine2.com.github.benmanes.caffeine.cache.Cach
 import javax.annotation.Nullable;
 
 import java.time.Duration;
+import java.time.LocalDateTime;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Comparator;
 import java.util.List;
+import java.util.function.Function;
 
 import static 
org.apache.paimon.partition.PartitionExpireStrategy.createPartitionExpireStrategy;
 import static org.apache.paimon.utils.Preconditions.checkArgument;
@@ -489,11 +495,34 @@ abstract class AbstractFileStore<T> implements 
FileStore<T> {
             partitionModification = catalogEnvironment.partitionModification();
         }
 
+        Function<LocalDateTime, List<PartitionEntry>> partitionSelector;
+        // Custom strategies, including subclasses, retain their FileStoreScan 
contract.
+        if (expireStrategy.getClass() == 
PartitionUpdateTimeExpireStrategy.class
+                || expireStrategy.getClass() == 
PartitionValuesTimeExpireStrategy.class) {
+            PartitionEntryScanner scanner =
+                    new PartitionEntryScanner(
+                            newManifestsReader(),
+                            manifestFileFactory(),
+                            options.scanManifestParallelism());
+            if (expireStrategy instanceof PartitionUpdateTimeExpireStrategy) {
+                PartitionUpdateTimeExpireStrategy updateStrategy =
+                        (PartitionUpdateTimeExpireStrategy) expireStrategy;
+                partitionSelector = time -> 
updateStrategy.selectExpiredPartitions(scanner, time);
+            } else {
+                PartitionValuesTimeExpireStrategy valuesStrategy =
+                        (PartitionValuesTimeExpireStrategy) expireStrategy;
+                partitionSelector = time -> 
valuesStrategy.selectExpiredPartitions(scanner, time);
+            }
+        } else {
+            FileStoreScan scan = newScan();
+            partitionSelector = time -> 
expireStrategy.selectExpiredPartitions(scan, time);
+        }
+
         return new NormalPartitionExpire(
                 expirationTime,
                 checkInterval,
                 expireStrategy,
-                newScan(),
+                partitionSelector,
                 newCommit(commitUser, table),
                 partitionModification,
                 options.endInputCheckPartitionExpire(),
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/manifest/ManifestEntryCache.java 
b/paimon-core/src/main/java/org/apache/paimon/manifest/ManifestEntryCache.java
index ab5b87551e..78703781ea 100644
--- 
a/paimon-core/src/main/java/org/apache/paimon/manifest/ManifestEntryCache.java
+++ 
b/paimon-core/src/main/java/org/apache/paimon/manifest/ManifestEntryCache.java
@@ -49,6 +49,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.Optional;
 import java.util.OptionalInt;
+import java.util.function.Consumer;
 import java.util.function.Function;
 import java.util.function.Supplier;
 import java.util.stream.Collectors;
@@ -219,6 +220,41 @@ public class ManifestEntryCache extends ObjectsCache<Path, 
ManifestEntry, Manife
         return Optional.empty();
     }
 
+    /** Visits binary views of cached entries without constructing data-file 
metadata objects. */
+    public void scan(
+            Path path,
+            long fileSize,
+            @Nullable PartitionPredicate partitionFilter,
+            Consumer<ManifestEntry> consumer)
+            throws IOException {
+        ManifestEntrySegments segments = (ManifestEntrySegments) 
cache.getIfPresents(path);
+        if (segments == null) {
+            if (cacheMetrics != null) {
+                cacheMetrics.increaseMissedObject();
+            }
+            segments = createSegments(path, fileSize);
+            cache.put(path, segments);
+        } else if (cacheMetrics != null) {
+            cacheMetrics.increaseHitObject();
+        }
+        ProjectedManifestEntry entry = 
ProjectedManifestEntry.fullProjection().createEntry();
+        try {
+            for (RichSegments segment : segments.segments()) {
+                if (partitionFilter == null || 
partitionFilter.test(segment.partition())) {
+                    SimpleObjectsCache.forEachRow(
+                            formatSerializer.get(),
+                            segment.segments(),
+                            row -> {
+                                
ManifestEntrySerializer.checkFormatIdentifier(row.getInt(0));
+                                consumer.accept(entry.replace(row));
+                            });
+                }
+            }
+        } finally {
+            entry.clear();
+        }
+    }
+
     private OptionalInt extractSpecifiedBucket(@Nullable BucketFilter filter) {
         if (filter != null) {
             Integer specifiedBucket = filter.specifiedBucket();
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/manifest/ManifestFile.java 
b/paimon-core/src/main/java/org/apache/paimon/manifest/ManifestFile.java
index 608c7dc576..0ae9282585 100644
--- a/paimon-core/src/main/java/org/apache/paimon/manifest/ManifestFile.java
+++ b/paimon-core/src/main/java/org/apache/paimon/manifest/ManifestFile.java
@@ -47,6 +47,7 @@ import java.io.UncheckedIOException;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
+import java.util.function.Consumer;
 import java.util.function.Function;
 import java.util.function.Predicate;
 
@@ -251,6 +252,56 @@ public class ManifestFile extends 
ObjectsFile<ManifestEntry> {
         }
     }
 
+    /**
+     * Visits binary entries using a narrow projection for uncached files and 
cached Avro blocks.
+     * Small manifests reuse the whole-manifest cache. The consumer must not 
retain entries.
+     */
+    public void scan(
+            ManifestFileMeta manifest,
+            Projection projection,
+            @Nullable PartitionPredicate partitionFilter,
+            Consumer<ManifestEntry> consumer) {
+        ManifestSidecar.Selection selected = selectBlocks(manifest, null, 
partitionFilter, null);
+        if (selected != null && selected.blocks().isEmpty()) {
+            return;
+        }
+        if (selected == null
+                && cache != null
+                && manifest.fileSize() <= 
cache.segmentsCache().maxElementSize()) {
+            try {
+                ((ManifestEntryCache) cache)
+                        .scan(
+                                pathFactory.toPath(manifest.fileName()),
+                                manifest.fileSize(),
+                                partitionFilter,
+                                consumer);
+            } catch (IOException e) {
+                throw new UncheckedIOException("Failed to scan manifest " + 
manifest.fileName(), e);
+            }
+            return;
+        }
+
+        ProjectedManifestEntry entry = projection.createEntry();
+        try (CloseableIterator<InternalRow> rows =
+                createManifestIterator(
+                        fileIO,
+                        pathFactory.toPath(manifest.fileName()),
+                        projection.projectedType(),
+                        partitionFilter,
+                        null,
+                        selected,
+                        cache == null ? null : cache.segmentsCache(),
+                        null)) {
+            while (rows.hasNext()) {
+                consumer.accept(entry.replace(rows.next()));
+            }
+        } catch (Exception e) {
+            throw new RuntimeException("Failed to scan manifest " + 
manifest.fileName(), e);
+        } finally {
+            entry.clear();
+        }
+    }
+
     private static CloseableIterator<InternalRow> createManifestIterator(
             FileIO fileIO,
             Path path,
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/operation/NormalPartitionExpire.java
 
b/paimon-core/src/main/java/org/apache/paimon/operation/NormalPartitionExpire.java
index 6abffab58d..1e990d97c9 100644
--- 
a/paimon-core/src/main/java/org/apache/paimon/operation/NormalPartitionExpire.java
+++ 
b/paimon-core/src/main/java/org/apache/paimon/operation/NormalPartitionExpire.java
@@ -42,6 +42,7 @@ import java.util.Comparator;
 import java.util.List;
 import java.util.Map;
 import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Function;
 import java.util.stream.Collectors;
 
 /** Expire partitions. */
@@ -53,7 +54,7 @@ public class NormalPartitionExpire implements PartitionExpire 
{
 
     private final Duration expirationTime;
     private final Duration checkInterval;
-    private final FileStoreScan scan;
+    private final Function<LocalDateTime, List<PartitionEntry>> 
partitionSelector;
     private final FileStoreCommit commit;
     @Nullable private final PartitionModification partitionModification;
     private LocalDateTime lastCheck;
@@ -72,10 +73,32 @@ public class NormalPartitionExpire implements 
PartitionExpire {
             boolean endInputCheckPartitionExpire,
             int maxExpireNum,
             int expireBatchSize) {
+        this(
+                expirationTime,
+                checkInterval,
+                strategy,
+                time -> strategy.selectExpiredPartitions(scan, time),
+                commit,
+                partitionModification,
+                endInputCheckPartitionExpire,
+                maxExpireNum,
+                expireBatchSize);
+    }
+
+    public NormalPartitionExpire(
+            Duration expirationTime,
+            Duration checkInterval,
+            PartitionExpireStrategy strategy,
+            Function<LocalDateTime, List<PartitionEntry>> partitionSelector,
+            FileStoreCommit commit,
+            @Nullable PartitionModification partitionModification,
+            boolean endInputCheckPartitionExpire,
+            int maxExpireNum,
+            int expireBatchSize) {
         this.expirationTime = expirationTime;
         this.checkInterval = checkInterval;
         this.strategy = strategy;
-        this.scan = scan;
+        this.partitionSelector = partitionSelector;
         this.commit = commit;
         this.partitionModification = partitionModification;
         // Avoid the execution time of stream jobs from being too short and 
preventing partition
@@ -155,8 +178,7 @@ public class NormalPartitionExpire implements 
PartitionExpire {
 
     private List<Map<String, String>> doExpire(
             LocalDateTime expireDateTime, long commitIdentifier) {
-        List<PartitionEntry> partitionEntries =
-                strategy.selectExpiredPartitions(scan, expireDateTime);
+        List<PartitionEntry> partitionEntries = 
partitionSelector.apply(expireDateTime);
         List<List<String>> expiredPartValues = new 
ArrayList<>(partitionEntries.size());
         for (PartitionEntry partition : partitionEntries) {
             Object[] array = strategy.convertPartition(partition.partition());
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/operation/PartitionEntryScanner.java
 
b/paimon-core/src/main/java/org/apache/paimon/operation/PartitionEntryScanner.java
new file mode 100644
index 0000000000..15f1b9d627
--- /dev/null
+++ 
b/paimon-core/src/main/java/org/apache/paimon/operation/PartitionEntryScanner.java
@@ -0,0 +1,215 @@
+/*
+ * 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.data.BinaryRow;
+import org.apache.paimon.io.DataFileMeta;
+import org.apache.paimon.manifest.FileEntry.Identifier;
+import org.apache.paimon.manifest.FileKind;
+import org.apache.paimon.manifest.ManifestEntry;
+import org.apache.paimon.manifest.ManifestFile;
+import org.apache.paimon.manifest.ManifestFileMeta;
+import org.apache.paimon.manifest.PartitionEntry;
+import org.apache.paimon.manifest.ProjectedManifestEntry;
+import org.apache.paimon.partition.PartitionPredicate;
+import org.apache.paimon.table.source.ScanMode;
+import org.apache.paimon.types.DataField;
+import org.apache.paimon.types.RowType;
+
+import javax.annotation.Nullable;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+
+import static 
org.apache.paimon.utils.ManifestReadThreadPool.getExecutorService;
+import static org.apache.paimon.utils.ThreadPoolUtils.randomlyOnlyExecute;
+
+/**
+ * Reads partition statistics directly from a snapshot's data manifests.
+ *
+ * <p>This scanner has no data, level or bucket filters. It is intended for 
partition maintenance,
+ * which needs all active files independently of the table's data scan 
configuration.
+ */
+public final class PartitionEntryScanner {
+
+    private static final ProjectedManifestEntry.Projection 
PARTITION_PROJECTION =
+            createProjection(false);
+    private static final ProjectedManifestEntry.Projection 
PARTITION_WITH_IDENTITY_PROJECTION =
+            createProjection(true);
+
+    private final ManifestFile.Factory manifestFileFactory;
+    private final ManifestsReader manifestsReader;
+    @Nullable private final Integer parallelism;
+
+    public PartitionEntryScanner(
+            ManifestsReader manifestsReader,
+            ManifestFile.Factory manifestFileFactory,
+            @Nullable Integer parallelism) {
+        this.manifestsReader = manifestsReader;
+        this.manifestFileFactory = manifestFileFactory;
+        this.parallelism = parallelism;
+    }
+
+    public PartitionEntryScanner withPartitionFilter(@Nullable 
PartitionPredicate filter) {
+        manifestsReader.withPartitionFilter(filter);
+        return this;
+    }
+
+    public List<PartitionEntry> scan() {
+        return scan(manifestsReader.read(null, 
ScanMode.ALL).filteredManifests);
+    }
+
+    public List<PartitionEntry> scan(List<ManifestFileMeta> manifests) {
+        Set<Identifier> deletedEntries = ConcurrentHashMap.newKeySet();
+        randomlyOnlyExecute(
+                getExecutorService(parallelism),
+                manifest ->
+                        readManifest(
+                                manifest,
+                                ProjectedManifestEntry.DELETE_ENTRY_PROJECTION,
+                                entry -> {
+                                    if (entry.kind() == FileKind.DELETE) {
+                                        deletedEntries.add(entry.identifier());
+                                    }
+                                }),
+                manifests.stream()
+                        .filter(manifest -> manifest.numDeletedFiles() > 0)
+                        .collect(Collectors.toList()));
+
+        ProjectedManifestEntry.Projection projection =
+                deletedEntries.isEmpty()
+                        ? PARTITION_PROJECTION
+                        : PARTITION_WITH_IDENTITY_PROJECTION;
+        Map<BinaryRow, PartitionStats> partitions = new ConcurrentHashMap<>();
+        randomlyOnlyExecute(
+                getExecutorService(parallelism),
+                manifest -> {
+                    Map<BinaryRow, PartitionStats> local = new HashMap<>();
+                    readManifest(
+                            manifest,
+                            projection,
+                            entry -> {
+                                if (entry.kind() != FileKind.ADD
+                                        || (!deletedEntries.isEmpty()
+                                                && 
deletedEntries.contains(entry.identifier()))) {
+                                    return;
+                                }
+                                BinaryRow partition = entry.partition();
+                                local.computeIfAbsent(partition, key -> new 
PartitionStats())
+                                        .add(entry);
+                            });
+                    local.forEach(
+                            (partition, stats) ->
+                                    partitions.compute(
+                                            partition,
+                                            (key, previous) ->
+                                                    previous == null
+                                                            ? stats
+                                                            : 
previous.merge(stats)));
+                },
+                manifests.stream()
+                        .filter(manifest -> manifest.numAddedFiles() > 0)
+                        .collect(Collectors.toList()));
+        return partitions.entrySet().stream()
+                .map(entry -> entry.getValue().toEntry(entry.getKey()))
+                .collect(Collectors.toList());
+    }
+
+    private void readManifest(
+            ManifestFileMeta manifest,
+            ProjectedManifestEntry.Projection projection,
+            Consumer<ManifestEntry> consumer) {
+        manifestFileFactory
+                .create()
+                .scan(manifest, projection, manifestsReader.partitionFilter(), 
consumer);
+    }
+
+    private static ProjectedManifestEntry.Projection createProjection(boolean 
withIdentity) {
+        RowType fileType =
+                withIdentity
+                        ? DataFileMeta.SCHEMA.project(
+                                DataFileMeta.FILE_NAME,
+                                DataFileMeta.FILE_SIZE,
+                                DataFileMeta.ROW_COUNT,
+                                DataFileMeta.LEVEL,
+                                DataFileMeta.CREATION_TIME,
+                                DataFileMeta.EXTRA_FILES,
+                                DataFileMeta.EMBEDDED_FILE_INDEX,
+                                DataFileMeta.EXTERNAL_PATH)
+                        : DataFileMeta.SCHEMA.project(
+                                DataFileMeta.FILE_SIZE,
+                                DataFileMeta.ROW_COUNT,
+                                DataFileMeta.CREATION_TIME);
+        RowType manifestType = ManifestEntry.MANIFEST_ROW_TYPE;
+        List<DataField> fields =
+                new ArrayList<>(
+                        Arrays.asList(
+                                manifestType.getField(ManifestEntry.KIND),
+                                manifestType.getField(ManifestEntry.PARTITION),
+                                
manifestType.getField(ManifestEntry.TOTAL_BUCKETS),
+                                
manifestType.getField(ManifestEntry.FILE).newType(fileType)));
+        if (withIdentity) {
+            fields.add(manifestType.getField(ManifestEntry.BUCKET));
+        }
+        return ProjectedManifestEntry.Projection.create(new RowType(false, 
fields));
+    }
+
+    private static class PartitionStats {
+        private long recordCount;
+        private long fileSize;
+        private long fileCount;
+        private long lastFileCreationTime = Long.MIN_VALUE;
+        private int totalBuckets;
+
+        private void add(ManifestEntry entry) {
+            DataFileMeta file = entry.file();
+            recordCount += file.rowCount();
+            fileSize += file.fileSize();
+            fileCount++;
+            lastFileCreationTime = Math.max(lastFileCreationTime, 
file.creationTimeEpochMillis());
+            totalBuckets = entry.totalBuckets();
+        }
+
+        private PartitionStats merge(PartitionStats other) {
+            recordCount += other.recordCount;
+            fileSize += other.fileSize;
+            fileCount += other.fileCount;
+            lastFileCreationTime = Math.max(lastFileCreationTime, 
other.lastFileCreationTime);
+            totalBuckets = other.totalBuckets;
+            return this;
+        }
+
+        private PartitionEntry toEntry(BinaryRow partition) {
+            return new PartitionEntry(
+                    partition,
+                    recordCount,
+                    fileSize,
+                    fileCount,
+                    lastFileCreationTime,
+                    totalBuckets);
+        }
+    }
+}
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/partition/PartitionUpdateTimeExpireStrategy.java
 
b/paimon-core/src/main/java/org/apache/paimon/partition/PartitionUpdateTimeExpireStrategy.java
index 6c41d90055..6c7b47ae41 100644
--- 
a/paimon-core/src/main/java/org/apache/paimon/partition/PartitionUpdateTimeExpireStrategy.java
+++ 
b/paimon-core/src/main/java/org/apache/paimon/partition/PartitionUpdateTimeExpireStrategy.java
@@ -21,6 +21,7 @@ package org.apache.paimon.partition;
 import org.apache.paimon.CoreOptions;
 import org.apache.paimon.manifest.PartitionEntry;
 import org.apache.paimon.operation.FileStoreScan;
+import org.apache.paimon.operation.PartitionEntryScanner;
 import org.apache.paimon.types.RowType;
 
 import java.time.LocalDateTime;
@@ -47,7 +48,16 @@ public class PartitionUpdateTimeExpireStrategy extends 
PartitionExpireStrategy {
     @Override
     public List<PartitionEntry> selectExpiredPartitions(
             FileStoreScan scan, LocalDateTime expirationTime) {
-        List<PartitionEntry> partitions = scan.readPartitionEntries();
+        return selectExpiredPartitions(scan.readPartitionEntries(), 
expirationTime);
+    }
+
+    public List<PartitionEntry> selectExpiredPartitions(
+            PartitionEntryScanner scan, LocalDateTime expirationTime) {
+        return selectExpiredPartitions(scan.scan(), expirationTime);
+    }
+
+    private List<PartitionEntry> selectExpiredPartitions(
+            List<PartitionEntry> partitions, LocalDateTime expirationTime) {
         long expirationMilli =
                 
expirationTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
         List<PartitionEntry> expired =
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/partition/PartitionValuesTimeExpireStrategy.java
 
b/paimon-core/src/main/java/org/apache/paimon/partition/PartitionValuesTimeExpireStrategy.java
index 0291bcc6c9..6f1ce78cd2 100644
--- 
a/paimon-core/src/main/java/org/apache/paimon/partition/PartitionValuesTimeExpireStrategy.java
+++ 
b/paimon-core/src/main/java/org/apache/paimon/partition/PartitionValuesTimeExpireStrategy.java
@@ -24,6 +24,7 @@ import org.apache.paimon.data.InternalArray;
 import org.apache.paimon.data.InternalRow;
 import org.apache.paimon.manifest.PartitionEntry;
 import org.apache.paimon.operation.FileStoreScan;
+import org.apache.paimon.operation.PartitionEntryScanner;
 import org.apache.paimon.types.RowType;
 
 import org.slf4j.Logger;
@@ -71,6 +72,20 @@ public class PartitionValuesTimeExpireStrategy extends 
PartitionExpireStrategy {
         }
 
         List<PartitionEntry> partitions = scan.readPartitionEntries();
+        return selectExpiredPartitions(partitions, predicate);
+    }
+
+    public List<PartitionEntry> selectExpiredPartitions(
+            PartitionEntryScanner scan, LocalDateTime expirationTime) {
+        PartitionValuesTimePredicate predicate = new 
PartitionValuesTimePredicate(expirationTime);
+        if (!retainLatest) {
+            return scan.withPartitionFilter(predicate).scan();
+        }
+        return selectExpiredPartitions(scan.scan(), predicate);
+    }
+
+    private List<PartitionEntry> selectExpiredPartitions(
+            List<PartitionEntry> partitions, PartitionValuesTimePredicate 
predicate) {
         List<PartitionEntry> expired =
                 partitions.stream()
                         .filter(entry -> predicate.test(entry.partition()))
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/utils/SimpleObjectsCache.java 
b/paimon-core/src/main/java/org/apache/paimon/utils/SimpleObjectsCache.java
index 727f30c396..cf0d5e803a 100644
--- a/paimon-core/src/main/java/org/apache/paimon/utils/SimpleObjectsCache.java
+++ b/paimon-core/src/main/java/org/apache/paimon/utils/SimpleObjectsCache.java
@@ -37,6 +37,7 @@ import java.io.EOFException;
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.function.Consumer;
 import java.util.function.Function;
 
 /** Cache records to {@link SegmentsCache} by compacted serializer. */
@@ -92,22 +93,37 @@ public class SimpleObjectsCache<K, V> extends 
ObjectsCache<K, V, Segments> {
             Function<V, R> convertor)
             throws IOException {
         List<R> entries = new ArrayList<>();
-        RandomAccessInputView view = createInputView(segments);
-        BinaryRow binaryRow = new BinaryRow(formatSerializer.getArity());
         Filter<InternalRow> readFilter = filters.readFilter();
         Filter<V> readVFilter = filters.readVFilter();
+        forEachRow(
+                formatSerializer,
+                segments,
+                row -> {
+                    if (readFilter.test(row)) {
+                        V value = projectedSerializer.fromRow(row);
+                        if (readVFilter.test(value)) {
+                            entries.add(convertor.apply(value));
+                        }
+                    }
+                });
+        return entries;
+    }
+
+    /** Visits reusable binary rows backed by cached segments. The consumer 
must not retain rows. */
+    public static void forEachRow(
+            InternalRowSerializer formatSerializer,
+            Segments segments,
+            Consumer<InternalRow> consumer)
+            throws IOException {
+        RandomAccessInputView view = createInputView(segments);
+        BinaryRow binaryRow = new BinaryRow(formatSerializer.getArity());
         while (true) {
             try {
                 formatSerializer.mapFromPages(binaryRow, view);
-                if (readFilter.test(binaryRow)) {
-                    V v = projectedSerializer.fromRow(binaryRow);
-                    if (readVFilter.test(v)) {
-                        entries.add(convertor.apply(v));
-                    }
-                }
             } catch (EOFException e) {
-                return entries;
+                return;
             }
+            consumer.accept(binaryRow);
         }
     }
 
diff --git 
a/paimon-core/src/test/java/org/apache/paimon/operation/PartitionEntryScannerTest.java
 
b/paimon-core/src/test/java/org/apache/paimon/operation/PartitionEntryScannerTest.java
new file mode 100644
index 0000000000..4b0efa4053
--- /dev/null
+++ 
b/paimon-core/src/test/java/org/apache/paimon/operation/PartitionEntryScannerTest.java
@@ -0,0 +1,376 @@
+/*
+ * 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.data.GenericRow;
+import org.apache.paimon.data.Timestamp;
+import org.apache.paimon.fs.Path;
+import org.apache.paimon.io.DataFileMeta;
+import org.apache.paimon.io.DataFileMetaSerializer;
+import org.apache.paimon.manifest.FileKind;
+import org.apache.paimon.manifest.ManifestEntry;
+import org.apache.paimon.manifest.ManifestFile;
+import org.apache.paimon.manifest.ManifestFileMeta;
+import org.apache.paimon.manifest.PartitionEntry;
+import org.apache.paimon.options.MemorySize;
+import org.apache.paimon.options.Options;
+import org.apache.paimon.partition.PartitionExpireStrategy;
+import org.apache.paimon.partition.PartitionPredicate;
+import org.apache.paimon.partition.PartitionUpdateTimeExpireStrategy;
+import org.apache.paimon.partition.PartitionValuesTimeExpireStrategy;
+import org.apache.paimon.predicate.PredicateBuilder;
+import org.apache.paimon.table.sink.BatchTableCommit;
+import org.apache.paimon.table.sink.BatchTableWrite;
+import org.apache.paimon.table.sink.BatchWriteBuilder;
+import org.apache.paimon.table.sink.CommitMessage;
+import org.apache.paimon.table.sink.CommitMessageImpl;
+import org.apache.paimon.table.sink.PostponeFixedBucketWriteBuilder;
+import org.apache.paimon.table.sink.TableCommitImpl;
+import org.apache.paimon.table.sink.TableWriteImpl;
+import org.apache.paimon.table.source.ScanMode;
+import org.apache.paimon.table.source.snapshot.ScannerTestBase;
+import org.apache.paimon.types.RowType;
+import org.apache.paimon.utils.SegmentsCache;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.time.Duration;
+import java.time.LocalDateTime;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/** Tests for the independent partition maintenance scanner. */
+public class PartitionEntryScannerTest extends ScannerTestBase {
+
+    @ParameterizedTest
+    @CsvSource({
+        "primary,false",
+        "primary,true",
+        "append,false",
+        "append,true",
+        "evolution,false",
+        "evolution,true"
+    })
+    void testMatchesFullScan(String mode, boolean sidecar) throws Exception {
+        Options options = new Options();
+        options.set(CoreOptions.MANIFEST_SIDECAR_ENABLED, sidecar);
+        if (mode.equals("evolution")) {
+            options.set(CoreOptions.DATA_EVOLUTION_ENABLED, true);
+            options.set(CoreOptions.ROW_TRACKING_ENABLED, true);
+            options.set(CoreOptions.BUCKET, -1);
+        }
+        tablePath = new Path(tablePath, "scanner");
+        table = createFileStoreTable(mode.equals("primary"), options, 
tablePath);
+        for (int commit = 0; commit < 3; commit++) {
+            writeRows(commit * 10);
+        }
+        assertMatchesFullScan(manifests());
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"update-time", "values-time"})
+    void testDataEvolutionPartialUpdateAndExpiration(String 
expirationStrategy) throws Exception {
+        Options options = new Options();
+        options.set(CoreOptions.DATA_EVOLUTION_ENABLED, true);
+        options.set(CoreOptions.ROW_TRACKING_ENABLED, true);
+        options.set(CoreOptions.BUCKET, -1);
+        options.set(CoreOptions.PARTITION_TIMESTAMP_PATTERN, "$pt");
+        options.set(CoreOptions.PARTITION_TIMESTAMP_FORMATTER, "yyyyMMdd");
+        tablePath = new Path(tablePath, "partial-update");
+        table = createFileStoreTable(false, options, tablePath);
+        LocalDateTime initialTime = LocalDateTime.of(2023, 1, 1, 0, 0);
+        int expiredPartition = 20230101;
+        int updatedPartition = 20230103;
+
+        BatchWriteBuilder builder = table.newBatchWriteBuilder();
+        try (BatchTableWrite write = builder.newWrite();
+                BatchTableCommit commit = builder.newCommit()) {
+            for (int partition : new int[] {expiredPartition, 
updatedPartition}) {
+                write.write(GenericRow.of(partition, 1, 10L));
+                write.write(GenericRow.of(partition, 2, 20L));
+            }
+            List<CommitMessage> messages = write.prepareCommit();
+            setCreationTime(messages, initialTime);
+            commit.commit(messages);
+        }
+        ManifestEntry original =
+                table.store().newScan().plan().files().stream()
+                        .filter(entry -> entry.partition().getInt(0) == 
updatedPartition)
+                        .findFirst()
+                        .get();
+        long previousSequence = original.file().maxSequenceNumber();
+        RowType writeType = table.rowType().project(Arrays.asList("pt", "b"));
+        for (int version = 1; version <= 2; version++) {
+            builder = table.newBatchWriteBuilder();
+            try (BatchTableWrite write = 
builder.newWrite().withWriteType(writeType);
+                    BatchTableCommit commit = builder.newCommit()) {
+                write.write(GenericRow.of(updatedPartition, version * 100L));
+                write.write(GenericRow.of(updatedPartition, version * 100L + 
1));
+                List<CommitMessage> messages = write.prepareCommit();
+                for (CommitMessage message : messages) {
+                    ((CommitMessageImpl) message)
+                            .newFilesIncrement()
+                            .newFiles()
+                            .replaceAll(
+                                    file -> 
file.assignFirstRowId(original.file().firstRowId()));
+                }
+                setCreationTime(messages, initialTime.plusDays(version));
+                commit.commit(messages);
+            }
+
+            List<ManifestEntry> files = table.store().newScan().plan().files();
+            
assertThat(files).extracting(ManifestEntry::fileName).contains(original.fileName());
+            DataFileMeta latest =
+                    files.stream()
+                            .filter(entry -> entry.partition().getInt(0) == 
updatedPartition)
+                            .map(ManifestEntry::file)
+                            
.max(Comparator.comparingLong(DataFileMeta::maxSequenceNumber))
+                            .get();
+            assertThat(latest.writeCols()).contains("b").doesNotContain("a");
+            
assertThat(latest.firstRowId()).isEqualTo(original.file().firstRowId());
+            
assertThat(latest.rowCount()).isEqualTo(original.file().rowCount());
+            
assertThat(latest.maxSequenceNumber()).isGreaterThan(previousSequence);
+            previousSequence = latest.maxSequenceNumber();
+            assertMatchesFullScan(manifests());
+        }
+
+        PartitionExpireStrategy strategy =
+                expirationStrategy.equals("update-time")
+                        ? new PartitionUpdateTimeExpireStrategy(
+                                table.coreOptions(), 
table.schema().logicalPartitionType())
+                        : new PartitionValuesTimeExpireStrategy(
+                                table.coreOptions(), 
table.schema().logicalPartitionType());
+        LocalDateTime cutoff = initialTime.plusDays(1).plusHours(12);
+        List<PartitionEntry> expected =
+                strategy.selectExpiredPartitions(table.store().newScan(), 
cutoff);
+        assertThat(expected)
+                .extracting(entry -> entry.partition().getInt(0))
+                .containsExactly(expiredPartition);
+        NormalPartitionExpire expire =
+                (NormalPartitionExpire)
+                        table.store()
+                                .newPartitionExpire(
+                                        commitUser,
+                                        table,
+                                        Duration.ofDays(1),
+                                        Duration.ZERO,
+                                        strategy);
+        assertThat(expire.expire(cutoff.plusDays(1), Long.MAX_VALUE))
+                .containsExactly(Collections.singletonMap("pt", 
String.valueOf(expiredPartition)));
+        assertMatchesFullScan(manifests());
+        assertThat(getResult(table.newRead(), table.newScan().plan().splits()))
+                .containsExactlyInAnyOrder("+I 20230103|1|200", "+I 
20230103|2|201");
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void testDeletedBucketLayout(boolean sidecar) throws Exception {
+        Options options = new Options();
+        options.set(CoreOptions.BUCKET, -2);
+        options.set(CoreOptions.MANIFEST_SIDECAR_ENABLED, sidecar);
+        tablePath = new Path(tablePath, "scanner");
+        table = createFileStoreTable(true, options, tablePath);
+        PostponeFixedBucketWriteBuilder builder = 
table.newPostponeFixedBucketWriteBuilder();
+        try (TableWriteImpl<?> write = builder.newWrite();
+                BatchTableCommit commit = builder.newCommit()) {
+            write.writeAndReturn(rowData(1, 1, 1L), 0, 4);
+            commit.commit(write.prepareCommit());
+        }
+        builder = 
table.newPostponeFixedBucketWriteBuilder().withOverwrite(Collections.emptyMap());
+        try (TableWriteImpl<?> write = builder.newWrite();
+                BatchTableCommit commit = builder.newCommit()) {
+            write.writeAndReturn(rowData(1, 2, 2L), 0, 2);
+            commit.commit(write.prepareCommit());
+        }
+        List<ManifestFileMeta> manifests = manifests();
+        
assertThat(manifests.stream().mapToLong(ManifestFileMeta::numDeletedFiles).sum())
+                .isPositive();
+        assertMatchesFullScan(manifests);
+        assertThat(scanner().scan(manifests))
+                .singleElement()
+                .satisfies(entry -> 
assertThat(entry.totalBuckets()).isEqualTo(2));
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void testDeletionMatchesCompleteFileIdentity(boolean externalPath) throws 
Exception {
+        writeRows(0);
+        ManifestEntry source = table.store().newScan().plan().files().get(0);
+        ManifestEntry old =
+                ManifestEntry.create(
+                        FileKind.ADD,
+                        source.partition(),
+                        0,
+                        4,
+                        externalPath
+                                ? source.file().newExternalPath("file:/old")
+                                : source.file().copy(new byte[] {1}));
+        ManifestEntry current =
+                ManifestEntry.create(
+                        FileKind.ADD,
+                        source.partition(),
+                        0,
+                        2,
+                        externalPath
+                                ? 
source.file().newExternalPath("file:/current")
+                                : source.file().copy(new byte[] {2}));
+        ManifestEntry deleted =
+                ManifestEntry.create(FileKind.DELETE, old.partition(), 0, 4, 
old.file());
+        ManifestFile file = table.store().manifestFileFactory().create();
+        List<ManifestFileMeta> manifests = file.write(Arrays.asList(old, 
current, deleted));
+        assertThat(scanner().scan(manifests))
+                .containsExactly(PartitionEntry.fromManifestEntry(current));
+        assertThat(scanner().scan(file.write(Arrays.asList(old, 
deleted)))).isEmpty();
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void testReusesWholeManifestAndBlockCaches(boolean sidecar) throws 
Exception {
+        Options options = new Options();
+        options.set(CoreOptions.MANIFEST_SIDECAR_ENABLED, sidecar);
+        tablePath = new Path(tablePath, "scanner");
+        table = createFileStoreTable(true, options, tablePath);
+        table.store()
+                .setManifestCache(
+                        new SegmentsCache<>(1024, MemorySize.ofMebiBytes(16), 
Long.MAX_VALUE));
+        writeRows(0);
+        List<ManifestFileMeta> manifests = manifests();
+        List<PartitionEntry> expected = scanner().scan(manifests);
+        assertThat(expected).hasSize(3);
+        for (ManifestFileMeta manifest : manifests) {
+            fileIO.delete(new Path(tablePath, "manifest/" + 
manifest.fileName()), false);
+        }
+        
assertThat(scanner().scan(manifests)).containsExactlyInAnyOrderElementsOf(expected);
+    }
+
+    @Test
+    void testEmptyScan() {
+        assertThat(scanner().scan(Collections.emptyList())).isEmpty();
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"none", "whole", "blocks"})
+    void testPartitionFilter(String cacheMode) throws Exception {
+        Options options = new Options();
+        options.set(CoreOptions.MANIFEST_SIDECAR_ENABLED, 
cacheMode.equals("blocks"));
+        tablePath = new Path(tablePath, "scanner");
+        table = createFileStoreTable(true, options, tablePath);
+        if (!cacheMode.equals("none")) {
+            table.store()
+                    .setManifestCache(
+                            new SegmentsCache<>(1024, 
MemorySize.ofMebiBytes(16), Long.MAX_VALUE));
+        }
+        writeRows(0);
+        writeRows(10);
+        PartitionPredicate filter =
+                PartitionPredicate.fromPredicate(
+                        table.schema().logicalPartitionType(),
+                        new 
PredicateBuilder(table.schema().logicalPartitionType()).equal(0, 2));
+        PartitionEntryScanner scanner = scanner().withPartitionFilter(filter);
+        List<PartitionEntry> expected =
+                
table.store().newScan().withPartitionFilter(filter).readPartitionEntries();
+        assertThat(scanner.scan()).containsExactlyElementsOf(expected);
+        assertThat(scanner.scan())
+                .singleElement()
+                .satisfies(entry -> 
assertThat(entry.partition().getInt(0)).isEqualTo(2));
+        assertThat(scanner.withPartitionFilter(null).scan()).hasSize(3);
+    }
+
+    @Test
+    void testCustomStrategyRetainsScanContract() throws Exception {
+        writeRows(0);
+        AtomicInteger calls = new AtomicInteger();
+        PartitionUpdateTimeExpireStrategy custom =
+                new PartitionUpdateTimeExpireStrategy(
+                        table.coreOptions(), 
table.schema().logicalPartitionType()) {
+                    @Override
+                    public List<PartitionEntry> selectExpiredPartitions(
+                            FileStoreScan scan, LocalDateTime expirationTime) {
+                        assertThat(scan.readPartitionEntries()).hasSize(3);
+                        calls.incrementAndGet();
+                        return Collections.emptyList();
+                    }
+                };
+        assertThat(
+                        table.store()
+                                .newPartitionExpire(
+                                        commitUser,
+                                        table,
+                                        Duration.ofDays(1),
+                                        Duration.ZERO,
+                                        custom)
+                                .expire(1))
+                .isEmpty();
+        assertThat(calls).hasValue(1);
+    }
+
+    private void writeRows(int start) throws Exception {
+        try (BatchTableWrite write = table.newWrite(commitUser);
+                TableCommitImpl commit = table.newCommit(commitUser)) {
+            for (int partition = 1; partition <= 3; partition++) {
+                for (int row = start; row < start + 10; row++) {
+                    write.write(GenericRow.of(partition, row, (long) row));
+                }
+            }
+            commit.commit(write.prepareCommit());
+        }
+    }
+
+    private void setCreationTime(List<CommitMessage> messages, LocalDateTime 
creationTime) {
+        DataFileMetaSerializer serializer = new DataFileMetaSerializer();
+        for (CommitMessage message : messages) {
+            ((CommitMessageImpl) message)
+                    .newFilesIncrement()
+                    .newFiles()
+                    .replaceAll(
+                            file -> {
+                                GenericRow row = (GenericRow) 
serializer.toRow(file);
+                                row.setField(
+                                        DataFileMeta.SCHEMA.getFieldIndex(
+                                                DataFileMeta.CREATION_TIME),
+                                        
Timestamp.fromLocalDateTime(creationTime));
+                                return serializer.fromRow(row);
+                            });
+        }
+    }
+
+    private List<ManifestFileMeta> manifests() {
+        return table.store().newScan().manifestsReader().read(null, 
ScanMode.ALL).filteredManifests;
+    }
+
+    private PartitionEntryScanner scanner() {
+        return new PartitionEntryScanner(
+                table.store().newScan().manifestsReader(), 
table.store().manifestFileFactory(), 2);
+    }
+
+    private void assertMatchesFullScan(List<ManifestFileMeta> manifests) {
+        assertThat(scanner().scan(manifests))
+                .containsExactlyInAnyOrderElementsOf(
+                        table.store().newScan().readPartitionEntries());
+    }
+}

Reply via email to