hello-stephen commented on code in PR #71411:
URL: https://github.com/apache/doris/pull/71411#discussion_r4794957415


##########
fe/fe-iceberg-common/src/main/java/org/apache/iceberg/io/NativeGcsResolvingFileIO.java:
##########
@@ -17,42 +17,211 @@
 
 package org.apache.iceberg.io;
 
+import org.apache.iceberg.CatalogUtil;
+import org.apache.iceberg.gcp.GCPProperties;
+import org.apache.iceberg.gcp.gcs.PrefixAwareGcsFileIO;
+
+import org.apache.doris.iceberg.GcsOAuthTokenValidator;
+import org.apache.hadoop.conf.Configuration;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
 import java.util.Map;
 
 /**
- * A {@link ResolvingFileIO} that preserves the legacy Hadoop GCS path unless 
SDK storage options exist.
+ * A {@link ResolvingFileIO} that preserves Hadoop GCS credentials unless SDK 
credentials override them.
  *
- * <p>Adding iceberg-gcp makes the SDK route these locations to GCSFileIO, 
which does not read the
- * {@code fs.s3a.*} HMAC settings Doris supplies. Both FE and the BE metadata 
scanner must load this
- * implementation because its class name is carried inside serialized Iceberg 
scan tasks. Explicit
- * {@code gcs.*} storage options retain the SDK path, including options 
supplied after FE selection.
+ * <p>Doris configures GCS access as Hadoop properties: native credentials 
(credential provider type,
+ * service-account impersonation) as {@code fs.gs.*}, and HMAC 
interoperability keys or anonymous access as
+ * {@code fs.s3a.*}. Only the Hadoop filesystems read them. Upstream 
ResolvingFileIO
+ * routes {@code gs} to {@code GCSFileIO} whenever iceberg-gcp is on the 
classpath and falls back to
+ * HadoopFileIO only when that class is missing. Both runtimes bundle 
iceberg-gcp for the REST
+ * catalog's {@code GoogleAuthManager} and an explicitly chosen {@code 
GCSFileIO}, so this class pins
+ * the default routing instead of relying on that class being absent. SDK 
credentials and their storage options retain
+ * the SDK path, including credentials received after FE selection. Other 
schemes resolve as upstream.
  *
- * <p>The SDK package is required because {@code implFromLocation} is 
package-private. It also keeps
- * this class and iceberg-core in the same class loader on both sides of a 
metadata scan.
+ * <p>It lives in {@code org.apache.iceberg.io} because {@code 
implFromLocation} is package-private; the
+ * override only takes effect when this class and iceberg-core share a class 
loader, which holds for the
+ * FE catalog and the BE metadata scanner, both of which bundle iceberg-core 
themselves. Its class
+ * name is part of serialized Iceberg scan tasks, so it must stay loadable on 
both sides.
  */
 public class NativeGcsResolvingFileIO extends ResolvingFileIO {
     private static final long serialVersionUID = 1L;
 
     private static final String GCS_FILE_IO_IMPL = 
"org.apache.iceberg.gcp.gcs.GCSFileIO";
     private static final String HADOOP_FILE_IO_IMPL = 
"org.apache.iceberg.hadoop.HadoopFileIO";
 
-    public static boolean hasSdkGcsProperties(Map<String, String> properties) {
-        return properties.entrySet().stream()
-                .anyMatch(entry -> entry.getKey().startsWith("gcs.") && 
entry.getValue() != null);
-    }
+    // Clients are bounded by credential prefixes, not file locations, and are 
rebuilt after serialization.
+    private transient Map<String, DelegateFileIO> scopedIos;
+    private volatile Boolean hadoopGcsConfigured;
+    private boolean closed;
 
     @Override
-    String implFromLocation(String location) {
+    synchronized String implFromLocation(String location) {
         String impl = super.implFromLocation(location);
         if (!GCS_FILE_IO_IMPL.equals(impl)) {
             return impl;
         }
-        // REST/table options and matching vended credentials can arrive after 
FE chose this resolver.
-        // HadoopFileIO ignores SDK encryption and billing options, so those 
must keep the native path.
-        if (hasSdkGcsProperties(properties()) || 
credentials().stream().anyMatch(credential ->
-                location.startsWith(credential.prefix()) && 
hasSdkGcsProperties(credential.config()))) {
+        StorageCredential matching = matchingCredential(location);
+        Map<String, String> scope = matching == null ? Collections.emptyMap() 
: matching.config();
+        // Validate the effective scope before choosing an identity: a present 
null token is not an absent token.
+        GcsOAuthTokenValidator.validate(properties(), scope);
+        Map<String, String> effective = effectiveProperties(scope);
+        String impersonation = 
effective.get("gcs.impersonate.service-account");
+        boolean sdkIdentity = effective.containsKey("gcs.oauth2.token")
+                || Boolean.parseBoolean(effective.get("gcs.no-auth"))
+                || (impersonation != null && !impersonation.isEmpty());
+        if (sdkIdentity) {
             return GCS_FILE_IO_IMPL;
         }
-        return HADOOP_FILE_IO_IMPL;
+        // Project selection is not authentication. SDK-only options must 
never silently replace HMAC with ADC.
+        if (properties().containsKey("gs.access_key") || 
hasHadoopGcsConfiguration()) {

Review Comment:
   [P2] Don’t infer a Hadoop identity from a cache setting. A REST catalog 
using operator SDK application default credentials with `gcs.user-project` 
worked on the base even if its Hadoop XML set only 
`fs.gs.impl.disable.cache=true`. `hasHadoopGcsConfiguration()` now treats that 
setting as an identity, so this branch throws for `gcs.user-project` before 
reaching the SDK. Distinguish a configured Hadoop credential source from 
tuning-only properties and test the selected delegate or actual read in 
`IcebergGcsSdkOptionsTest`.



##########
regression-test/suites/external_table_p0/iceberg/test_iceberg_nested_predicate_cache.groovy:
##########
@@ -0,0 +1,160 @@
+// 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.
+
+import org.apache.doris.regression.action.ProfileAction
+
+suite("test_iceberg_nested_predicate_cache", 
"p0,external,iceberg,external_docker,external_docker_iceberg") {
+    String sdk = context.config.otherConfigs.get("icebergFixtureSdkDir")
+    String warehouse = 
context.config.otherConfigs.get("icebergFixtureWarehouse")
+    boolean local = sdk != null && warehouse != null
+    assertTrue((sdk == null) == (warehouse == null), "Set both local fixture 
SDK and warehouse")
+    if (!local && 
!"true".equalsIgnoreCase(context.config.otherConfigs.get("enableIcebergTest"))) 
{
+        logger.info("disable iceberg test")
+        return
+    }
+    def execute = { List<String> command ->
+        StringBuilder stdout = new StringBuilder()
+        StringBuilder stderr = new StringBuilder()
+        // List<String> can still contain GStrings; ProcessBuilder copies its 
elements into String[].
+        def process = new ProcessBuilder(command.collect { it.toString() 
}).start()
+        Thread outputReader = process.consumeProcessOutputStream(stdout)
+        Thread errorReader = process.consumeProcessErrorStream(stderr)
+        process.waitForOrKill(300000)
+        // Process exit can precede output-consumer completion; read every SDK 
marker before checking.
+        outputReader.join()
+        errorReader.join()
+        assertEquals(0, process.exitValue(), "SDK command failed: 
${stderr}\n${stdout}")
+        return stdout.toString()
+    }
+    def shellQuote = { String value -> "'" + value.replace("'", "'\"'\"'") + 
"'" }
+    File source = new File(context.file.parentFile, 
"cache_data/CreateNestedPredicateCacheFixture.java")
+    File classes
+    String container
+    String directory = "/tmp/doris_nested_cache_${UUID.randomUUID()}"
+    String docker = context.config.otherConfigs.get("externalDockerCommand") 
?: "docker"
+    def sdkRun = { String phase ->
+        if (local) {
+            String bin = System.getProperty("java.home") + "/bin/"
+            return execute([bin + "java", "-cp", classes.absolutePath + ":" + 
sdk + "/*",
+                    "CreateNestedPredicateCacheFixture", phase, 
"nested_predicate_cache", warehouse])
+        }
+        String command = "java -cp \"${directory}:/opt/spark/jars/*\" " +
+                "CreateNestedPredicateCacheFixture ${phase} 
nested_predicate_cache"
+        return execute(["bash", "-c", "${docker} exec ${shellQuote(container)} 
bash -lc ${shellQuote(command)}"])
+    }
+    def settings = ["enable_sql_cache", "enable_query_cache", 
"enable_condition_cache", "enable_profile", "profile_level", 
"enable_file_scanner_v2"]
+            .collectEntries { name -> [(name): (sql "SELECT 
@@${name}")[0][0].toString()] }
+    try {
+        if (local) {
+            assertTrue(warehouse.startsWith("file:"), "Local SDK mode requires 
a shared file warehouse")
+            classes = new File(context.file.parentFile, 
".nested_cache_${UUID.randomUUID()}")
+            assertTrue(classes.mkdirs())
+            execute([System.getProperty("java.home") + "/bin/javac", "-cp", 
sdk + "/*", "-d",
+                    classes.absolutePath, source.absolutePath])
+        } else {
+            container = 
context.config.otherConfigs.get("icebergSparkContainer")
+            if (container == null || container.isEmpty()) {
+                def candidates = execute(["bash", "-c", "${docker} ps --format 
'{{.ID}}'"]).readLines()
+                def matches = candidates.findAll { String candidate ->
+                    def probe = new ProcessBuilder("bash", "-c", "${docker} 
exec ${shellQuote(candidate)} " +
+                            "bash -lc 'test -f /mnt/SUCCESS && command -v 
spark-sql >/dev/null'").start()
+                    probe.consumeProcessOutput(new StringBuilder(), new 
StringBuilder())
+                    probe.waitForOrKill(30000)
+                    return probe.exitValue() == 0
+                }
+                assertEquals(1, matches.size(), "Set icebergSparkContainer to 
the Spark Iceberg container")
+                container = matches[0]
+            }
+            String encoded = 
source.getText("UTF-8").getBytes("UTF-8").encodeBase64().toString()
+            String command = "mkdir -p ${directory} && echo ${encoded} | 
base64 -d > ${directory}/${source.name} && " +
+                    "javac -cp \"/opt/spark/jars/*\" -d ${directory} 
${directory}/${source.name}"
+            execute(["bash", "-c", "${docker} exec ${shellQuote(container)} 
bash -lc ${shellQuote(command)}"])
+        }
+        assertTrue(sdkRun("create").contains("CACHE_FIXTURE rows=8192 x=0"))
+        sql "DROP CATALOG IF EXISTS nested_predicate_cache_catalog"
+        if (local) {
+            sql """CREATE CATALOG nested_predicate_cache_catalog PROPERTIES (
+                    'type'='iceberg', 'iceberg.catalog.type'='hadoop',
+                    'warehouse'='${warehouse.replace("'", "''")}')"""
+        } else {
+            String host = context.config.otherConfigs.get("externalEnvIp")
+            String rest = 
context.config.otherConfigs.get("iceberg_rest_uri_port")
+            String minio = 
context.config.otherConfigs.get("iceberg_minio_port")
+            sql """CREATE CATALOG nested_predicate_cache_catalog PROPERTIES (
+                    'type'='iceberg', 'iceberg.catalog.type'='rest', 
'uri'='http://${host}:${rest}',
+                    's3.access_key'='admin', 's3.secret_key'='password',
+                    's3.endpoint'='http://${host}:${minio}', 
's3.region'='us-east-1')"""
+        }
+        sql "SET enable_sql_cache=false"
+        sql "SET enable_query_cache=false"
+        sql "SET enable_condition_cache=true"
+        sql "SET enable_file_scanner_v2=true"
+        sql "SET profile_level=2"
+        def profileAction = new ProfileAction(context)
+        def assertCacheHit = { String token, boolean expectPruning ->
+            String profile = profileAction.getProfileBySql(token, 
["ConditionCacheHit", "ConditionCacheFilteredRows"])
+            def hits = profile =~ /ConditionCacheHit:\s*([0-9,]+)/
+            assertTrue(hits.findAll().any { Long.parseLong(it[1].replace(",", 
"")) > 0 },
+                    "No positive condition-cache hit; the regression must 
exercise cache reuse: ${profile}")
+            if (expectPruning) {
+                def filtered = profile =~ 
/ConditionCacheFilteredRows:\s*([0-9,]+)/
+                assertTrue(filtered.findAll().any { 
Long.parseLong(it[1].replace(",", "")) > 0 },
+                        "The Q-only bitmap must still prune nonmatching 
granules: ${profile}")
+            }
+        }
+        String table = 
"nested_predicate_cache_catalog.nested_predicate_cache.nested_default"
+        String predicate = "mod(element_at(s,'x'),2)=1 AND mod(k,3)=1"
+        String warmToken = "nested_cache_warm_${UUID.randomUUID()}"
+        // Project the whole parent: its field ID must stay stable while the 
child's ID changes.
+        String warm = "SELECT /* ${warmToken} */ s,k FROM ${table} WHERE 
${predicate}"
+        sql "SET enable_profile=false"
+        5.times { sql warm }
+        sql "SET enable_profile=true"
+        sql warm
+        assertCacheHit(warmToken, true)
+        qt_original_rows "SELECT count(*) FROM ${table} WHERE ${predicate}"
+
+        String evolved = sdkRun("evolve")
+        assertTrue(evolved.contains("CACHE_FIXTURE rows=8192 x=9"))
+        assertTrue(evolved.contains("CACHE_EVOLVED root=1 old=3 new=5"))
+        sql "REFRESH TABLE ${table}"
+        String evolvedToken = "nested_cache_evolved_${UUID.randomUUID()}"
+        String query = "SELECT /* ${evolvedToken} */ s,k FROM ${table} WHERE 
${predicate}"
+        sql "SET enable_profile=false"
+        sql "SET enable_condition_cache=false"
+        def expected = sql(query)
+        qt_evolved_defaults """SELECT 
element_at(s,'x'),element_at(s,'keep'),k,count(*)
+                FROM ${table} WHERE ${predicate} GROUP BY 1,2,3 ORDER BY 
1,2,3"""
+        qt_null_parents "SELECT count(*) FROM ${table} WHERE s IS NULL"
+        sql "SET enable_condition_cache=true"
+        def first = sql(query)
+        assertTrue(expected == first, "A Q-only request reused a P AND Q 
bitmap: " +
+                "expected ${expected.size()} rows, got ${first.size()}; sample 
${first.take(3)}")
+        sql "SET enable_profile=true"
+        def repeated = sql(query)
+        assertTrue(expected == repeated, "Cached rows differ from the full 
scan: " +
+                "expected ${expected.size()} rows, got ${repeated.size()}; 
sample ${repeated.take(3)}")
+        assertCacheHit(evolvedToken, true)

Review Comment:
   [P3] Keep all warm and evolved scans on the same backend. With both 
`enable_file_cache` and `use_consistent_hash_for_external_scan` off, 
round-robin scheduling can select a different BE on each query, for example 
with two eligible BEs on one host. The profiled repeat can then miss a 
correctly populated BE-local cache, and the first evolved read can miss the 
stale bitmap the test is meant to catch. Set and restore consistent routing for 
this suite, or pin the test to one eligible BE.



##########
fe/fe-core/src/main/java/org/apache/doris/datasource/property/metastore/AbstractIcebergProperties.java:
##########
@@ -290,12 +290,9 @@ protected void 
preserveHadoopGcsFileIO(List<StorageProperties> storageProperties
         if (!ResolvingFileIO.class.getName().equals(ioImpl) && !(rest && 
ioImpl == null)) {
             return;
         }
-        if (rest && ((IcebergRestProperties) 
this).isIcebergRestVendedCredentialsEnabled()) {
-            return;
-        }
-        // SDK storage options (including encryption and billing) must retain 
their native semantics.
-        // REST-only gcp.auth.* options do not select a storage identity.
-        if (NativeGcsResolvingFileIO.hasSdkGcsProperties(fileIOProperties)) {
+        if (rest) {
+            // Table-load credentials arrive after catalog initialization; 
validate their effective scope at use.
+            fileIOProperties.put(CatalogProperties.FILE_IO_IMPL, 
NativeGcsResolvingFileIO.class.getName());

Review Comment:
   [P2] Preserve the REST server’s default FileIO. A catalog with no client 
`io-impl` now sends `NativeGcsResolvingFileIO` into Iceberg’s config merge as a 
client choice, so it masks `/v1/config`’s `defaults.io-impl`. For example, a 
server that defaults to `HadoopFileIO` for `s3a://` metadata can have working 
Hadoop-only credentials in `core-site.xml`. This backport sends those reads to 
`S3FileIO`, which does not use those Hadoop credentials. Install the 
compatibility resolver only if the effective choice after the REST merge is 
absent or generic. [Iceberg 1.11.0 config 
precedence](https://github.com/apache/iceberg/blob/apache-iceberg-1.11.0/core/src/main/java/org/apache/iceberg/rest/responses/ConfigResponse.java#L108-L126)



##########
regression-test/suites/external_table_p0/iceberg/test_iceberg_manifest_row_lineage_cache.groovy:
##########
@@ -0,0 +1,194 @@
+// 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.
+
+import com.amazonaws.auth.AWSStaticCredentialsProvider
+import com.amazonaws.auth.BasicAWSCredentials
+import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration
+import com.amazonaws.services.s3.AmazonS3ClientBuilder
+import groovy.json.JsonSlurper
+import org.apache.avro.file.DataFileStream
+import org.apache.avro.generic.GenericDatumReader
+
+suite("test_iceberg_manifest_row_lineage_cache", 
"p0,external,iceberg,external_docker,external_docker_iceberg") {
+    if 
(!"true".equalsIgnoreCase(context.config.otherConfigs.get("enableIcebergTest")))
 {
+        return
+    }
+
+    String externalEnvIp = context.config.otherConfigs.get("externalEnvIp")
+    String restPort = context.config.otherConfigs.get("iceberg_rest_uri_port")
+    String minioPort = context.config.otherConfigs.get("iceberg_minio_port")
+    String writerCatalog = "manifest_lineage_writer"
+    String warmCatalog = "manifest_lineage_warm"
+    String coldCatalog = "manifest_lineage_cold"
+    String dbName = "manifest_row_lineage_cache_db"
+    def catalogs = [writerCatalog, warmCatalog, coldCatalog]
+    def oldBatchMode = sql("show variables like 
'enable_external_table_batch_mode'")[0][1]
+    def oldBatchSize = sql("show variables like 
'num_files_in_batch_mode'")[0][1]
+    def minio = AmazonS3ClientBuilder.standard()
+            .withEndpointConfiguration(new 
EndpointConfiguration("http://${externalEnvIp}:${minioPort}";, "us-east-1"))
+            .withPathStyleAccessEnabled(true)
+            .withCredentials(new AWSStaticCredentialsProvider(new 
BasicAWSCredentials("admin", "password")))
+            .build()
+
+    def manifestState = { table ->
+        def connection = new 
URL("http://${externalEnvIp}:${restPort}/v1/namespaces/${dbName}/tables/${table}";)
+                .openConnection()
+        connection.connectTimeout = 10000
+        connection.readTimeout = 10000
+        def metadata
+        try {
+            metadata = connection.inputStream.withCloseable { new 
JsonSlurper().parse(it).metadata }
+        } finally {
+            connection.disconnect()
+        }
+        def snapshot = metadata.snapshots.find { it['snapshot-id'] == 
metadata['current-snapshot-id'] }
+        assertTrue(snapshot != null)
+        def location = new URI(snapshot['manifest-list'].toString())
+        Map inheritedIds = [:]
+        // Read the committed descriptor independently of Doris's 
parsed-manifest cache and metadata scanner.
+        minio.getObject(location.host, 
location.path.substring(1)).withCloseable { object ->
+            new DataFileStream(object.objectContent, new 
GenericDatumReader()).withCloseable { reader ->
+                reader.each { record ->
+                    inheritedIds[record.get('manifest_path').toString()] =
+                            record.schema.getField('first_row_id') == null ? 
null : record.get('first_row_id')
+                }
+            }
+        }
+        return [snapshotId: metadata['current-snapshot-id'], firstRowIds: 
inheritedIds]
+    }
+
+    def assertCacheHit = { query ->
+        String plan = sql("explain verbose ${query}").collect { it[0] 
}.join("\n")
+        def stats = plan =~ /manifest cache: hits=(\d+), misses=(\d+), 
failures=(\d+)/
+        assertTrue(stats.find(), plan)
+        assertTrue(stats.group(1).toLong() > 0, plan)
+        assertEquals(0L, stats.group(3).toLong())
+    }
+
+    def refresh = { catalog, table -> sql "refresh table 
${catalog}.${dbName}.${table}" }
+    def lineage = { catalog, table, suffix = "" ->
+        return sql("""select id, _row_id, _last_updated_sequence_number
+            from ${catalog}.${dbName}.${table}${suffix} order by id""")
+    }
+    def assertSdkMatches = { table ->
+        refresh(writerCatalog, table)
+        def expected = lineage(writerCatalog, table)
+        [warmCatalog, coldCatalog].each { catalog ->
+            refresh(catalog, table)
+            assertEquals(expected, lineage(catalog, table))
+        }
+        return expected.collectEntries { row ->
+            [(row[0].toString().toInteger()): [row[1].toString().toLong(), 
row[2].toString().toLong()]]
+        }
+    }
+
+    try {
+        catalogs.each { catalog ->
+            sql "drop catalog if exists ${catalog}"
+            sql """create catalog ${catalog} properties (
+                'type' = 'iceberg',
+                'iceberg.catalog.type' = 'rest',
+                'uri' = 'http://${externalEnvIp}:${restPort}',
+                's3.access_key' = 'admin',
+                's3.secret_key' = 'password',
+                's3.endpoint' = 'http://${externalEnvIp}:${minioPort}',
+                's3.region' = 'us-east-1',
+                'meta.cache.iceberg.manifest.enable' = '${catalog != 
writerCatalog}'
+            )"""
+        }
+        sql "create database if not exists ${writerCatalog}.${dbName}"
+        sql "set num_files_in_batch_mode = 1"
+
+        ["parquet", "orc"].each { format ->
+            String tableName = "upgrade_${format}"
+            String writer = "${writerCatalog}.${dbName}.${tableName}"
+            String warm = "${warmCatalog}.${dbName}.${tableName}"
+            String cold = "${coldCatalog}.${dbName}.${tableName}"
+            sql "drop table if exists ${writer}"
+            sql """create table ${writer} (id int, value int)
+                properties ('format-version' = '2', 'write.format.default' = 
'${format}',
+                    'commit.manifest-merge.enabled' = 'false',
+                    'write.update.mode' = 'merge-on-read', 'write.merge.mode' 
= 'merge-on-read')"""
+            sql "insert into ${writer} values (1, 10), (2, 20), (3, 30)"
+            def oldState = manifestState(tableName)
+            def oldSnapshot = oldState.snapshotId
+            assertTrue(!oldState.firstRowIds.isEmpty())
+            oldState.firstRowIds.values().each { id -> assertTrue(id == null) }
+
+            refresh(warmCatalog, tableName)
+            sql "set enable_external_table_batch_mode = false"
+            String warmQuery = "select id, value from ${warm} order by id"
+            sql warmQuery
+            assertCacheHit(warmQuery)
+
+            // Writing through a separate catalog leaves the warmed 
parsed-manifest cache intact.
+            sql "alter table ${writer} set ('format-version' = '3')"
+            refresh(warmCatalog, tableName)
+            "qt_${format}_property_only"("""select id, _row_id, 
_last_updated_sequence_number
+                from ${warm} order by id""")
+            sql "insert into ${writer} values (4, 40), (5, 50)"
+            def newState = manifestState(tableName)
+            
assertTrue(newState.firstRowIds.keySet().containsAll(oldState.firstRowIds.keySet()),
+                    "the trigger requires reusing the pre-upgrade physical 
manifest")
+            oldState.firstRowIds.keySet().each { path -> 
assertTrue(newState.firstRowIds[path] != null) }
+
+            [false, true].each { batchMode ->
+                sql "set enable_external_table_batch_mode = ${batchMode}"
+                refresh(warmCatalog, tableName)
+                "qt_${format}_upgraded_${batchMode}"("""select id,
+                    _row_id is not null, _last_updated_sequence_number is not 
null
+                    from ${warm} order by id""")
+                assertEquals(lineage(writerCatalog, tableName), 
lineage(warmCatalog, tableName))
+                if (!batchMode) {
+                    assertCacheHit("select id, _row_id from ${warm} order by 
id")
+                }
+            }
+
+            // This catalog first sees V3; a later historical read must not 
borrow its inherited IDs.
+            refresh(coldCatalog, tableName)

Review Comment:
   [P3] Warm the V3-first catalog with batch mode off. The preceding loop 
leaves batch mode enabled with a one-file threshold. 
`IcebergScanNode.planFileScanTaskWithManifestCache()` bypasses the parsed cache 
in that mode, so neither this warmup nor the historical reads can detect V3 row 
IDs being reused for V2. Disable batch mode here and verify a V3 cache hit 
before opening the historical snapshot.



##########
fe/fe-iceberg-common/src/main/java/org/apache/iceberg/io/NativeGcsResolvingFileIO.java:
##########
@@ -17,42 +17,211 @@
 
 package org.apache.iceberg.io;
 
+import org.apache.iceberg.CatalogUtil;
+import org.apache.iceberg.gcp.GCPProperties;
+import org.apache.iceberg.gcp.gcs.PrefixAwareGcsFileIO;
+
+import org.apache.doris.iceberg.GcsOAuthTokenValidator;
+import org.apache.hadoop.conf.Configuration;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
 import java.util.Map;
 
 /**
- * A {@link ResolvingFileIO} that preserves the legacy Hadoop GCS path unless 
SDK storage options exist.
+ * A {@link ResolvingFileIO} that preserves Hadoop GCS credentials unless SDK 
credentials override them.
  *
- * <p>Adding iceberg-gcp makes the SDK route these locations to GCSFileIO, 
which does not read the
- * {@code fs.s3a.*} HMAC settings Doris supplies. Both FE and the BE metadata 
scanner must load this
- * implementation because its class name is carried inside serialized Iceberg 
scan tasks. Explicit
- * {@code gcs.*} storage options retain the SDK path, including options 
supplied after FE selection.
+ * <p>Doris configures GCS access as Hadoop properties: native credentials 
(credential provider type,
+ * service-account impersonation) as {@code fs.gs.*}, and HMAC 
interoperability keys or anonymous access as
+ * {@code fs.s3a.*}. Only the Hadoop filesystems read them. Upstream 
ResolvingFileIO
+ * routes {@code gs} to {@code GCSFileIO} whenever iceberg-gcp is on the 
classpath and falls back to
+ * HadoopFileIO only when that class is missing. Both runtimes bundle 
iceberg-gcp for the REST
+ * catalog's {@code GoogleAuthManager} and an explicitly chosen {@code 
GCSFileIO}, so this class pins
+ * the default routing instead of relying on that class being absent. SDK 
credentials and their storage options retain
+ * the SDK path, including credentials received after FE selection. Other 
schemes resolve as upstream.
  *
- * <p>The SDK package is required because {@code implFromLocation} is 
package-private. It also keeps
- * this class and iceberg-core in the same class loader on both sides of a 
metadata scan.
+ * <p>It lives in {@code org.apache.iceberg.io} because {@code 
implFromLocation} is package-private; the
+ * override only takes effect when this class and iceberg-core share a class 
loader, which holds for the
+ * FE catalog and the BE metadata scanner, both of which bundle iceberg-core 
themselves. Its class
+ * name is part of serialized Iceberg scan tasks, so it must stay loadable on 
both sides.
  */
 public class NativeGcsResolvingFileIO extends ResolvingFileIO {
     private static final long serialVersionUID = 1L;
 
     private static final String GCS_FILE_IO_IMPL = 
"org.apache.iceberg.gcp.gcs.GCSFileIO";
     private static final String HADOOP_FILE_IO_IMPL = 
"org.apache.iceberg.hadoop.HadoopFileIO";
 
-    public static boolean hasSdkGcsProperties(Map<String, String> properties) {
-        return properties.entrySet().stream()
-                .anyMatch(entry -> entry.getKey().startsWith("gcs.") && 
entry.getValue() != null);
-    }
+    // Clients are bounded by credential prefixes, not file locations, and are 
rebuilt after serialization.
+    private transient Map<String, DelegateFileIO> scopedIos;
+    private volatile Boolean hadoopGcsConfigured;
+    private boolean closed;
 
     @Override
-    String implFromLocation(String location) {
+    synchronized String implFromLocation(String location) {
         String impl = super.implFromLocation(location);
         if (!GCS_FILE_IO_IMPL.equals(impl)) {
             return impl;
         }
-        // REST/table options and matching vended credentials can arrive after 
FE chose this resolver.
-        // HadoopFileIO ignores SDK encryption and billing options, so those 
must keep the native path.
-        if (hasSdkGcsProperties(properties()) || 
credentials().stream().anyMatch(credential ->
-                location.startsWith(credential.prefix()) && 
hasSdkGcsProperties(credential.config()))) {
+        StorageCredential matching = matchingCredential(location);
+        Map<String, String> scope = matching == null ? Collections.emptyMap() 
: matching.config();
+        // Validate the effective scope before choosing an identity: a present 
null token is not an absent token.
+        GcsOAuthTokenValidator.validate(properties(), scope);
+        Map<String, String> effective = effectiveProperties(scope);
+        String impersonation = 
effective.get("gcs.impersonate.service-account");
+        boolean sdkIdentity = effective.containsKey("gcs.oauth2.token")
+                || Boolean.parseBoolean(effective.get("gcs.no-auth"))
+                || (impersonation != null && !impersonation.isEmpty());
+        if (sdkIdentity) {
             return GCS_FILE_IO_IMPL;
         }
-        return HADOOP_FILE_IO_IMPL;
+        // Project selection is not authentication. SDK-only options must 
never silently replace HMAC with ADC.
+        if (properties().containsKey("gs.access_key") || 
hasHadoopGcsConfiguration()) {
+            for (String key : effective.keySet()) {
+                if (key.startsWith("gcs.") && !"gcs.project-id".equals(key)) {
+                    throw new IllegalArgumentException("GCS option requires an 
explicit SDK storage identity: " + key);
+                }
+            }
+            return HADOOP_FILE_IO_IMPL;
+        }
+        // With no configured Hadoop identity, retain the upstream SDK/ADC 
default.
+        return GCS_FILE_IO_IMPL;
+    }
+
+    private boolean hasHadoopGcsConfiguration() {
+        if (hadoopGcsConfigured == null) {
+            boolean configured = false;
+            Configuration conf = getConf();
+            if (conf != null) {
+                for (Map.Entry<String, String> entry : conf) {
+                    if (entry.getKey().startsWith("fs.gs.")) {
+                        configured = true;
+                        break;
+                    }
+                }
+            }
+            hadoopGcsConfigured = configured;
+        }
+        return hadoopGcsConfigured;
+    }
+
+    @Override
+    public synchronized void setConf(Configuration conf) {
+        super.setConf(conf);
+        // Hadoop configurations can contain thousands of defaults; inspect 
them once per configuration.
+        hadoopGcsConfigured = null;
+    }
+
+    @Override
+    public synchronized void initialize(Map<String, String> properties) {
+        super.initialize(properties);
+        closed = false;
+    }
+
+    @Override
+    public synchronized void setCredentials(List<StorageCredential> 
credentials) {
+        boolean changed = !credentials().equals(credentials);
+        super.setCredentials(credentials);
+        if (changed) {
+            // Replacement credentials must not reuse a client initialized 
with the previous effective root map.
+            closeScopedIos();
+        }
+    }
+
+    private void closeScopedIos() {
+        if (scopedIos == null) {
+            return;
+        }
+        List<DelegateFileIO> delegates = new ArrayList<>(scopedIos.values());
+        // Detach every delegate before closing: a close failure must not 
leave stale credentials cached.
+        scopedIos.clear();
+        RuntimeException failure = null;
+        for (DelegateFileIO delegate : delegates) {
+            try {
+                delegate.close();
+            } catch (RuntimeException closeFailure) {
+                if (failure == null) {
+                    failure = closeFailure;
+                } else {
+                    failure.addSuppressed(closeFailure);
+                }
+            }
+        }
+        if (failure != null) {
+            throw failure;
+        }
+    }
+
+    private StorageCredential matchingCredential(String location) {
+        StorageCredential matching = null;
+        for (StorageCredential credential : credentials()) {
+            if (location.startsWith(credential.prefix())
+                    && (matching == null || credential.prefix().length() >= 
matching.prefix().length())) {
+                matching = credential;
+            }
+        }
+        return matching;
+    }
+
+    private Map<String, String> effectiveProperties(Map<String, String> scope) 
{
+        Map<String, String> effective = new HashMap<>(properties());
+        effective.putAll(scope);
+        return effective;
+    }
+
+    @Override
+    synchronized DelegateFileIO io(String location) {
+        if (closed) {
+            throw new IllegalStateException("FileIO is closed");
+        }
+        if (!GCS_FILE_IO_IMPL.equals(implFromLocation(location))) {
+            return super.io(location);
+        }
+        StorageCredential matching = matchingCredential(location);
+        String prefix = matching == null ? "" : matching.prefix();
+        if (scopedIos == null) {
+            scopedIos = new HashMap<>();
+        }
+        return scopedIos.computeIfAbsent(prefix, ignored -> {
+            // GCSFileIO eagerly parses globals and every credential, 
including unrelated/overridden expiries.
+            // Give its root client the validated effective map, and retain 
only this scope for SDK refresh.
+            Map<String, String> effective = effectiveProperties(
+                    matching == null ? Collections.emptyMap() : 
matching.config());
+            // Match SDK authentication selection: only a non-null endpoint 
enables refresh.
+            if (matching != null && 
effective.containsKey(GCPProperties.GCS_OAUTH2_TOKEN)

Review Comment:
   [P2] Keep an inherited token bound to its credential scope, not an 
options-only prefix. A REST table can supply its token, expiry, and refresh 
endpoint in table-level `config`, while `gs://bucket/private/` supplies only 
`gcs.project-id`. The merged map triggers the prefix-aware adapter as if 
`/private/` had supplied the token. A refresh that returns a fresh table token 
for `gs://bucket/` worked with the previous SDK handler but is now rejected 
because there is no exact `/private/` entry. Track where the token came from 
when choosing the refresh behavior and cover this configuration with an 
expired-token test. [Iceberg 1.11.0 refresh 
selection](https://github.com/apache/iceberg/blob/apache-iceberg-1.11.0/gcp/src/main/java/org/apache/iceberg/gcp/gcs/OAuth2RefreshCredentialsHandler.java#L63-L82)



##########
be/test/format_v2/orc/orc_reader_test.cpp:
##########
@@ -4989,6 +5098,277 @@ TEST_F(NewOrcReaderTest, 
InitReturnsEndOfFileWhenIoContextShouldStop) {
     EXPECT_TRUE(status.is<ErrorCode::END_OF_FILE>()) << status;
 }
 
+TEST_F(NewOrcReaderTest, AggregatePushdownFloatingStatisticsRequireFiniteSums) 
{
+    const double nan = std::numeric_limits<double>::quiet_NaN();
+    const double infinity = std::numeric_limits<double>::infinity();
+    struct Case {
+        std::string name;
+        std::vector<std::optional<double>> values;
+        bool metadata;
+        bool has_values;
+        double minimum = 0;
+        double maximum = 0;
+    };
+    const std::vector<Case> cases {{"finite", {1, -2, 3}, true, true, -2, 3},
+                                   {"finite_nullable", {std::nullopt, 1, 2}, 
true, true, 1, 2},
+                                   {"all_null", {std::nullopt, std::nullopt}, 
false, false},
+                                   {"nan_middle", {1, nan, 2}, false, true},
+                                   {"nan_last", {1, 2, nan}, false, true},
+                                   {"nan_first", {nan, 1, 2}, false, true},
+                                   {"all_nan", {nan, nan}, false, true},
+                                   {"nan_nullable", {std::nullopt, 1, nan, 2}, 
false, true},
+                                   {"positive_infinity", {1, infinity}, false, 
true},
+                                   {"negative_infinity", {-infinity, 2}, 
false, true},
+                                   {"opposite_infinities", {-infinity, 
infinity}, false, true}};
+    for (bool single_precision : {false, true}) {
+        auto inputs = cases;
+        if (!single_precision) {
+            inputs.push_back(
+                    {"sum_overflow",
+                     {std::numeric_limits<double>::max(), 
std::numeric_limits<double>::max()},
+                     false,
+                     true});
+        } else {
+            const double maximum = std::numeric_limits<float>::max();
+            inputs.push_back(
+                    {"finite_float_max", {maximum, maximum}, true, true, 
maximum, maximum});
+        }
+        for (const auto& input : inputs) {
+            SCOPED_TRACE(input.name + (single_precision ? " float" : " 
double"));
+            const auto path =
+                    (_test_dir / (input.name + (single_precision ? "_f.orc" : 
"_d.orc"))).string();
+            write_orc_floating_statistics_file(path, single_precision, 
{input.values});
+            auto reader = create_reader_for_path(path);
+            RuntimeState state {TQueryOptions(), TQueryGlobals()};
+            ASSERT_TRUE(reader->init(&state).ok());
+            auto request = std::make_shared<format::FileScanRequest>();
+            request->non_predicate_columns = {field_projection(0)};
+            ASSERT_TRUE(reader->open(request).ok());
+            format::FileAggregateRequest aggregate_request;
+            aggregate_request.agg_type = TPushAggOp::MINMAX;
+            aggregate_request.columns.push_back({.projection = 
field_projection(0)});
+            format::FileAggregateResult result;
+            auto status = reader->get_aggregate_result(aggregate_request, 
&result);
+            if (!input.metadata) {
+                EXPECT_TRUE(status.is<ErrorCode::NOT_IMPLEMENTED_ERROR>()) << 
status;
+                continue;
+            }
+            ASSERT_TRUE(status.ok()) << status;
+            EXPECT_EQ(result.count, input.values.size());
+            ASSERT_EQ(result.columns.size(), 1);
+            EXPECT_EQ(result.columns[0].has_min, input.has_values);
+            EXPECT_EQ(result.columns[0].has_max, input.has_values);
+            if (input.has_values) {
+                const double minimum =
+                        single_precision
+                                ? 
static_cast<double>(result.columns[0].min_value.get<TYPE_FLOAT>())
+                                : 
result.columns[0].min_value.get<TYPE_DOUBLE>();
+                const double maximum =
+                        single_precision
+                                ? 
static_cast<double>(result.columns[0].max_value.get<TYPE_FLOAT>())
+                                : 
result.columns[0].max_value.get<TYPE_DOUBLE>();
+                EXPECT_DOUBLE_EQ(minimum, input.minimum);
+                EXPECT_DOUBLE_EQ(maximum, input.maximum);
+            }
+        }
+    }
+}
+
+TEST_F(NewOrcReaderTest, MetadataFloatingFallbackPreservesRowsAndNaN) {
+    for (bool single_precision : {false, true}) {
+        for (bool include_nan : {false, true}) {
+            SCOPED_TRACE(single_precision);
+            SCOPED_TRACE(include_nan);
+            // Give each fixture its own identity: metadata cache keys can 
fall back to path and size.
+            const auto path = (_test_dir / (std::string("floating_metadata_") +
+                                            (single_precision ? "float_" : 
"double_") +
+                                            (include_nan ? "nan.orc" : 
"finite.orc")))
+                                      .string();
+            write_orc_floating_statistics_file(
+                    path, single_precision,
+                    {{{1}, {include_nan ? 
std::numeric_limits<double>::quiet_NaN() : 3}, {2}}});
+            RuntimeState state {TQueryOptions(), TQueryGlobals()};
+            format::ColumnDefinition column;
+            column.identifier = Field::create_field<TYPE_STRING>("value");
+            column.name = "value";
+            column.type = single_precision ? 
make_nullable(std::make_shared<DataTypeFloat32>())
+                                           : 
make_nullable(std::make_shared<DataTypeFloat64>());
+            format::TableReader reader;
+            ASSERT_TRUE(reader.init({.projected_columns = {column},
+                                     .conjuncts = {},
+                                     .format = format::FileFormat::ORC,
+                                     .scan_params = nullptr,
+                                     .io_ctx = nullptr,
+                                     .runtime_state = &state,
+                                     .scanner_profile = nullptr,
+                                     .push_down_agg_type = TPushAggOp::MINMAX})
+                                .ok());
+            format::SplitReadOptions options;
+            options.current_split_format = format::FileFormat::ORC;
+            options.current_range.__set_path(path);
+            
options.current_range.__set_file_size(std::filesystem::file_size(path));
+            options.current_range.__set_start_offset(0);
+            options.current_range.__set_size(std::filesystem::file_size(path));
+            ASSERT_TRUE(reader.prepare_split(options).ok());
+            FileScanSplit source;
+            source.range = options.current_range;
+            source.is_source_split = true;
+            std::vector<FileScanSplit> children;
+            bool was_split = false;
+            ASSERT_TRUE(reader.build_physical_splits(source, &children, 
&was_split).ok());
+            EXPECT_FALSE(was_split);
+            EXPECT_EQ(reader._metadata_aggregate_result.has_value(), 
!include_nan);

Review Comment:
   [P2] Check the ORC fallback at read time on this branch. 
`build_physical_splits()` only sets `_metadata_aggregate_result` through 
`get_metadata_aggregate_result()`. Branch 4.1’s `OrcReader` inherits the 
`NotSupported` implementation of that hook and only overrides 
`get_aggregate_result()`, which runs from `get_block()`. The finite FLOAT and 
DOUBLE cases therefore fail this assertion even when pushdown is correct. Drop 
the planning-state assertion and keep checking for two synthetic rows versus 
three original rows with NaN.



##########
regression-test/suites/external_table_p0/iceberg/test_iceberg_mixed_gcs_credentials.groovy:
##########
@@ -0,0 +1,233 @@
+// 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.
+
+import com.sun.net.httpserver.HttpExchange
+import com.sun.net.httpserver.HttpHandler
+import com.sun.net.httpserver.HttpServer
+import groovy.json.JsonOutput
+import groovy.json.JsonSlurper
+
+import java.net.InetSocketAddress
+import java.net.URLDecoder
+import java.util.concurrent.ConcurrentHashMap
+import java.util.concurrent.ConcurrentLinkedQueue
+import java.util.concurrent.Executors
+import java.util.concurrent.TimeUnit
+import java.util.concurrent.atomic.AtomicInteger
+import java.util.concurrent.atomic.AtomicReference
+
+// SHOW PARTITIONS reads both manifests on FE. The fixture has one 
category=alpha partition,
+// one 123-byte data file and seven records; no data-file read or external 
cloud service is needed.
+suite("test_iceberg_mixed_gcs_credentials", "p0,external") {
+    def fixture = new File(context.config.dataPath, 
"external_table_p0/iceberg/mixed_gcs_credentials")
+    Map metadata = new JsonSlurper().parse(new File(fixture, "metadata.json")) 
as Map
+    Map<String, byte[]> objects = [
+            "public/list.avro": new File(fixture, "list.avro").bytes,
+            "private/manifest.avro": new File(fixture, "manifest.avro").bytes,
+            "v1.metadata.json": new File(fixture, "metadata.json").bytes]
+    def mode = new AtomicReference<String>("forward")
+    def accepted = new ConcurrentHashMap<String, AtomicInteger>()
+    def rejected = new AtomicInteger()
+    def fallbackReads = new AtomicInteger()
+    Map<String, Map<String, String>> invalidConfigs = [:]
+    ["gs.oauth2.token", "gcs.oauth2.token"].eachWithIndex { String key, int 
alias ->
+        ["", " ", "invalid secret token"].eachWithIndex { String token, int 
value ->
+            invalidConfigs.put("invalid_${alias}_${value}".toString(), [(key): 
token])
+        }
+    }
+    def validTables = ["forward", "reverse", "same_prefix", "legacy", 
"unrelated_expiry", "overridden_expiry"]
+    def tableNames = validTables + invalidConfigs.keySet()
+    def requests = new ConcurrentLinkedQueue<String>()
+    def executor = Executors.newFixedThreadPool(4)
+    HttpServer server = HttpServer.create(new InetSocketAddress("0.0.0.0", 0), 
0)
+    server.setExecutor(executor)
+    // Like HTTP TVF fixtures, the advertised address must be reachable from 
FE.
+    String host = context.config.otherConfigs.get("httpTvfHost")
+            ?: context.config.otherConfigs.get("externalEnvIp") ?: "127.0.0.1"
+    String endpoint = "http://${host}:${server.address.port}";
+    def jsonResponse = { HttpExchange exchange, int status, Object value ->
+        byte[] body = JsonOutput.toJson(value).getBytes("UTF-8")
+        exchange.responseHeaders.set("Content-Type", "application/json")
+        exchange.sendResponseHeaders(status, body.length)
+        exchange.responseBody.write(body)
+    }
+    def sdkConfig = { String token ->
+        ["gcs.project-id": "fixture-project", "gcs.service.host": endpoint, 
"gcs.oauth2.token": token]
+    }
+    server.createContext("/", { HttpExchange exchange ->
+        try {
+            String path = URLDecoder.decode(exchange.requestURI.rawPath, 
"UTF-8")
+            requests.add(exchange.requestMethod + " " + path)
+            if (path == "/v1/config") {
+                jsonResponse(exchange, 200, [defaults: [:], overrides: [:]])
+            } else if (path == "/v1/namespaces") {
+                jsonResponse(exchange, 200, [namespaces: [["fixture_db"]]])
+            } else if (path == "/v1/namespaces/fixture_db") {
+                jsonResponse(exchange, 200, [namespace: ["fixture_db"], 
properties: [:]])
+            } else if (path == "/v1/namespaces/fixture_db/tables") {
+                jsonResponse(exchange, 200, [identifiers: tableNames.collect {
+                    [namespace: ["fixture_db"], name: it]
+                }])
+            } else if (path.startsWith("/v1/namespaces/fixture_db/tables/")
+                    && tableNames.contains(
+                            path.substring(path.lastIndexOf('/') + 1))) {
+                String table = path.substring(path.lastIndexOf('/') + 1)
+                def broad = [prefix: "gs://fixture-bucket/", config: 
sdkConfig("broad-token")]
+                // HadoopFileIO ignores scoped configs: this scope must retain 
the catalog's HMAC identity.
+                def narrow = [prefix: "gs://fixture-bucket/private/", config: 
table == "legacy"
+                        ? ["fs.gs.auth.type": "UNAUTHENTICATED"] : 
sdkConfig("narrow-token")]
+                def unrelated = [prefix: "gs://other-bucket/", config: 
sdkConfig("unrelated-token")]
+                def credentials = table == "reverse" ? [narrow, unrelated, 
broad] : [broad, unrelated, narrow]
+                if (table == "same_prefix") {
+                    credentials = [broad, [prefix: narrow.prefix, config: 
sdkConfig("wrong-token")],
+                            unrelated, narrow]
+                }
+                if (table == "unrelated_expiry" || table == 
"overridden_expiry") {
+                    broad.config["gcs.oauth2.token-expires-at"] = 
"4102444800000"
+                    narrow.config["gcs.oauth2.token-expires-at"] = 
"4102444800000"
+                    unrelated.config["gcs.oauth2.token-expires-at"] = 
"invalid-expiry"
+                }
+                boolean invalid = invalidConfigs.containsKey(table)
+                Map invalidConfig = invalid ? invalidConfigs.get(table) : [:]
+                if (invalidConfig.containsKey("gcs.oauth2.token")) {
+                    invalidConfig = ["gcs.project-id": "fixture-project", 
"gcs.service.host": endpoint] + invalidConfig
+                }
+                if (table == "overridden_expiry") {
+                    invalidConfig = ["gcs.oauth2.token-expires-at": 
"invalid-expiry"]
+                }
+                jsonResponse(exchange, 200, ["metadata-location": 
"gs://fixture-bucket/v1.metadata.json",
+                        metadata: metadata, "storage-credentials": invalid ? 
[] : credentials,
+                        config: invalidConfig])
+            } else {
+                boolean nativeApi = 
path.startsWith("/storage/v1/b/fixture-bucket/o/")
+                        || 
path.startsWith("/download/storage/v1/b/fixture-bucket/o/")
+                String object = nativeApi ? path.substring(path.indexOf("/o/") 
+ 3)
+                        : path.startsWith("/fixture-bucket/") ? 
path.substring("/fixture-bucket/".length()) : ""
+                byte[] body = objects.get(object)
+                if (body == null) {
+                    jsonResponse(exchange, 404, [error: [message: "Unknown 
fixture object", type: "NoSuchKey", code: 404]])
+                    return
+                }
+                String authorization = 
exchange.requestHeaders.getFirst("Authorization")
+                boolean invalid = mode.get().startsWith("invalid_")
+                boolean hmac = invalid || mode.get() == "legacy" && 
object.startsWith("private/")
+                String token = object.startsWith("private/") ? "narrow-token" 
: "broad-token"
+                boolean authorized = hmac ? !nativeApi && authorization != null
+                        && authorization.startsWith("AWS4-HMAC-SHA256 ")
+                        && 
authorization.contains("Credential=fixture-storage-key/")
+                        : nativeApi && authorization == "Bearer ${token}"
+                if (!authorized) {
+                    rejected.incrementAndGet()
+                    exchange.sendResponseHeaders(403, -1)
+                    return
+                }
+                if (invalid) {
+                    // Keep the base identity usable: a silent fallback would 
succeed and fail this test.
+                    fallbackReads.incrementAndGet()
+                }
+                accepted.computeIfAbsent(mode.get() + ":" + object, { new 
AtomicInteger() }).incrementAndGet()
+                boolean media = 
exchange.requestURI.rawQuery?.split('&')?.contains("alt=media")
+                if (nativeApi && !media) {
+                    jsonResponse(exchange, 200, [bucket: "fixture-bucket", 
name: object,
+                            size: body.length.toString(), generation: "1", 
metageneration: "1"])
+                    return
+                }
+                exchange.responseHeaders.set("ETag", '"fixture-etag"')
+                exchange.responseHeaders.set("Last-Modified", "Tue, 14 Nov 
2023 22:13:20 GMT")
+                String range = exchange.requestHeaders.getFirst("Range")
+                int start = 0
+                int end = body.length - 1
+                if (range != null) {
+                    def match = range =~ /^bytes=(\d+)-(\d*)$/
+                    assertTrue(match.matches(), "Unexpected fixture range: 
${range}")
+                    start = match.group(1).toInteger()
+                    if (!match.group(2).isEmpty()) {
+                        end = Math.min(end, match.group(2).toInteger())
+                    }
+                    if (start > end) {
+                        exchange.sendResponseHeaders(416, -1)
+                        return
+                    }
+                    exchange.responseHeaders.set("Content-Range", "bytes 
${start}-${end}/${body.length}")
+                }
+                exchange.responseHeaders.set("Content-Length", (end - start + 
1).toString())
+                boolean head = exchange.requestMethod == "HEAD"
+                exchange.sendResponseHeaders(range == null ? 200 : 206, head ? 
-1 : end - start + 1)
+                if (!head) {
+                    exchange.responseBody.write(body, start, end - start + 1)
+                }
+            }
+        } finally {
+            exchange.close()
+        }
+    } as HttpHandler)
+    server.start()
+    try {
+        def createCatalog = { String catalog, String resolver ->
+            sql "DROP CATALOG IF EXISTS ${catalog}"
+            // The catalog starts with Hadoop/HMAC settings; scoped-only gcs.* 
options arrive on table load.
+            sql """CREATE CATALOG ${catalog} PROPERTIES (
+                'type' = 'iceberg', 'iceberg.catalog.type' = 'rest', 'uri' = 
'${endpoint}',
+                'warehouse' = 'gs://fixture-bucket/warehouse', 
'rest.auth.type' = 'none',
+                ${resolver}
+                'gcs.project-id' = 'fixture-project', 'provider' = 'GCP', 
'gs.endpoint' = '${endpoint}', 'use_path_style' = 'true',
+                'gs.access_key' = 'fixture-storage-key', 'gs.secret_key' = 
'fixture-storage-secret',
+                'iceberg.rest.vended-credentials-enabled' = 'false',
+                'fs.s3a.endpoint.region' = 'us-east-1', 
'fs.s3a.connection.ssl.enabled' = 'false',
+                'fs.s3a.retry.limit' = '0', 'fs.s3a.attempts.maximum' = '1', 
'fs.s3a.bucket.probe' = '0'
+            )"""
+        }
+        createCatalog("test_iceberg_mixed_gcs_credentials", "")
+        order_qt_forward "SHOW PARTITIONS FROM 
test_iceberg_mixed_gcs_credentials.fixture_db.forward"

Review Comment:
   [P2] Exercise storage through SQL that branch 4.1 supports. 
`ShowPartitionsCommand.validate()` rejects Iceberg catalogs before opening the 
table, so this first query cannot produce `category=alpha`. The negative cases 
using the same command also get a catalog-type error instead of the expected 
credential error. Use a supported Iceberg metadata path that reads both fixture 
objects and keep the per-scope authentication assertions.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


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

Reply via email to