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

yiguolei pushed a commit to branch branch-4.2
in repository https://gitbox.apache.org/repos/asf/doris.git


The following commit(s) were added to refs/heads/branch-4.2 by this push:
     new 83a4669022e branch-4.2: [opt](iceberg) Decouple bounded manifest 
loading from parsed caching (70410) (#70860)
83a4669022e is described below

commit 83a4669022e5a5ae10bff16e09a57c9d41eae06d
Author: 924060929 <[email protected]>
AuthorDate: Fri Nov 27 15:27:34 2026 +0800

    branch-4.2: [opt](iceberg) Decouple bounded manifest loading from parsed 
caching (70410) (#70860)
    
    cherry pick from #70410
---
 fe/check/checkstyle/suppressions.xml               |   2 +
 .../iceberg/IcebergExternalMetaCache.java          |  10 +-
 .../iceberg/cache/IcebergManifestLoader.java       | 241 ++++++++++
 .../iceberg/cache/IcebergScanFileIO.java           | 189 ++++++++
 .../iceberg/cache/ManifestCacheValue.java          |  14 +-
 .../datasource/iceberg/source/IcebergScanNode.java | 272 +++++++++--
 .../java/org/apache/iceberg/DeleteFileIndex.java   |   2 +-
 .../org/apache/iceberg/DorisDataTableScan.java     |  74 +++
 .../org/apache/iceberg/ManifestReaderAccess.java   |  56 +++
 .../IcebergUncachedManifestPlanningTest.java       | 525 +++++++++++++++++++++
 10 files changed, 1331 insertions(+), 54 deletions(-)

diff --git a/fe/check/checkstyle/suppressions.xml 
b/fe/check/checkstyle/suppressions.xml
index e38650d8919..e8c89d245a5 100644
--- a/fe/check/checkstyle/suppressions.xml
+++ b/fe/check/checkstyle/suppressions.xml
@@ -71,6 +71,8 @@ under the License.
 
     <!-- The scan adapter needs Iceberg package access to preserve the 
original scan context. -->
     <suppress files="org[\\/]apache[\\/]iceberg[\\/]DorisDataTableScan\.java" 
checks="ImportControl"/>
+    <!-- Access package-private live manifest entries; all other style checks 
remain enabled. -->
+    <suppress 
files="org[\\/]apache[\\/]iceberg[\\/]ManifestReaderAccess\.java" 
checks="ImportControl"/>
     <!-- ignore iceberg delete file index copied from 
iceberg/DeleteFileIndex.java -->
     <suppress files="org[\\/]apache[\\/]iceberg[\\/]DeleteFileIndex\.java" 
checks="[a-zA-Z0-9]*"/>
 
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergExternalMetaCache.java
 
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergExternalMetaCache.java
index 40241b8f04f..5d4a43036a8 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergExternalMetaCache.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergExternalMetaCache.java
@@ -28,6 +28,7 @@ import org.apache.doris.datasource.NameMapping;
 import org.apache.doris.datasource.SchemaCacheValue;
 import org.apache.doris.datasource.SessionContext;
 import org.apache.doris.datasource.hive.HMSExternalCatalog;
+import org.apache.doris.datasource.iceberg.cache.IcebergManifestLoader;
 import org.apache.doris.datasource.iceberg.cache.ManifestCacheValue;
 import org.apache.doris.datasource.metacache.AbstractExternalMetaCache;
 import org.apache.doris.datasource.metacache.CacheSpec;
@@ -47,6 +48,7 @@ import org.apache.commons.lang3.exception.ExceptionUtils;
 import org.apache.iceberg.ManifestContent;
 import org.apache.iceberg.ManifestFiles;
 import org.apache.iceberg.ManifestReader;
+import org.apache.iceberg.PartitionSpec;
 import org.apache.iceberg.Schema;
 import org.apache.iceberg.Snapshot;
 import org.apache.iceberg.Table;
@@ -1362,7 +1364,10 @@ public class IcebergExternalMetaCache extends 
AbstractExternalMetaCache {
             org.apache.iceberg.ManifestFile manifest, Table table, boolean 
accountRetainedSize)
             throws IOException {
         ManifestCacheValue.Builder builder = 
ManifestCacheValue.dataFilesBuilder(accountRetainedSize);
-        try (ManifestReader<org.apache.iceberg.DataFile> reader = 
ManifestFiles.read(manifest, table.io())) {
+        Map<Integer, PartitionSpec> specs = 
IcebergManifestLoader.manifestReadSpecs(manifest, table, table.io());
+        try (ManifestReader<org.apache.iceberg.DataFile> reader = specs == null
+                ? ManifestFiles.read(manifest, table.io())
+                : ManifestFiles.read(manifest, table.io(), specs)) {
             for (org.apache.iceberg.DataFile dataFile : reader) {
                 builder.addDataFile(dataFile.copy());
             }
@@ -1376,8 +1381,9 @@ public class IcebergExternalMetaCache extends 
AbstractExternalMetaCache {
         ManifestCacheValue.Builder builder = 
ManifestCacheValue.deleteFilesBuilder(accountRetainedSize);
         // Cache the manifest's physical partition types, just as 
loadDataFiles does. Current table
         // specs may promote a DATE to nanos or erase a dropped field before 
query-local adaptation.
+        Map<Integer, PartitionSpec> specs = 
IcebergManifestLoader.manifestReadSpecs(manifest, table, table.io());
         try (ManifestReader<org.apache.iceberg.DeleteFile> reader = 
ManifestFiles.readDeleteManifest(manifest,
-                table.io(), null)) {
+                table.io(), specs)) {
             for (org.apache.iceberg.DeleteFile deleteFile : reader) {
                 builder.addDeleteFile(deleteFile.copy());
             }
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/cache/IcebergManifestLoader.java
 
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/cache/IcebergManifestLoader.java
new file mode 100644
index 00000000000..ca5ae912dd7
--- /dev/null
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/cache/IcebergManifestLoader.java
@@ -0,0 +1,241 @@
+// 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.doris.datasource.iceberg.cache;
+
+import org.apache.iceberg.ContentFile;
+import org.apache.iceberg.DataFile;
+import org.apache.iceberg.DeleteFile;
+import org.apache.iceberg.FileContent;
+import org.apache.iceberg.ManifestContent;
+import org.apache.iceberg.ManifestFile;
+import org.apache.iceberg.ManifestFiles;
+import org.apache.iceberg.ManifestReader;
+import org.apache.iceberg.ManifestReaderAccess;
+import org.apache.iceberg.MetadataColumns;
+import org.apache.iceberg.PartitionData;
+import org.apache.iceberg.PartitionField;
+import org.apache.iceberg.PartitionSpec;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.Snapshot;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.types.Type;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.ContentFileUtil;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.function.Predicate;
+import java.util.function.UnaryOperator;
+
+/** Reads immutable manifest contents independently of whether the result is 
retained in a cache. */
+public final class IcebergManifestLoader {
+    /** One manifest's request-local predicate and partition adapter, confined 
to its loading worker. */
+    public static final class ReadFilter {
+        private final Types.StructType partitionType;
+        private final Predicate<ContentFile<?>> predicate;
+        private final Runnable skipped;
+        private boolean partitionTypeChecked;
+        private IcebergPartitionValueAdapter adapter;
+
+        public ReadFilter(PartitionSpec spec, Predicate<ContentFile<?>> 
predicate, Runnable skipped) {
+            this.partitionType = spec.rawPartitionType();
+            this.predicate = predicate;
+            this.skipped = skipped;
+        }
+
+        private void checkPartitionType(ContentFile<?> file) {
+            if (!partitionTypeChecked) {
+                Types.StructType physical = ((PartitionData) 
file.partition()).getPartitionType();
+                if (!physical.equals(partitionType)) {
+                    adapter = new IcebergPartitionValueAdapter(physical, 
partitionType);
+                }
+                partitionTypeChecked = true;
+            }
+        }
+
+        DataFile adapt(DataFile file) {
+            checkPartitionType(file);
+            return adapter == null ? file : adapter.adapt(file);
+        }
+
+        DeleteFile adapt(DeleteFile file) {
+            checkPartitionType(file);
+            return adapter == null ? file : adapter.adapt(file);
+        }
+
+        boolean matches(ContentFile<?> file) {
+            if (predicate.test(file)) {
+                return true;
+            }
+            skipped.run();
+            return false;
+        }
+    }
+
+    private IcebergManifestLoader() {
+    }
+
+    public static ManifestCacheValue readForCache(ManifestFile manifest, Table 
table,
+            ManifestContent content, boolean accountRetainedSize) throws 
IOException {
+        return readInternal(manifest, table, table.io(), content, 
accountRetainedSize,
+                null, null, DataFile::copy, () -> { });
+    }
+
+    public static Function<ManifestFile, ManifestCacheValue> 
uncachedLoader(Table table, List<String> columns,
+            Function<ManifestFile, ReadFilter> filters, Runnable 
checkCancelled) {
+        return uncachedLoader(table, columns, filters, DataFile::copy, 
checkCancelled);
+    }
+
+    public static Function<ManifestFile, ManifestCacheValue> 
uncachedLoader(Table table, List<String> columns,
+            Function<ManifestFile, ReadFilter> filters, 
UnaryOperator<DataFile> copyDataFile,
+            Runnable checkCancelled) {
+        return manifest -> {
+            // One request-local IO view per manifest load: ensures any stream 
opened before SDK reader
+            // ownership is established is closed if cancellation interrupts 
initialization.
+            try (IcebergScanFileIO io = new IcebergScanFileIO(table.io(), 
checkCancelled)) {
+                return read(manifest, table, io, manifest.content(), false,
+                        columns, filters, copyDataFile, checkCancelled);
+            }
+        };
+    }
+
+    private static ManifestCacheValue read(ManifestFile manifest, Table table, 
FileIO io,
+            ManifestContent content, boolean accountRetainedSize, List<String> 
columns,
+            Function<ManifestFile, ReadFilter> filters, 
UnaryOperator<DataFile> copyDataFile,
+            Runnable checkCancelled) {
+        try {
+            return readInternal(manifest, table, io, content, 
accountRetainedSize,
+                    columns, filters, copyDataFile, checkCancelled);
+        } catch (IOException e) {
+            throw new RuntimeException("Failed to read iceberg manifest " + 
manifest.path(), e);
+        }
+    }
+
+    private static ManifestCacheValue readInternal(ManifestFile manifest, 
Table table, FileIO io,
+            ManifestContent content, boolean accountRetainedSize, List<String> 
columns,
+            Function<ManifestFile, ReadFilter> filters, 
UnaryOperator<DataFile> copyDataFile,
+            Runnable checkCancelled) throws IOException {
+        checkCancelled.run();
+        ReadFilter filter = filters == null ? null : filters.apply(manifest);
+        if (content == ManifestContent.DELETES) {
+            return ManifestCacheValue.forDeleteFiles(
+                    loadDeleteFiles(manifest, table, io, filter, 
checkCancelled), accountRetainedSize);
+        }
+        return ManifestCacheValue.forDataFiles(
+                loadDataFiles(manifest, table, io, columns, filter, 
copyDataFile, checkCancelled),
+                accountRetainedSize);
+    }
+
+    private static List<DataFile> loadDataFiles(ManifestFile manifest, Table 
table, FileIO io,
+            List<String> columns, ReadFilter filter, UnaryOperator<DataFile> 
copyDataFile,
+            Runnable checkCancelled) throws IOException {
+        List<DataFile> dataFiles = new ArrayList<>();
+        // .copy() is mandatory: the ManifestReader iterator reuses the same 
object across iterations.
+        try (ManifestReader<DataFile> reader = ManifestFiles.read(manifest, io,
+                manifestReadSpecs(manifest, table, io))) {
+            if (columns != null) {
+                reader.select(columns);
+            }
+            for (DataFile borrowed : ManifestReaderAccess.liveFiles(reader)) {
+                checkCancelled.run();
+                DataFile file = filter == null ? borrowed : 
filter.adapt(borrowed);
+                if (filter == null || filter.matches(file)) {
+                    dataFiles.add(copyDataFile.apply(file));
+                }
+            }
+        }
+        return dataFiles;
+    }
+
+    /**
+     * Recover physical partition types only when a dropped partition source 
prevents strict SDK header
+     * binding. Otherwise return null so the SDK reads physical types from the 
manifest header (preserving
+     * pre-promotion physical types such as DATE before query-local 
adaptation).
+     */
+    public static Map<Integer, PartitionSpec> manifestReadSpecs(ManifestFile 
manifest, Table table, FileIO io)
+            throws IOException {
+        Map<Integer, PartitionSpec> tableSpecs = table.specs();
+        PartitionSpec spec = tableSpecs == null ? null : 
tableSpecs.get(manifest.partitionSpecId());
+        if (spec == null) {
+            return null;
+        }
+        // Fixed-result transforms (bucket/year/month/day/hour) remain 
readable without their source
+        // schema. Iceberg resolves their result from UNKNOWN; do not require 
expired source schemas.
+        boolean missingSource = spec.rawPartitionType().fields().stream()
+                .anyMatch(field -> field.type().typeId() == 
Type.TypeID.UNKNOWN);
+        if (!missingSource) {
+            return null;
+        }
+        Long commitSnapshotId = manifest.snapshotId();
+        Snapshot commitSnapshot = commitSnapshotId == null ? null : 
table.snapshot(commitSnapshotId);
+        Schema commitSchema = commitSnapshot == null ? null : 
table.schemas().get(commitSnapshot.schemaId());
+        if (commitSchema == null
+                || spec.fields().stream().anyMatch(field -> 
commitSchema.findField(field.sourceId()) == null)) {
+            // A rewrite can retain older physical types while committing 
after source removal. Recover the
+            // header types so data and delete partitions use the same 
canonical representation after adaptation.
+            PartitionSpec readable = 
ManifestReaderAccess.readPartitionSpec(manifest, io);
+            return Collections.singletonMap(readable.specId(), readable);
+        }
+        Map<Integer, Types.NestedField> sources = new LinkedHashMap<>();
+        Set<String> reservedNames = new HashSet<>();
+        spec.fields().forEach(field -> reservedNames.add(field.name()));
+        for (PartitionField field : spec.fields()) {
+            Types.NestedField source = 
commitSchema.findField(field.sourceId());
+            String name = "source_" + field.sourceId();
+            while (!reservedNames.add(name)) {
+                name += "_";
+            }
+            sources.put(field.sourceId(), 
Types.NestedField.optional(field.sourceId(), name, source.type()));
+        }
+        PartitionSpec readable = spec.toUnbound().bind(new Schema(
+                new ArrayList<>(sources.values())), true);
+        return Collections.singletonMap(readable.specId(), readable);
+    }
+
+    private static List<DeleteFile> loadDeleteFiles(ManifestFile manifest, 
Table table, FileIO io,
+            ReadFilter filter, Runnable checkCancelled) throws IOException {
+        List<DeleteFile> deleteFiles = new ArrayList<>();
+        try (ManifestReader<DeleteFile> reader =
+                ManifestFiles.readDeleteManifest(manifest, io, 
manifestReadSpecs(manifest, table, io))) {
+            for (DeleteFile borrowed : ManifestReaderAccess.liveFiles(reader)) 
{
+                checkCancelled.run();
+                DeleteFile file = filter == null ? borrowed : 
filter.adapt(borrowed);
+                if (filter == null || filter.matches(file)) {
+                    deleteFiles.add(filter == null ? file.copy() : 
copyDeleteForIndex(file));
+                }
+            }
+        }
+        return deleteFiles;
+    }
+
+    /** Match the SDK index's retention policy after predicates have inspected 
the complete statistics. */
+    public static DeleteFile copyDeleteForIndex(DeleteFile file) {
+        Set<Integer> columns = file.content() == FileContent.POSITION_DELETES
+                ? 
Collections.singleton(MetadataColumns.DELETE_FILE_PATH.fieldId())
+                : new HashSet<>(file.equalityFieldIds());
+        return ContentFileUtil.copy(file, true, columns);
+    }
+}
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/cache/IcebergScanFileIO.java
 
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/cache/IcebergScanFileIO.java
new file mode 100644
index 00000000000..79d9c7d5210
--- /dev/null
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/cache/IcebergScanFileIO.java
@@ -0,0 +1,189 @@
+// 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.doris.datasource.iceberg.cache;
+
+import org.apache.iceberg.CatalogProperties;
+import org.apache.iceberg.DataFile;
+import org.apache.iceberg.DeleteFile;
+import org.apache.iceberg.ManifestFile;
+import org.apache.iceberg.ManifestListFile;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.io.SeekableInputStream;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+
+/** Request-local reads: cancellation never enters a catalog's shared FileIO 
or Doris manifest-cache loader. */
+final class IcebergScanFileIO implements FileIO {
+    private static final Logger LOG = 
LogManager.getLogger(IcebergScanFileIO.class);
+
+    private final FileIO delegate;
+    private final Runnable checkCancelled;
+    private final Set<SeekableInputStream> openStreams = 
ConcurrentHashMap.newKeySet();
+
+    IcebergScanFileIO(FileIO delegate, Runnable checkCancelled) {
+        this.delegate = delegate;
+        this.checkCancelled = checkCancelled;
+    }
+
+    @Override
+    public InputFile newInputFile(String path) {
+        checkCancelled.run();
+        return guarded(delegate.newInputFile(path));
+    }
+
+    @Override
+    public InputFile newInputFile(String path, long length) {
+        checkCancelled.run();
+        return guarded(delegate.newInputFile(path, length));
+    }
+
+    @Override
+    public InputFile newInputFile(DataFile file) {
+        checkCancelled.run();
+        return guarded(delegate.newInputFile(file));
+    }
+
+    @Override
+    public InputFile newInputFile(DeleteFile file) {
+        checkCancelled.run();
+        return guarded(delegate.newInputFile(file));
+    }
+
+    @Override
+    public InputFile newInputFile(ManifestFile file) {
+        checkCancelled.run();
+        return guarded(delegate.newInputFile(file));
+    }
+
+    @Override
+    public InputFile newInputFile(ManifestListFile file) {
+        checkCancelled.run();
+        return guarded(delegate.newInputFile(file));
+    }
+
+    private InputFile guarded(InputFile input) {
+        return new InputFile() {
+            @Override
+            public long getLength() {
+                checkCancelled.run();
+                return input.getLength();
+            }
+
+            @Override
+            public boolean exists() {
+                checkCancelled.run();
+                return input.exists();
+            }
+
+            @Override
+            public String location() {
+                return input.location();
+            }
+
+            @Override
+            public SeekableInputStream newStream() {
+                checkCancelled.run();
+                SeekableInputStream stream = input.newStream();
+                openStreams.add(stream);
+                return new SeekableInputStream() {
+                    @Override
+                    public long getPos() throws IOException {
+                        return stream.getPos();
+                    }
+
+                    @Override
+                    public void seek(long position) throws IOException {
+                        checkCancelled.run();
+                        stream.seek(position);
+                    }
+
+                    @Override
+                    public int read() throws IOException {
+                        checkCancelled.run();
+                        return stream.read();
+                    }
+
+                    @Override
+                    public int read(byte[] bytes, int offset, int length) 
throws IOException {
+                        checkCancelled.run();
+                        return stream.read(bytes, offset, length);
+                    }
+
+                    @Override
+                    public long skip(long count) throws IOException {
+                        checkCancelled.run();
+                        return stream.skip(count);
+                    }
+
+                    @Override
+                    public void close() throws IOException {
+                        // Closing belongs to the SDK reader, including when 
cancelled.
+                        try {
+                            stream.close();
+                        } finally {
+                            openStreams.remove(stream);
+                        }
+                    }
+                };
+            }
+        };
+    }
+
+    @Override
+    public Map<String, String> properties() {
+        checkCancelled.run();
+        Map<String, String> properties = new HashMap<>(delegate.properties());
+        // SDK ByteBuffer cache hits bypass our stream's checks. Keep the 
guard even for in-memory reads.
+        // This view has request identity anyway; the catalog FileIO and Doris 
shared manifest cache are intact.
+        properties.put(CatalogProperties.IO_MANIFEST_CACHE_ENABLED, "false");
+        return properties;
+    }
+
+    @Override
+    public OutputFile newOutputFile(String path) {
+        throw new UnsupportedOperationException("Split planning FileIO is 
read-only");
+    }
+
+    @Override
+    public void deleteFile(String path) {
+        throw new UnsupportedOperationException("Split planning FileIO is 
read-only");
+    }
+
+    @Override
+    public void close() {
+        // Close any streams opened before SDK reader ownership was 
established (e.g. if cancellation
+        // interrupted AvroIterable between newStream() and getLength()). 
Never close the shared delegate.
+        for (SeekableInputStream stream : openStreams) {
+            if (openStreams.remove(stream)) {
+                try {
+                    stream.close();
+                } catch (IOException e) {
+                    LOG.debug("Failed to close leaked Iceberg manifest 
stream", e);
+                }
+            }
+        }
+    }
+}
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/cache/ManifestCacheValue.java
 
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/cache/ManifestCacheValue.java
index 8cb90121fae..1283c62ef35 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/cache/ManifestCacheValue.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/cache/ManifestCacheValue.java
@@ -36,7 +36,7 @@ import java.util.List;
 import java.util.Map;
 
 /**
- * Cached manifest payload containing parsed files.
+ * Immutable parsed files of one Iceberg manifest, optionally retained in the 
manifest cache.
  */
 public class ManifestCacheValue {
     private static final long AUXILIARY_LIST_ENTRY_BYTES =
@@ -77,7 +77,11 @@ public class ManifestCacheValue {
     }
 
     public static ManifestCacheValue forDataFiles(List<DataFile> dataFiles) {
-        Builder builder = dataFilesBuilder();
+        return forDataFiles(dataFiles, true);
+    }
+
+    public static ManifestCacheValue forDataFiles(List<DataFile> dataFiles, 
boolean accountRetainedSize) {
+        Builder builder = dataFilesBuilder(accountRetainedSize);
         if (dataFiles != null) {
             dataFiles.forEach(builder::addDataFile);
         }
@@ -85,7 +89,11 @@ public class ManifestCacheValue {
     }
 
     public static ManifestCacheValue forDeleteFiles(List<DeleteFile> 
deleteFiles) {
-        Builder builder = deleteFilesBuilder();
+        return forDeleteFiles(deleteFiles, true);
+    }
+
+    public static ManifestCacheValue forDeleteFiles(List<DeleteFile> 
deleteFiles, boolean accountRetainedSize) {
+        Builder builder = deleteFilesBuilder(accountRetainedSize);
         if (deleteFiles != null) {
             deleteFiles.forEach(builder::addDeleteFile);
         }
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/source/IcebergScanNode.java
 
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/source/IcebergScanNode.java
index 575df9274c0..c543b8f0f5c 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/source/IcebergScanNode.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/source/IcebergScanNode.java
@@ -60,6 +60,8 @@ import 
org.apache.doris.datasource.iceberg.IcebergSysExternalTable;
 import org.apache.doris.datasource.iceberg.IcebergTimestampUtils;
 import org.apache.doris.datasource.iceberg.IcebergUtils;
 import org.apache.doris.datasource.iceberg.cache.IcebergManifestCacheLoader;
+import org.apache.doris.datasource.iceberg.cache.IcebergManifestLoader;
+import org.apache.doris.datasource.iceberg.cache.ManifestCacheValue;
 import org.apache.doris.datasource.iceberg.profile.IcebergMetricsReporter;
 import 
org.apache.doris.datasource.iceberg.source.IcebergDeleteFileFilter.EqualityDelete;
 import org.apache.doris.datasource.mvcc.MvccSnapshot;
@@ -104,6 +106,7 @@ import org.apache.commons.lang3.exception.ExceptionUtils;
 import org.apache.iceberg.BaseFileScanTask;
 import org.apache.iceberg.BaseTable;
 import org.apache.iceberg.BatchScan;
+import org.apache.iceberg.ContentFile;
 import org.apache.iceberg.ContentScanTask;
 import org.apache.iceberg.DataFile;
 import org.apache.iceberg.DeleteFile;
@@ -135,9 +138,13 @@ import org.apache.iceberg.expressions.Expression;
 import org.apache.iceberg.expressions.Expressions;
 import org.apache.iceberg.expressions.InclusiveMetricsEvaluator;
 import org.apache.iceberg.expressions.ManifestEvaluator;
+import org.apache.iceberg.expressions.Projections;
 import org.apache.iceberg.expressions.ResidualEvaluator;
 import org.apache.iceberg.io.CloseableIterable;
 import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.metrics.Counter;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.metrics.ScanMetricsUtil;
 import org.apache.iceberg.types.Type;
 import org.apache.iceberg.types.TypeUtil;
 import org.apache.iceberg.types.Types;
@@ -174,11 +181,14 @@ import java.util.concurrent.Executor;
 import java.util.concurrent.FutureTask;
 import java.util.concurrent.ThreadPoolExecutor;
 import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.function.Predicate;
 import java.util.function.Supplier;
 import java.util.stream.Collectors;
 
 public class IcebergScanNode extends FileQueryScanNode {
     private static final long MAX_RETAINED_SERIALIZED_TASK_BYTES = 16L * 1024 
* 1024;
+    private static final int MAX_UNCACHED_MANIFEST_WINDOW_FILES = 30_000;
 
     public static final int MIN_DELETE_FILE_SUPPORT_VERSION = 2;
     static final int ICEBERG_SCAN_SEMANTICS_VERSION = 2;
@@ -2099,21 +2109,84 @@ public class IcebergScanNode extends FileQueryScanNode {
 
     @VisibleForTesting
     CloseableIterable<FileScanTask> planFileScanTaskWithoutReuse(TableScan 
scan) {
-        if (!IcebergUtils.isManifestCacheEnabled(source.getCatalog())) {
-            return splitFiles(scan);
+        if (IcebergUtils.isManifestCacheEnabled(source.getCatalog())) {
+            try {
+                return planFileScanTaskWithManifestCache(scan);
+            } catch (Exception e) {
+                if (isScanTaskLeaseClosed() || 
Thread.currentThread().isInterrupted()
+                        || (splitAssignment != null && 
splitAssignment.isStop())
+                        || e instanceof CancellationException) {
+                    throw new CancellationException("Iceberg scan planning was 
cancelled");
+                }
+                manifestCacheFailures++;
+                LOG.warn("Plan with manifest cache failed, fallback to 
original scan: " + e.getMessage(), e);
+                return splitFiles(scan);
+            }
+        }
+        checkScanPlanningCancelled();
+        if (canPlanManifestsWithoutCache(scan)) {
+            targetSplitSize = sessionVariable.getFileSplitSize() > 0
+                    ? sessionVariable.getFileSplitSize() : 
sessionVariable.getMaxSplitSize();
+            Snapshot snapshot = scan.snapshot();
+            return splitFiles(
+                    DorisDataTableScan.planFilesWithLocalPlanner(scan, metrics 
-> {
+                        try {
+                            return streamFileScanTasks(scan, snapshot, false, 
metrics);
+                        } catch (IOException e) {
+                            throw new RuntimeException("Failed to plan Iceberg 
scan tasks", e);
+                        }
+                    }),
+                    targetSplitSize);
         }
-        try {
-            return planFileScanTaskWithManifestCache(scan);
-        } catch (Exception e) {
-            if (isScanTaskLeaseClosed() || 
Thread.currentThread().isInterrupted()
-                    || (splitAssignment != null && splitAssignment.isStop())
-                    || e instanceof CancellationException) {
-                throw new CancellationException("Iceberg scan planning was 
cancelled");
+        return splitFiles(scan);
+    }
+
+    private void checkScanPlanningCancelled() {
+        if (isScanTaskLeaseClosed() || Thread.currentThread().isInterrupted()
+                || (splitAssignment != null && splitAssignment.isStop())) {
+            throw new CancellationException("Iceberg scan planning was 
cancelled");
+        }
+    }
+
+    private boolean canPlanManifestsWithoutCache(TableScan scan) {
+        if (!isBatchMode() || tableLevelPushDownCount) {
+            return false;
+        }
+        if (!DorisDataTableScan.supportsLocalManifestPlanning(scan)) {
+            return false;
+        }
+        if (!(source.getTargetTable() instanceof ExternalTable)) {
+            return false;
+        }
+        Snapshot snapshot = scan.snapshot();
+        return snapshot != null && 
canBufferManifestFiles(snapshot.dataManifests(scan.table().io()),
+                manifestReadConcurrency());
+    }
+
+    @VisibleForTesting
+    static boolean canBufferManifestFiles(List<ManifestFile> manifests, int 
window) {
+        // A single manifest already streams without ParallelIterable in the 
SDK. Preserve early delivery
+        // within large manifests too: our prefetcher drains each manifest, 
whereas SDK consumers can take
+        // the first file before its manifest finishes. Include deleted 
entries in the read-work bound:
+        // ManifestReader traverses them even though they are not retained in 
the live-file result.
+        if (manifests.size() <= 1) {
+            return false;
+        }
+        int filesPerManifest = MAX_UNCACHED_MANIFEST_WINDOW_FILES / 
Math.max(1, window);
+        for (ManifestFile manifest : manifests) {
+            Integer added = manifest.addedFilesCount();
+            Integer existing = manifest.existingFilesCount();
+            Integer deleted = manifest.deletedFilesCount();
+            if (added == null || existing == null || deleted == null
+                    || (long) added + existing + deleted > filesPerManifest) {
+                return false;
             }
-            manifestCacheFailures++;
-            LOG.warn("Plan with manifest cache failed, fallback to original 
scan: " + e.getMessage(), e);
-            return splitFiles(scan);
         }
+        return true;
+    }
+
+    private static int manifestReadConcurrency() {
+        return Math.max(1, Config.external_scan_metadata_threads);
     }
 
     private CloseableIterable<FileScanTask> splitFiles(TableScan scan) {
@@ -2454,10 +2527,21 @@ public class IcebergScanNode extends FileQueryScanNode {
     @VisibleForTesting
     protected CloseableIterable<FileScanTask> 
streamFileScanTasksWithManifestCache(
             TableScan scan, Snapshot snapshot) throws IOException {
-        // Initialize manifest cache for efficient manifest file access
+        return streamFileScanTasks(scan, snapshot, true, null);
+    }
+
+    private CloseableIterable<FileScanTask> streamFileScanTasks(
+            TableScan scan, Snapshot snapshot, boolean cacheEnabled, 
ScanMetrics scanMetrics) throws IOException {
+        checkScanPlanningCancelled();
         if (!(source.getTargetTable() instanceof ExternalTable)) {
             throw new RuntimeException("Iceberg scan target table is not an 
external table");
         }
+        List<ManifestFile> dataManifestList = 
snapshot.dataManifests(icebergTable.io());
+        List<ManifestFile> deleteManifests = 
snapshot.deleteManifests(icebergTable.io());
+        if (scanMetrics != null) {
+            
scanMetrics.totalDataManifests().increment(dataManifestList.size());
+            
scanMetrics.totalDeleteManifests().increment(deleteManifests.size());
+        }
         Schema scanSchema = scan.schema();
         Set<Integer> unsafeNanosFields = 
IcebergTimestampUtils.unsafeNanosFields(icebergTable, scanSchema);
 
@@ -2482,40 +2566,60 @@ public class IcebergScanNode extends FileQueryScanNode {
         InclusiveMetricsEvaluator metricsEvaluator =
                 new InclusiveMetricsEvaluator(scanSchema, filterExpr, 
caseSensitive);
 
+        Function<ManifestFile, IcebergManifestLoader.ReadFilter> filters = 
manifest -> {
+            PartitionSpec spec = specsById.get(manifest.partitionSpecId());
+            // Evaluators and the lazy type adapter belong to one loading 
worker, never to a shared cache.
+            InclusiveMetricsEvaluator metrics = new 
InclusiveMetricsEvaluator(scanSchema, filterExpr, caseSensitive);
+            ResidualEvaluator residual = ResidualEvaluator.of(spec, 
filterExpr, caseSensitive);
+            Predicate<ContentFile<?>> predicate = file -> 
matchesFileFilter(file, metrics, residual);
+            return new IcebergManifestLoader.ReadFilter(spec, predicate, () -> 
{
+                if (scanMetrics != null) {
+                    if (manifest.content() == ManifestContent.DATA) {
+                        scanMetrics.skippedDataFiles().increment();
+                    } else {
+                        scanMetrics.skippedDeleteFiles().increment();
+                    }
+                }
+            });
+        };
+
         // ========== Phase 1: Load delete files from delete manifests 
==========
         List<DeleteFile> deleteFiles = new ArrayList<>();
-        List<ManifestFile> deleteManifests = 
snapshot.deleteManifests(icebergTable.io());
-        List<ManifestFile> matchingDeletes = new ArrayList<>();
-        for (ManifestFile manifest : deleteManifests) {
-            // Skip non-delete manifests
-            if (manifest.content() != ManifestContent.DELETES) {
-                continue;
-            }
-            // Get the partition spec for this manifest
-            PartitionSpec spec = specsById.get(manifest.partitionSpecId());
-            if (spec == null) {
-                continue;
-            }
-            // Create manifest evaluator for partition-level pruning
-            ManifestEvaluator evaluator =
-                    ManifestEvaluator.forPartitionFilter(filterExpr, spec, 
caseSensitive);
-            // Skip manifest if it doesn't match the filter expression 
(partition pruning)
-            if (!evaluator.eval(manifest)) {
-                continue;
-            }
-            matchingDeletes.add(manifest);
-        }
-        try (NativeManifestPrefetcher prefetch = 
prefetchManifests(matchingDeletes, true)) {
-            for (NativeManifestPrefetcher.Result result : prefetch) {
-                
deleteFiles.addAll(result.value.forScan(specsById.get(result.manifest.partitionSpecId()))
-                        .getDeleteFiles());
+        Set<Integer> equalityFields = new HashSet<>();
+        if (!deleteManifests.isEmpty()) {
+            Function<ManifestFile, ManifestCacheValue> deleteLoader = 
cacheEnabled ? null
+                    : IcebergManifestLoader.uncachedLoader(
+                            icebergTable, null, filters, 
this::checkScanPlanningCancelled);
+            try (CloseableIterable<ManifestFile> matchingDeletes = 
getMatchingManifest(
+                    deleteManifests, specsById, filterExpr, 
this::checkScanPlanningCancelled, scanMetrics, true);
+                    NativeManifestPrefetcher prefetch = prefetchManifests(
+                            matchingDeletes, cacheEnabled, true, 
deleteLoader)) {
+                for (NativeManifestPrefetcher.Result result : prefetch) {
+                    checkScanPlanningCancelled();
+                    int specId = result.manifest.partitionSpecId();
+                    ResidualEvaluator residual = 
residualEvaluators.get(specId);
+                    // Manifest summaries only reject whole manifests. Match 
the SDK's per-file row and
+                    // partition pruning before indexing, after type 
adaptation, without changing cached values.
+                    for (DeleteFile file : 
result.value.forScan(specsById.get(specId)).getDeleteFiles()) {
+                        checkScanPlanningCancelled();
+                        if (!cacheEnabled || matchesFileFilter(file, 
metricsEvaluator, residual)) {
+                            deleteFiles.add(cacheEnabled ? 
IcebergManifestLoader.copyDeleteForIndex(file) : file);
+                            if (!cacheEnabled && file.content() == 
FileContent.EQUALITY_DELETES) {
+                                equalityFields.addAll(file.equalityFieldIds());
+                            }
+                        } else if (scanMetrics != null) {
+                            scanMetrics.skippedDeleteFiles().increment();
+                        }
+                    }
+                }
             }
         }
 
         // Build delete file index for efficient lookup of deletes applicable 
to each data file
         DeleteFileIndex.Builder deleteIndexBuilder = 
DeleteFileIndex.builderFor(deleteFiles)
                 .specsById(specsById)
-                .caseSensitive(caseSensitive);
+                .caseSensitive(caseSensitive)
+                .scanMetrics(scanMetrics == null ? ScanMetrics.noop() : 
scanMetrics);
         // Equality deletes may reference fields dropped from the current 
schema, so resolve their
         // field IDs against every historical schema. Other scans skip 
indexing the schema history.
         if (deleteFiles.stream().anyMatch(file -> file.content() == 
FileContent.EQUALITY_DELETES)) {
@@ -2523,13 +2627,24 @@ public class IcebergScanNode extends FileQueryScanNode {
         }
         DeleteFileIndex deleteIndex = deleteIndexBuilder.build();
 
+        // Read statistics for predicates, retain requested/equality-key 
statistics in the window, then
+        // discard internal equality-key maps only after delete association. 
Shared cached values stay complete.
+        Set<Integer> requiredStats = deleteIndex.hasEqualityDeletes() ? 
equalityFields : Collections.emptySet();
+        boolean hasPredicate = filterExpr != Expressions.alwaysTrue();
+        DorisDataTableScan.DataFileProjection dataProjection = cacheEnabled ? 
null
+                : DorisDataTableScan.dataFileProjection(scan, requiredStats, 
hasPredicate);
+        Function<ManifestFile, ManifestCacheValue> dataLoader = cacheEnabled ? 
null
+                : IcebergManifestLoader.uncachedLoader(icebergTable, 
dataProjection.manifestColumns(), filters,
+                        dataProjection::copyForManifest, 
this::checkScanPlanningCancelled);
+
         // A batch scan retains only the current manifest view and the bounded 
prefetch window.
         // Errors after delivery must fail the query; restarting a full SDK 
scan could duplicate rows.
-        CloseableIterable<ManifestFile> dataManifests = 
IcebergUtils.getMatchingManifest(
-                snapshot.dataManifests(icebergTable.io()), specsById, 
filterExpr);
+        checkScanPlanningCancelled();
+        CloseableIterable<ManifestFile> dataManifests = getMatchingManifest(
+                dataManifestList, specsById, filterExpr, 
this::checkScanPlanningCancelled, scanMetrics, false);
         NativeManifestPrefetcher prefetch;
         try {
-            prefetch = prefetchManifests(dataManifests, false);
+            prefetch = prefetchManifests(dataManifests, cacheEnabled, false, 
dataLoader);
         } catch (RuntimeException | Error e) {
             dataManifests.close();
             throw e;
@@ -2546,14 +2661,23 @@ public class IcebergScanNode extends FileQueryScanNode {
             @Override
             protected FileScanTask computeNext() {
                 while (true) {
+                    checkScanPlanningCancelled();
                     while (files.hasNext()) {
+                        checkScanPlanningCancelled();
                         org.apache.iceberg.DataFile file = files.next();
-                        if (!metricsEvaluator.eval(file)
-                                || 
residual.residualFor(file.partition()).equals(Expressions.alwaysFalse())) {
+                        if (cacheEnabled && !matchesFileFilter(file, 
metricsEvaluator, residual)) {
+                            if (scanMetrics != null) {
+                                scanMetrics.skippedDataFiles().increment();
+                            }
                             continue;
                         }
                         DeleteFile[] deletes = 
deleteIndex.forDataFile(file.dataSequenceNumber(), file);
-                        return new BaseFileScanTask(file, deletes, schemaJson, 
specJson.get(spec.specId()), residual);
+                        DataFile taskFile = dataProjection == null ? file : 
dataProjection.forTask(file);
+                        if (scanMetrics != null) {
+                            ScanMetricsUtil.fileTask(scanMetrics, taskFile, 
deletes);
+                        }
+                        return new BaseFileScanTask(taskFile, deletes, 
schemaJson, specJson.get(spec.specId()),
+                                residual);
                     }
                     if (!manifests.hasNext()) {
                         return endOfData();
@@ -2580,7 +2704,52 @@ public class IcebergScanNode extends FileQueryScanNode {
         });
     }
 
-    private NativeManifestPrefetcher prefetchManifests(Iterable<ManifestFile> 
manifests, boolean deletes) {
+    private static boolean matchesFileFilter(ContentFile<?> file, 
InclusiveMetricsEvaluator metrics,
+            ResidualEvaluator residual) {
+        return metrics.eval(file) && 
!residual.residualFor(file.partition()).equals(Expressions.alwaysFalse());
+    }
+
+    private static CloseableIterable<ManifestFile> 
getMatchingManifest(List<ManifestFile> manifests,
+            Map<Integer, PartitionSpec> specsById, Expression dataFilter, 
Runnable checkCancelled,
+            ScanMetrics scanMetrics, boolean deleteManifests) {
+        ManifestContent expectedContent = deleteManifests ? 
ManifestContent.DELETES : ManifestContent.DATA;
+        Map<Integer, ManifestEvaluator> evalCache = new HashMap<>();
+        Counter skipped = scanMetrics == null ? null
+                : deleteManifests ? scanMetrics.skippedDeleteManifests() : 
scanMetrics.skippedDataManifests();
+        CloseableIterable<ManifestFile> matching = CloseableIterable.filter(
+                CloseableIterable.withNoopClose(manifests),
+                manifest -> {
+                    checkCancelled.run();
+                    if (manifest.content() != expectedContent) {
+                        return false;
+                    }
+                    PartitionSpec spec = 
specsById.get(manifest.partitionSpecId());
+                    if (spec == null) {
+                        return false;
+                    }
+                    boolean matches = 
evalCache.computeIfAbsent(manifest.partitionSpecId(), specId ->
+                            ManifestEvaluator.forPartitionFilter(
+                                    Expressions.and(Expressions.alwaysTrue(),
+                                            Projections.inclusive(spec, 
true).project(dataFilter)),
+                                    spec, true)).eval(manifest);
+                    if (!matches && skipped != null) {
+                        skipped.increment();
+                    }
+                    return matches;
+                });
+        CloseableIterable<ManifestFile> live = 
CloseableIterable.filter(matching, manifest -> {
+            boolean hasLiveFiles = manifest.hasAddedFiles() || 
manifest.hasExistingFiles();
+            if (!hasLiveFiles && skipped != null) {
+                skipped.increment();
+            }
+            return hasLiveFiles;
+        });
+        return scanMetrics == null ? live : 
CloseableIterable.count(deleteManifests
+                ? scanMetrics.scannedDeleteManifests() : 
scanMetrics.scannedDataManifests(), live);
+    }
+
+    private NativeManifestPrefetcher prefetchManifests(Iterable<ManifestFile> 
manifests, boolean cacheEnabled,
+            boolean deletes, Function<ManifestFile, ManifestCacheValue> 
uncachedLoader) {
         Executor metadata = getManifestReadExecutor();
         SplitAssignment assignment = splitAssignment == null
                 ? new SplitAssignment(backendPolicy, this, 
this::splitToScanRange,
@@ -2592,19 +2761,26 @@ public class IcebergScanNode extends FileQueryScanNode {
             }
         }
         ExternalTable target = (ExternalTable) source.getTargetTable();
-        IcebergExternalMetaCache cache = 
Env.getCurrentEnv().getExtMetaCacheMgr().iceberg(source.getCatalog().getId());
+        IcebergExternalMetaCache cache = cacheEnabled
+                ? 
Env.getCurrentEnv().getExtMetaCacheMgr().iceberg(source.getCatalog().getId()) : 
null;
         return new NativeManifestPrefetcher(manifests, metadata, assignment,
                 metadata instanceof FairTaskExecutor.Group && 
getScanTaskLease() == null,
-                Math.max(1, Config.external_scan_metadata_threads),
+                manifestReadConcurrency(),
                 () -> 
IcebergUtils.retainTableGenerationForAsyncPlanning(target, 
frozenGenerationSource),
                 manifest -> {
                     try {
+                        if (!cacheEnabled) {
+                            return preExecutionAuthenticator.execute(() -> 
uncachedLoader.apply(manifest));
+                        }
                         return preExecutionAuthenticator.execute(() -> deletes
                                 ? 
IcebergManifestCacheLoader.loadDeleteFilesWithCache(cache, target, manifest,
                                         icebergTable, runtimeContext, 
this::recordManifestCacheAccess)
                                 : 
IcebergManifestCacheLoader.loadDataFilesWithCache(cache, target, manifest,
                                         icebergTable, runtimeContext, 
this::recordManifestCacheAccess));
                     } catch (Exception e) {
+                        if (e instanceof CancellationException) {
+                            throw (CancellationException) e;
+                        }
                         throw new RuntimeException(e);
                     }
                 });
diff --git a/fe/fe-core/src/main/java/org/apache/iceberg/DeleteFileIndex.java 
b/fe/fe-core/src/main/java/org/apache/iceberg/DeleteFileIndex.java
index 78aae9240f4..dda3f0cbc67 100644
--- a/fe/fe-core/src/main/java/org/apache/iceberg/DeleteFileIndex.java
+++ b/fe/fe-core/src/main/java/org/apache/iceberg/DeleteFileIndex.java
@@ -452,7 +452,7 @@ public class DeleteFileIndex {
       return this;
     }
 
-    Builder scanMetrics(ScanMetrics newScanMetrics) {
+    public Builder scanMetrics(ScanMetrics newScanMetrics) {
       this.scanMetrics = newScanMetrics;
       return this;
     }
diff --git 
a/fe/fe-core/src/main/java/org/apache/iceberg/DorisDataTableScan.java 
b/fe/fe-core/src/main/java/org/apache/iceberg/DorisDataTableScan.java
index 08c11ad8cef..868f2d9dd0a 100644
--- a/fe/fe-core/src/main/java/org/apache/iceberg/DorisDataTableScan.java
+++ b/fe/fe-core/src/main/java/org/apache/iceberg/DorisDataTableScan.java
@@ -17,8 +17,17 @@
 
 package org.apache.iceberg;
 
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.util.ContentFileUtil;
+
+import java.util.Collections;
 import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
 import java.util.Map;
+import java.util.Set;
+import java.util.function.Function;
 
 /** Keeps partition pruning aligned with the schema selected by the Doris 
relation. */
 public class DorisDataTableScan extends DataTableScan {
@@ -34,6 +43,71 @@ public class DorisDataTableScan extends DataTableScan {
         return new DorisDataTableScan(dataScan.table(), 
dataScan.tableSchema(), dataScan.context());
     }
 
+    /** Only native data scans can be replaced by local manifest planning 
without losing custom semantics. */
+    public static boolean supportsLocalManifestPlanning(TableScan scan) {
+        return (scan.getClass() == DataTableScan.class || scan.getClass() == 
DorisDataTableScan.class)
+                && scan.table().getClass() == BaseTable.class;
+    }
+
+    /** Separate predicate-read statistics, window retention and the native 
task's requested statistics. */
+    public static DataFileProjection dataFileProjection(TableScan scan, 
Set<Integer> equalityFields,
+            boolean hasPredicate) {
+        return new DataFileProjection((DataTableScan) scan, equalityFields, 
hasPredicate);
+    }
+
+    /** Immutable per-scan projection; equality keys remain available until 
delete association completes. */
+    public static final class DataFileProjection {
+        private final List<String> manifestColumns;
+        private final boolean keepWindowStats;
+        private final Set<Integer> windowStatColumns;
+        private final boolean keepTaskStats;
+        private final Set<Integer> taskStatColumns;
+        private final boolean needsTaskCopy;
+
+        private DataFileProjection(DataTableScan scan, Set<Integer> 
equalityFields, boolean hasPredicate) {
+            keepTaskStats = scan.shouldReturnColumnStats();
+            Set<Integer> requested = keepTaskStats ? scan.columnsToKeepStats() 
: Collections.emptySet();
+            taskStatColumns = requested == null ? null : 
Collections.unmodifiableSet(new HashSet<>(requested));
+            manifestColumns = (hasPredicate || !equalityFields.isEmpty()) && 
!keepTaskStats
+                    ? ManifestReader.withStatsColumns(scan.scanColumns()) : 
scan.scanColumns();
+            keepWindowStats = keepTaskStats || !equalityFields.isEmpty();
+            if (taskStatColumns == null) {
+                // A null native selection with returnColumnStats=true 
explicitly requests every column.
+                windowStatColumns = null;
+                needsTaskCopy = false;
+            } else {
+                Set<Integer> retained = new HashSet<>(taskStatColumns);
+                retained.addAll(equalityFields);
+                windowStatColumns = Collections.unmodifiableSet(retained);
+                needsTaskCopy = !taskStatColumns.containsAll(equalityFields);
+            }
+        }
+
+        public List<String> manifestColumns() {
+            return manifestColumns;
+        }
+
+        public DataFile copyForManifest(DataFile file) {
+            return ContentFileUtil.copy(file, keepWindowStats, 
windowStatColumns);
+        }
+
+        public DataFile forTask(DataFile file) {
+            return needsTaskCopy ? ContentFileUtil.copy(file, keepTaskStats, 
taskStatColumns) : file;
+        }
+    }
+
+    /** Reuse the native ScanEvent, planning timer and close-time table 
reporter around local planning. */
+    public static CloseableIterable<FileScanTask> 
planFilesWithLocalPlanner(TableScan scan,
+            Function<ScanMetrics, CloseableIterable<FileScanTask>> planner) {
+        DataTableScan nativeScan = (DataTableScan) scan;
+        return new DataTableScan(scan.table(), nativeScan.tableSchema(), 
nativeScan.context()) {
+            @Override
+            public CloseableIterable<FileScanTask> doPlanFiles() {
+                return planner.apply(scanMetrics());
+            }
+        }.planFiles();
+    }
+
     /** Rebinds snapshot specs by field ID to the full schema selected for the 
scan. */
     public static Map<Integer, PartitionSpec> specsForScan(TableScan scan) {
         Map<Integer, PartitionSpec> tableSpecs = scan.table().specs();
diff --git 
a/fe/fe-core/src/main/java/org/apache/iceberg/ManifestReaderAccess.java 
b/fe/fe-core/src/main/java/org/apache/iceberg/ManifestReaderAccess.java
new file mode 100644
index 00000000000..bcc18d63d5e
--- /dev/null
+++ b/fe/fe-core/src/main/java/org/apache/iceberg/ManifestReaderAccess.java
@@ -0,0 +1,56 @@
+// 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.iceberg;
+
+import org.apache.iceberg.avro.AvroIterable;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.util.JsonUtil;
+
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
+import java.io.IOException;
+import java.util.Map;
+
+/** Package bridge for filtering borrowed manifest entries before copying 
retained files. */
+public final class ManifestReaderAccess {
+    private ManifestReaderAccess() {
+    }
+
+    /** Recover header types without rejecting historical fields whose source 
columns were dropped. */
+    public static PartitionSpec readPartitionSpec(ManifestFile manifest, 
FileIO io) throws IOException {
+        // A rewritten manifest can carry the current table schema and an 
older partition spec. The SDK's
+        // header reader binds strictly, unlike table metadata loading, and 
rejects that valid combination.
+        try (CloseableIterable<?> header = InternalData.read(FileFormat.AVRO, 
io.newInputFile(manifest))
+                .project(new Schema(ManifestEntry.STATUS)).build()) {
+            Map<String, String> metadata = ((AvroIterable<?>) 
header).getMetadata();
+            ObjectNode specJson = JsonUtil.mapper().createObjectNode();
+            specJson.put("spec-id", manifest.partitionSpecId());
+            specJson.set("fields", 
JsonUtil.mapper().readTree(metadata.get("partition-spec")));
+            return 
PartitionSpecParser.fromJson(specJson).bind(SchemaParser.fromJson(metadata.get("schema")),
 true);
+        }
+    }
+
+    /**
+     * The reader owns all underlying streams and must remain open during 
iteration. Files are reused;
+     * callers must finish inspecting each file and copy any retained value 
before advancing.
+     */
+    public static <F extends ContentFile<F>> Iterable<F> 
liveFiles(ManifestReader<F> reader) {
+        return CloseableIterable.transform(reader.liveEntries(), 
ManifestEntry::file);
+    }
+}
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/datasource/iceberg/source/IcebergUncachedManifestPlanningTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/datasource/iceberg/source/IcebergUncachedManifestPlanningTest.java
new file mode 100644
index 00000000000..6bc21caddae
--- /dev/null
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/datasource/iceberg/source/IcebergUncachedManifestPlanningTest.java
@@ -0,0 +1,525 @@
+// 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.doris.datasource.iceberg.source;
+
+import org.apache.doris.analysis.TupleDescriptor;
+import org.apache.doris.analysis.TupleId;
+import org.apache.doris.common.security.authentication.ExecutionAuthenticator;
+import org.apache.doris.common.util.FairTaskExecutor;
+import org.apache.doris.datasource.ExternalTable;
+import org.apache.doris.datasource.FederationBackendPolicy;
+import org.apache.doris.datasource.iceberg.IcebergExternalCatalog;
+import org.apache.doris.datasource.iceberg.IcebergPartitionInfo;
+import org.apache.doris.datasource.iceberg.IcebergSnapshot;
+import org.apache.doris.datasource.iceberg.IcebergSnapshotCacheValue;
+import org.apache.doris.datasource.iceberg.IcebergTableCacheValue;
+import org.apache.doris.datasource.iceberg.cache.IcebergManifestLoader;
+import org.apache.doris.datasource.iceberg.cache.ManifestCacheValue;
+import org.apache.doris.planner.PlanNodeId;
+import org.apache.doris.planner.ScanContext;
+import org.apache.doris.qe.SessionVariable;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.iceberg.DataFiles;
+import org.apache.iceberg.DeleteFile;
+import org.apache.iceberg.DorisDataTableScan;
+import org.apache.iceberg.FileFormat;
+import org.apache.iceberg.FileMetadata;
+import org.apache.iceberg.FileScanTask;
+import org.apache.iceberg.ManifestFile;
+import org.apache.iceberg.MetadataColumns;
+import org.apache.iceberg.Metrics;
+import org.apache.iceberg.PartitionSpec;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.TableScan;
+import org.apache.iceberg.hadoop.HadoopTables;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.io.SeekableInputStream;
+import org.apache.iceberg.types.Conversions;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.api.io.TempDir;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.lang.reflect.Field;
+import java.lang.reflect.Proxy;
+import java.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.Executor;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+@Timeout(60)
+class IcebergUncachedManifestPlanningTest {
+    private static final Schema SCHEMA = new Schema(
+            Types.NestedField.required(1, "id", Types.IntegerType.get()),
+            Types.NestedField.optional(2, "p", Types.StringType.get()));
+
+    @TempDir
+    Path tempDir;
+
+    @Test
+    void canBufferManifestFilesEnforcesSingleOversizedDeletedAndNullBounds() {
+        ManifestFile small = manifestWithFileCounts(10, 100, 0);
+        ManifestFile boundary = manifestWithFileCounts(750, 3000, 0);
+        ManifestFile oversized = manifestWithFileCounts(751, 3000, 0);
+        
Assertions.assertFalse(IcebergScanNode.canBufferManifestFiles(Collections.singletonList(small),
 8),
+                "a single SDK manifest already streams without 
ParallelIterable polling");
+        
Assertions.assertTrue(IcebergScanNode.canBufferManifestFiles(Arrays.asList(small,
 boundary), 8));
+        
Assertions.assertFalse(IcebergScanNode.canBufferManifestFiles(Arrays.asList(small,
 oversized), 8));
+        Assertions.assertTrue(IcebergScanNode.canBufferManifestFiles(
+                Arrays.asList(small, manifestWithFileCounts(1, 0, 3749)), 8));
+        Assertions.assertFalse(IcebergScanNode.canBufferManifestFiles(
+                Arrays.asList(small, manifestWithFileCounts(1, 0, 3750)), 8),
+                "deleted entries also count against the whole-manifest read 
bound");
+        Assertions.assertFalse(IcebergScanNode.canBufferManifestFiles(
+                Arrays.asList(small, manifestWithFileCounts(null, 0, 0)), 8));
+        Assertions.assertFalse(IcebergScanNode.canBufferManifestFiles(
+                Arrays.asList(small, manifestWithFileCounts(1, 0, null)), 8));
+        Assertions.assertFalse(IcebergScanNode.canBufferManifestFiles(
+                Arrays.asList(small, manifestWithFileCounts(Integer.MAX_VALUE, 
Integer.MAX_VALUE, 0)), 8));
+    }
+
+    @Test
+    void 
uncachedBatchScanUsesBoundedPrefetcherAssociatesDeletesAndDropsUnrequestedStats()
 throws Exception {
+        Map<String, String> props = Collections.singletonMap("format-version", 
"2");
+        Table table = createTable("uncached_batch_deletes", SCHEMA, 
PartitionSpec.unpartitioned(), props);
+
+        Map<Integer, ByteBuffer> bounds1 = Collections.singletonMap(
+                1, Conversions.toByteBuffer(Types.IntegerType.get(), 1));
+        Map<Integer, ByteBuffer> bounds2 = Collections.singletonMap(
+                1, Conversions.toByteBuffer(Types.IntegerType.get(), 2));
+        table.newFastAppend().appendFile(DataFiles.builder(table.spec())
+                
.withPath("/d/file_1.parquet").withFormat(FileFormat.PARQUET).withFileSizeInBytes(100)
+                .withMetrics(new Metrics(10L, null, null, null, null, bounds1, 
bounds1)).build()).commit();
+        table.newFastAppend().appendFile(DataFiles.builder(table.spec())
+                
.withPath("/d/file_2.parquet").withFormat(FileFormat.PARQUET).withFileSizeInBytes(100)
+                .withMetrics(new Metrics(10L, null, null, null, null, bounds2, 
bounds2)).build()).commit();
+
+        // Position delete targets file_1; equality delete targets id=2 
(file_2).
+        Map<Integer, ByteBuffer> posBounds = Collections.singletonMap(
+                MetadataColumns.DELETE_FILE_PATH.fieldId(),
+                Conversions.toByteBuffer(Types.StringType.get(), 
"/d/file_1.parquet"));
+        DeleteFile posDelete = 
FileMetadata.deleteFileBuilder(table.spec()).ofPositionDeletes()
+                .withPath("/d/pos_del.parquet").withFormat(FileFormat.PARQUET)
+                
.withReferencedDataFile("/d/file_1.parquet").withFileSizeInBytes(64)
+                .withMetrics(new Metrics(1L, null, null, null, null, 
posBounds, posBounds)).build();
+        DeleteFile eqDelete = 
FileMetadata.deleteFileBuilder(table.spec()).ofEqualityDeletes(1)
+                
.withPath("/d/eq_del.parquet").withFormat(FileFormat.PARQUET).withFileSizeInBytes(64)
+                .withMetrics(new Metrics(1L, null, null, null, null, bounds2, 
bounds2)).build();
+        
table.newRowDelta().addDeletes(posDelete).addDeletes(eqDelete).commit();
+
+        AtomicInteger submissions = new AtomicInteger();
+        try (FairTaskExecutor pool = newPool(2)) {
+            Executor recordingExecutor = task -> {
+                submissions.incrementAndGet();
+                pool.newGroup(16).execute(task);
+            };
+            IcebergScanNode node = createScanNode(table, true, 
recordingExecutor);
+            TableScan scan = DorisDataTableScan.wrap(table.newScan());
+
+            List<FileScanTask> tasks = new ArrayList<>();
+            try (CloseableIterable<FileScanTask> planned = 
node.planFileScanTaskWithoutReuse(scan)) {
+                for (FileScanTask task : planned) {
+                    tasks.add(task);
+                }
+            }
+
+            Assertions.assertTrue(submissions.get() > 0, "uncached batch scan 
must use bounded manifest executor");
+            Assertions.assertEquals(2, tasks.size());
+            Map<String, FileScanTask> byPath = new HashMap<>();
+            for (FileScanTask task : tasks) {
+                byPath.put(task.file().path().toString(), task);
+            }
+
+            FileScanTask task1 = byPath.get("/d/file_1.parquet");
+            FileScanTask task2 = byPath.get("/d/file_2.parquet");
+            Assertions.assertNotNull(task1);
+            Assertions.assertNotNull(task2);
+            Assertions.assertEquals(1, task1.deletes().size());
+            Assertions.assertEquals("/d/pos_del.parquet", 
task1.deletes().get(0).path().toString());
+            Assertions.assertEquals(1, task2.deletes().size());
+            Assertions.assertEquals("/d/eq_del.parquet", 
task2.deletes().get(0).path().toString());
+
+            // Unrequested column stats (including equality key bounds) must 
be stripped from final tasks.
+            Assertions.assertNull(task1.file().lowerBounds());
+            Assertions.assertNull(task2.file().lowerBounds());
+            Assertions.assertNull(task2.file().upperBounds());
+        }
+    }
+
+    @Test
+    void 
uncachedSingleManifestAndNonBatchFallbackToSdkWithoutUsingManifestExecutor() 
throws Exception {
+        Table singleManifestTable = createTable("single_manifest", SCHEMA, 
PartitionSpec.unpartitioned(),
+                Collections.singletonMap("format-version", "2"));
+        
singleManifestTable.newFastAppend().appendFile(DataFiles.builder(singleManifestTable.spec())
+                .withPath("/d/only.parquet").withFormat(FileFormat.PARQUET)
+                .withFileSizeInBytes(100).withRecordCount(1).build()).commit();
+
+        AtomicInteger submissions = new AtomicInteger();
+        Executor recordingExecutor = task -> {
+            submissions.incrementAndGet();
+            task.run();
+        };
+
+        // Single manifest in batch mode -> stays on SDK streaming.
+        IcebergScanNode singleNode = createScanNode(singleManifestTable, true, 
recordingExecutor);
+        try (CloseableIterable<FileScanTask> planned = 
singleNode.planFileScanTaskWithoutReuse(
+                DorisDataTableScan.wrap(singleManifestTable.newScan()))) {
+            List<FileScanTask> tasks = new ArrayList<>();
+            planned.forEach(tasks::add);
+            Assertions.assertEquals(1, tasks.size());
+        }
+        Assertions.assertEquals(0, submissions.get());
+
+        // Multiple manifests but non-batch mode -> stays on SDK path.
+        
singleManifestTable.newFastAppend().appendFile(DataFiles.builder(singleManifestTable.spec())
+                .withPath("/d/second.parquet").withFormat(FileFormat.PARQUET)
+                .withFileSizeInBytes(100).withRecordCount(1).build()).commit();
+        IcebergScanNode nonBatchNode = createScanNode(singleManifestTable, 
false, recordingExecutor);
+        try (CloseableIterable<FileScanTask> planned = 
nonBatchNode.planFileScanTaskWithoutReuse(
+                DorisDataTableScan.wrap(singleManifestTable.newScan()))) {
+            List<FileScanTask> tasks = new ArrayList<>();
+            planned.forEach(tasks::add);
+            Assertions.assertEquals(2, tasks.size());
+        }
+        Assertions.assertEquals(0, submissions.get());
+    }
+
+    @Test
+    void uncachedProjectionDoesNotMutateCachedReadStatistics() throws 
Exception {
+        Table table = createTable("projection_isolation", SCHEMA, 
PartitionSpec.unpartitioned(),
+                Collections.singletonMap("format-version", "2"));
+        Map<Integer, ByteBuffer> bounds = Collections.singletonMap(
+                1, Conversions.toByteBuffer(Types.IntegerType.get(), 42));
+        table.newFastAppend().appendFile(DataFiles.builder(table.spec())
+                
.withPath("/d/proj.parquet").withFormat(FileFormat.PARQUET).withFileSizeInBytes(100)
+                .withMetrics(new Metrics(5L, null, null, null, null, bounds, 
bounds)).build()).commit();
+
+        ManifestFile manifest = 
table.currentSnapshot().dataManifests(table.io()).get(0);
+        ManifestCacheValue full = IcebergManifestLoader.readForCache(manifest, 
table, manifest.content(), false);
+        DorisDataTableScan.DataFileProjection projection = 
DorisDataTableScan.dataFileProjection(
+                table.newScan(), Collections.emptySet(), false);
+        ManifestCacheValue projected = IcebergManifestLoader.uncachedLoader(
+                table, projection.manifestColumns(), null, 
projection::copyForManifest, () -> { }).apply(manifest);
+
+        Assertions.assertEquals(bounds, 
full.getDataFiles().get(0).lowerBounds());
+        Assertions.assertNull(projected.getDataFiles().get(0).lowerBounds());
+        Assertions.assertEquals(full.getDataFiles().get(0).path(), 
projected.getDataFiles().get(0).path());
+        Assertions.assertEquals(full.getDataFiles().get(0).recordCount(), 
projected.getDataFiles().get(0).recordCount());
+    }
+
+    @Test
+    void 
rewrittenManifestAfterDroppingPartitionSourcePreservesDeletesInUncachedScan() 
throws Exception {
+        PartitionSpec spec = 
PartitionSpec.builderFor(SCHEMA).identity("p").build();
+        Table table = createTable("dropped_partition_source_rewrite", SCHEMA, 
spec,
+                Collections.singletonMap("format-version", "2"));
+        table.newFastAppend().appendFile(DataFiles.builder(spec)
+                .withPath("/d/p1_a.parquet").withFormat(FileFormat.PARQUET)
+                
.withPartitionPath("p=alpha").withFileSizeInBytes(100).withRecordCount(2).build()).commit();
+        table.newFastAppend().appendFile(DataFiles.builder(spec)
+                .withPath("/d/p1_b.parquet").withFormat(FileFormat.PARQUET)
+                
.withPartitionPath("p=beta").withFileSizeInBytes(100).withRecordCount(2).build()).commit();
+
+        // Add a position delete referencing the historical partition file 
before dropping the source column.
+        Map<Integer, ByteBuffer> delBounds = Collections.singletonMap(
+                MetadataColumns.DELETE_FILE_PATH.fieldId(),
+                Conversions.toByteBuffer(Types.StringType.get(), 
"/d/p1_a.parquet"));
+        DeleteFile posDelete = 
FileMetadata.deleteFileBuilder(spec).ofPositionDeletes()
+                .withPath("/d/p1_a_del.parquet").withFormat(FileFormat.PARQUET)
+                .withPartitionPath("p=alpha").withFileSizeInBytes(64)
+                .withMetrics(new Metrics(1L, null, null, null, null, 
delBounds, delBounds)).build();
+        table.newRowDelta().addDeletes(posDelete).commit();
+
+        // Drop the partition field and its source column, then rewrite 
manifests so the header carries
+        // the new schema alongside the historical spec.
+        table.updateSpec().removeField("p").commit();
+        table.updateSchema().deleteColumn("p").commit();
+        table.rewriteManifests().rewriteIf(m -> true).clusterBy(f -> 
"all").commit();
+        long rewriteSnapshotId = table.currentSnapshot().snapshotId();
+        List<ManifestFile> rewrittenDataManifests = 
table.currentSnapshot().dataManifests(table.io());
+        Assertions.assertEquals(1, rewrittenDataManifests.size());
+        Assertions.assertEquals(rewriteSnapshotId, 
rewrittenDataManifests.get(0).snapshotId());
+
+        // Add another data manifest so the scan has >1 data manifests and 
enters the bounded uncached path.
+        table.newFastAppend().appendFile(DataFiles.builder(table.spec())
+                .withPath("/d/unpart.parquet").withFormat(FileFormat.PARQUET)
+                .withFileSizeInBytes(100).withRecordCount(3).build()).commit();
+
+        AtomicInteger submissions = new AtomicInteger();
+        try (FairTaskExecutor pool = newPool(2)) {
+            Executor recordingExecutor = task -> {
+                submissions.incrementAndGet();
+                pool.newGroup(16).execute(task);
+            };
+            IcebergScanNode node = createScanNode(table, true, 
recordingExecutor);
+            TableScan scan = DorisDataTableScan.wrap(table.newScan());
+            Map<String, FileScanTask> byPath = new HashMap<>();
+            try (CloseableIterable<FileScanTask> planned = 
node.planFileScanTaskWithoutReuse(scan)) {
+                for (FileScanTask task : planned) {
+                    byPath.put(task.file().path().toString(), task);
+                }
+            }
+            Assertions.assertTrue(submissions.get() > 0);
+            Assertions.assertEquals(3, byPath.size());
+            Assertions.assertEquals(1, 
byPath.get("/d/p1_a.parquet").deletes().size());
+            Assertions.assertEquals("/d/p1_a_del.parquet",
+                    
byPath.get("/d/p1_a.parquet").deletes().get(0).path().toString());
+            Assertions.assertEquals(0, 
byPath.get("/d/p1_b.parquet").deletes().size());
+        }
+    }
+
+    @Test
+    void uncachedLoaderPropagatesCancellationImmediately() throws Exception {
+        Table table = createTable("cancel_check", SCHEMA, 
PartitionSpec.unpartitioned(),
+                Collections.singletonMap("format-version", "2"));
+        table.newFastAppend().appendFile(DataFiles.builder(table.spec())
+                .withPath("/d/c1.parquet").withFormat(FileFormat.PARQUET)
+                .withFileSizeInBytes(100).withRecordCount(1).build()).commit();
+
+        ManifestFile manifest = 
table.currentSnapshot().dataManifests(table.io()).get(0);
+        AtomicBoolean cancelled = new AtomicBoolean(true);
+        Assertions.assertThrows(CancellationException.class, () -> 
IcebergManifestLoader.uncachedLoader(
+                table, null, null, () -> {
+                    if (cancelled.get()) {
+                        throw new CancellationException("cancelled");
+                    }
+                }).apply(manifest));
+    }
+
+    @Test
+    void uncachedLoaderClosesStreamWhenCancelledBetweenNewStreamAndGetLength() 
throws Exception {
+        Table table = createTable("cancel_after_open", SCHEMA, 
PartitionSpec.unpartitioned(),
+                Collections.singletonMap("format-version", "2"));
+        table.newFastAppend().appendFile(DataFiles.builder(table.spec())
+                .withPath("/d/c2.parquet").withFormat(FileFormat.PARQUET)
+                .withFileSizeInBytes(100).withRecordCount(1).build()).commit();
+
+        ManifestFile manifest = 
table.currentSnapshot().dataManifests(table.io()).get(0);
+        FileIO delegateIo = table.io();
+        AtomicBoolean cancelled = new AtomicBoolean(false);
+        AtomicInteger streamsOpened = new AtomicInteger();
+        AtomicInteger streamsClosed = new AtomicInteger();
+        AtomicBoolean delegateIoClosed = new AtomicBoolean(false);
+
+        FileIO trackingIo = new FileIO() {
+            @Override
+            public InputFile newInputFile(String path) {
+                return wrap(delegateIo.newInputFile(path));
+            }
+
+            @Override
+            public InputFile newInputFile(String path, long length) {
+                return wrap(delegateIo.newInputFile(path, length));
+            }
+
+            @Override
+            public InputFile newInputFile(ManifestFile file) {
+                return wrap(delegateIo.newInputFile(file));
+            }
+
+            private InputFile wrap(InputFile delegateInput) {
+                return new InputFile() {
+                    @Override
+                    public long getLength() {
+                        return delegateInput.getLength();
+                    }
+
+                    @Override
+                    public SeekableInputStream newStream() {
+                        SeekableInputStream delegateStream = 
delegateInput.newStream();
+                        streamsOpened.incrementAndGet();
+                        // Cancel immediately after the stream opens, before 
AvroIterable calls getLength().
+                        cancelled.set(true);
+                        return new SeekableInputStream() {
+                            @Override
+                            public long getPos() throws IOException {
+                                return delegateStream.getPos();
+                            }
+
+                            @Override
+                            public void seek(long newPos) throws IOException {
+                                delegateStream.seek(newPos);
+                            }
+
+                            @Override
+                            public int read() throws IOException {
+                                return delegateStream.read();
+                            }
+
+                            @Override
+                            public int read(byte[] b, int off, int len) throws 
IOException {
+                                return delegateStream.read(b, off, len);
+                            }
+
+                            @Override
+                            public void close() throws IOException {
+                                streamsClosed.incrementAndGet();
+                                delegateStream.close();
+                            }
+                        };
+                    }
+
+                    @Override
+                    public String location() {
+                        return delegateInput.location();
+                    }
+
+                    @Override
+                    public boolean exists() {
+                        return delegateInput.exists();
+                    }
+                };
+            }
+
+            @Override
+            public OutputFile newOutputFile(String path) {
+                return delegateIo.newOutputFile(path);
+            }
+
+            @Override
+            public void deleteFile(String path) {
+                delegateIo.deleteFile(path);
+            }
+
+            @Override
+            public Map<String, String> properties() {
+                return delegateIo.properties();
+            }
+
+            @Override
+            public void close() {
+                delegateIoClosed.set(true);
+            }
+        };
+
+        Table mockedTable = Mockito.spy(table);
+        Mockito.doReturn(trackingIo).when(mockedTable).io();
+
+        Assertions.assertThrows(CancellationException.class, () -> 
IcebergManifestLoader.uncachedLoader(
+                mockedTable, null, null, () -> {
+                    if (cancelled.get()) {
+                        throw new CancellationException("cancelled after 
stream open");
+                    }
+                }).apply(manifest));
+        Assertions.assertEquals(1, streamsOpened.get(), "stream should have 
been opened before cancellation");
+        Assertions.assertEquals(1, streamsClosed.get(), "opened stream must be 
closed on cancellation");
+        Assertions.assertFalse(delegateIoClosed.get(), "shared catalog FileIO 
must never be closed");
+    }
+
+    private Table createTable(String name, Schema schema, PartitionSpec spec, 
Map<String, String> properties) {
+        HadoopTables tables = new HadoopTables(new Configuration());
+        return tables.create(schema, spec, properties, 
tempDir.resolve(name).toString());
+    }
+
+    private IcebergScanNode createScanNode(Table table, boolean batchMode, 
Executor manifestExecutor)
+            throws Exception {
+        SessionVariable sv = new SessionVariable();
+        sv.setMaxSplitSize(64L * 1024 * 1024);
+
+        IcebergScanNode node = new IcebergScanNode(
+                new PlanNodeId(1), new TupleDescriptor(new TupleId(1)), sv, 
ScanContext.EMPTY) {
+            @Override
+            public boolean isBatchMode() {
+                return batchMode;
+            }
+
+            @Override
+            protected Executor getManifestReadExecutor() {
+                return manifestExecutor;
+            }
+        };
+
+        IcebergExternalCatalog catalog = 
Mockito.mock(IcebergExternalCatalog.class);
+        
Mockito.when(catalog.getProperties()).thenReturn(Collections.emptyMap());
+        ExternalTable dorisTable = Mockito.mock(ExternalTable.class);
+        Mockito.when(dorisTable.getCatalog()).thenReturn(catalog);
+
+        IcebergSource source = Mockito.mock(IcebergSource.class);
+        Mockito.when(source.getCatalog()).thenReturn(catalog);
+        Mockito.when(source.getTargetTable()).thenReturn(dorisTable);
+
+        setField(node, "icebergTable", table);
+        setField(node, "source", source);
+        setField(node, "preExecutionAuthenticator", new 
ExecutionAuthenticator() { });
+        setField(node, "conjuncts", new ArrayList<>());
+        IcebergSnapshotCacheValue frozenSource = new IcebergSnapshotCacheValue(
+                new IcebergPartitionInfo(Collections.emptyMap(), 
Collections.emptyMap(), Collections.emptyMap()),
+                new IcebergSnapshot(table.currentSnapshot().snapshotId(), 
table.schema().schemaId()))
+                .bindSourceGeneration(new IcebergTableCacheValue(table));
+        setField(node, "frozenGenerationSource", frozenSource);
+        FederationBackendPolicy policy = 
Mockito.mock(FederationBackendPolicy.class);
+        Mockito.when(policy.getBackends()).thenReturn(Collections.emptyList());
+        Mockito.when(policy.numBackends()).thenReturn(0);
+        setField(node, "backendPolicy", policy);
+        return node;
+    }
+
+    private static void setField(Object target, String name, Object value) 
throws Exception {
+        Class<?> cls = target.getClass();
+        while (cls != null) {
+            try {
+                Field field = cls.getDeclaredField(name);
+                field.setAccessible(true);
+                field.set(target, value);
+                return;
+            } catch (NoSuchFieldException ignored) {
+                cls = cls.getSuperclass();
+            }
+        }
+        throw new NoSuchFieldException(name);
+    }
+
+    private static FairTaskExecutor newPool(int workers) {
+        return new FairTaskExecutor(workers, task -> {
+            Thread t = new Thread(task);
+            t.setDaemon(true);
+            return t;
+        });
+    }
+
+    private static ManifestFile manifestWithFileCounts(Integer added, Integer 
existing, Integer deleted) {
+        return (ManifestFile) 
Proxy.newProxyInstance(ManifestFile.class.getClassLoader(),
+                new Class<?>[] {ManifestFile.class}, (proxy, method, args) -> {
+                    if (method.getName().equals("addedFilesCount")) {
+                        return added;
+                    }
+                    if (method.getName().equals("existingFilesCount")) {
+                        return existing;
+                    }
+                    if (method.getName().equals("deletedFilesCount")) {
+                        return deleted;
+                    }
+                    throw new UnsupportedOperationException(method.getName());
+                });
+    }
+}


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to