Gabriel39 commented on code in PR #71411:
URL: https://github.com/apache/doris/pull/71411#discussion_r4796502087


##########
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:
   Addressed in `849914a1635`.
   
   Fixed. Hadoop identity detection now recognizes explicit 
filesystem/authentication/impersonation configuration while ignoring 
tuning-only settings. The ADC test performs authenticated metadata reads with 
billing and CSEK options, including fs.gs.impl.disable.cache and HTTP tuning, 
after serialization. Existing Hadoop/HMAC routing tests still pass.



##########
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:
   Addressed in `849914a1635`.
   
   Fixed. Exact-prefix refresh is selected only when the winning scope actually 
supplies the token. Options-only scopes retain their effective storage options 
and use the inherited table token's SDK refresh policy. New tests expire that 
token, return a broader refreshed credential and verify an authenticated read, 
both before and after serialization. Existing scoped-refresh rejection and 
lifecycle tests still pass.



##########
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:
   Addressed in `849914a1635`.
   
   Fixed. Both positive and negative cases now query the supported Iceberg 
`$partitions` metadata table. Positive cases directly assert the manifest's 
record count and retain authenticated reads for every fixture object; negative 
cases retain the credential-error and no-fallback assertions. Removed the 
obsolete SHOW PARTITIONS golden output. Groovy compilation passed; the live 
external SQL suite remains for CI.



##########
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:
   Addressed in `849914a1635`.
   
   Fixed. Removed the planning-state assertion and kept the read-time checks 
for two synthetic finite rows versus three original rows with NaN. The test 
also checks the actual finite values. The affected translation unit compiles 
with ASAN and passes clang-format 16; full BE unit-test execution remains for 
CI.



##########
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:
   Addressed in `849914a1635`.
   
   Fixed. Batch mode is disabled before warming the V3-first catalog, and a 
positive parsed-manifest-cache hit is required before the historical snapshot 
reads. The suite still restores the original batch settings. Groovy compilation 
and the focused manifest row-lineage unit tests passed.



-- 
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