Copilot commented on code in PR #12541:
URL: https://github.com/apache/gravitino/pull/12541#discussion_r3861375333


##########
spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/plugin/TestGravitinoLakehouseRESTDiscoveryDriverPlugin.java:
##########
@@ -0,0 +1,317 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.gravitino.spark.connector.plugin;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import com.google.common.collect.ImmutableMap;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import org.apache.spark.SparkConf;
+import org.apache.spark.sql.internal.StaticSQLConf;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+public class TestGravitinoLakehouseRESTDiscoveryDriverPlugin {
+
+  private static final String DISCOVERY_PLUGIN =
+      GravitinoLakehouseRESTDiscoveryPlugin.class.getName();
+  private static final String GRAVITINO_PLUGIN = 
GravitinoSparkPlugin.class.getName();
+  private static final String URI_CONFIG = "spark.sql.gravitino.fakeREST.uri";
+  private static final String CATALOG_PREFIX = "spark.sql.catalog.";
+
+  @BeforeEach
+  void resetPolicies() {
+    TrackingPolicy.invocationCount = 0;

Review Comment:
   `TrackingPolicy.invocationCount` is a mutable static used for assertions; if 
the build enables JUnit 5 parallel execution, this test can become flaky due to 
cross-test interference. Prefer an `AtomicInteger` (or make the counter 
instance-scoped) to keep the test deterministic under parallel runs.



##########
spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/plugin/GravitinoLakehouseRESTDiscoveryDriverPlugin.java:
##########
@@ -0,0 +1,434 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.gravitino.spark.connector.plugin;
+
+import static org.apache.gravitino.spark.connector.ConnectorConstants.COMMA;
+import static 
org.apache.gravitino.spark.connector.utils.ConnectorUtil.removeDuplicateSparkExtensions;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import java.lang.reflect.InvocationTargetException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.ServiceConfigurationError;
+import java.util.ServiceLoader;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.spark.SparkConf;
+import org.apache.spark.SparkContext;
+import org.apache.spark.api.plugin.DriverPlugin;
+import org.apache.spark.api.plugin.PluginContext;
+import org.apache.spark.sql.catalyst.parser.CatalystSqlParser$;
+import org.apache.spark.sql.internal.StaticSQLConf;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import scala.Tuple2;
+import scala.collection.Seq;
+
+class GravitinoLakehouseRESTDiscoveryDriverPlugin implements DriverPlugin {
+
+  @VisibleForTesting
+  static final String REGISTRATION_POLICY_CONFIG = 
"spark.sql.gravitino.REST.registrationPolicy";
+
+  private static final Logger LOG =
+      
LoggerFactory.getLogger(GravitinoLakehouseRESTDiscoveryDriverPlugin.class);
+  private static final String GRAVITINO_PREFIX = "spark.sql.gravitino.";
+  private static final String SPARK_CATALOG_PREFIX = "spark.sql.catalog.";
+  private static final String URI_SUFFIX = "REST.uri";
+  private static final String CATALOG_PROPERTIES_INFIX = 
"REST.catalogProperties.";
+  private static final Pattern PROVIDER_URI_PATTERN =
+      
Pattern.compile("^spark\\.sql\\.gravitino\\.([A-Za-z][A-Za-z0-9]*)REST\\.uri$");
+  private static final CatalogRegistrationPolicy DEFAULT_POLICY = (format, 
catalogName) -> true;
+
+  private final List<LakehouseRESTCatalogProvider> providersForTesting;
+
+  GravitinoLakehouseRESTDiscoveryDriverPlugin() {
+    this.providersForTesting = null;
+  }
+
+  @VisibleForTesting
+  GravitinoLakehouseRESTDiscoveryDriverPlugin(
+      List<LakehouseRESTCatalogProvider> providersForTesting) {
+    this.providersForTesting = new ArrayList<>(providersForTesting);
+  }
+
+  @Override
+  public Map<String, String> init(SparkContext sc, PluginContext 
pluginContext) {
+    initialize(sc.conf());
+    return Collections.emptyMap();
+  }
+
+  @VisibleForTesting
+  void initialize(SparkConf sparkConf) {
+    validatePluginOrder(sparkConf);
+    SparkConf userConf = sparkConf.clone();
+    Map<String, String> activeFormats = findActiveFormats(userConf);
+    if (activeFormats.isEmpty()) {
+      return;
+    }
+
+    ClassLoader classLoader = contextClassLoader();
+    Map<String, LakehouseRESTCatalogProvider> providers = 
loadProviders(classLoader);
+    CatalogRegistrationPolicy policy = loadRegistrationPolicy(userConf, 
classLoader);
+    List<CatalogRegistration> registrations = new ArrayList<>();
+    Set<String> registeredNames = new LinkedHashSet<>();
+    Set<String> extensions = new LinkedHashSet<>();
+
+    activeFormats.forEach(
+        (format, uri) -> {
+          LakehouseRESTCatalogProvider provider = providers.get(format);
+          Preconditions.checkArgument(
+              provider != null,
+              "No lakehouse REST catalog provider found for configured format: 
%s",
+              format);
+          validateProviderRuntime(provider, classLoader);
+
+          Map<String, String> globalProperties = 
extractCatalogProperties(userConf, format);
+          List<String> advertisedCatalogs =
+              provider.listCatalogs(uri, 
Collections.unmodifiableMap(globalProperties));
+          Preconditions.checkState(
+              advertisedCatalogs != null,
+              "Lakehouse REST catalog provider %s returned a null catalog 
list",
+              format);
+
+          List<String> sortedCatalogs = new ArrayList<>(advertisedCatalogs);
+          Collections.sort(sortedCatalogs);
+          for (String catalogName : sortedCatalogs) {
+            addRegistration(
+                userConf,
+                provider,
+                policy,
+                format,
+                uri,
+                catalogName,
+                globalProperties,
+                registeredNames,
+                registrations);
+          }
+          extensions.addAll(Arrays.asList(provider.sparkExtensions()));
+        });
+
+    applyRegistrations(sparkConf, userConf, registrations);
+    registerSqlExtensions(sparkConf, extensions);
+  }
+
+  private static void validatePluginOrder(SparkConf sparkConf) {
+    String configuredPlugins = sparkConf.get("spark.plugins", "");
+    List<String> plugins = new ArrayList<>();
+    for (String plugin : configuredPlugins.split(COMMA)) {
+      if (StringUtils.isNotBlank(plugin)) {
+        plugins.add(plugin.trim());
+      }
+    }
+
+    int discoveryPluginIndex =
+        plugins.indexOf(GravitinoLakehouseRESTDiscoveryPlugin.class.getName());
+    int gravitinoPluginIndex = 
plugins.indexOf(GravitinoSparkPlugin.class.getName());
+    Preconditions.checkArgument(
+        discoveryPluginIndex < 0
+            || gravitinoPluginIndex < 0
+            || discoveryPluginIndex < gravitinoPluginIndex,
+        "%s must be listed before %s in spark.plugins",
+        GravitinoLakehouseRESTDiscoveryPlugin.class.getName(),
+        GravitinoSparkPlugin.class.getName());
+  }
+
+  private static Map<String, String> findActiveFormats(SparkConf userConf) {
+    Map<String, String> activeFormats = new TreeMap<>();
+    for (Tuple2<String, String> entry : userConf.getAll()) {
+      Matcher matcher = PROVIDER_URI_PATTERN.matcher(entry._1);
+      if (matcher.matches()) {
+        String format = matcher.group(1);
+        String uri = entry._2;
+        Preconditions.checkArgument(
+            StringUtils.isNotBlank(uri),
+            "%s%s%s must not be blank",
+            GRAVITINO_PREFIX,
+            format,
+            URI_SUFFIX);
+        activeFormats.put(format, uri);
+      }
+    }
+    return activeFormats;
+  }
+
+  private Map<String, LakehouseRESTCatalogProvider> loadProviders(ClassLoader 
classLoader) {
+    List<LakehouseRESTCatalogProvider> loadedProviders = new ArrayList<>();
+    if (providersForTesting != null) {
+      loadedProviders.addAll(providersForTesting);
+    } else {
+      try {
+        ServiceLoader.load(LakehouseRESTCatalogProvider.class, classLoader)
+            .forEach(loadedProviders::add);
+      } catch (ServiceConfigurationError e) {
+        throw new IllegalArgumentException("Failed to load lakehouse REST 
catalog providers", e);
+      }
+    }

Review Comment:
   `ServiceLoader...forEach(loadedProviders::add)` eagerly instantiates *all* 
providers whenever *any* `<format>REST.uri` is configured. Because 
`LanceRESTCatalogProvider` has compileOnly runtime dependencies, this can make 
discovery fail even if the configured format is not Lance (or if a future 
format is added and users don’t ship the Lance bundle). Consider loading 
providers in a way that tolerates per-provider 
`ServiceConfigurationError/NoClassDefFoundError/LinkageError` (skip + log), and 
only hard-fail later if the configured format has no usable provider; 
alternatively, move the Lance provider into a separate optional artifact so 
non-Lance discovery doesn’t require Lance runtime classes.



##########
spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/plugin/TestLanceRESTCatalogProvider.java:
##########
@@ -0,0 +1,124 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.gravitino.spark.connector.plugin;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpServer;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+public class TestLanceRESTCatalogProvider {
+
+  private HttpServer server;
+  private String serverUri;
+
+  @BeforeEach
+  void startServer() throws IOException {
+    server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
+    serverUri = "http://localhost:"; + server.getAddress().getPort() + 
"/lance/";
+  }
+
+  @AfterEach
+  void stopServer() {
+    server.stop(0);
+  }
+
+  @Test
+  void testListsAllCatalogPages() {
+    AtomicInteger requests = new AtomicInteger();
+    server.createContext(
+        "/lance/v1/namespace/$/list",
+        exchange -> {
+          int request = requests.getAndIncrement();
+          if (request == 0) {
+            
assertFalse(exchange.getRequestURI().getQuery().contains("page_token"));
+            respond(exchange, 200, 
"{\"namespaces\":[\"catalog_b\"],\"page_token\":\"next\"}");
+          } else {
+            
assertTrue(exchange.getRequestURI().getQuery().contains("page_token=next"));

Review Comment:
   `URI#getQuery()` can be null when no query string is present, which will 
throw an NPE on the first request. Capture the query into a local variable and 
assert against null safely (e.g., treat null as “no query”), so the test fails 
with an assertion instead of erroring.



##########
spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/plugin/TestGravitinoLakehouseRESTDiscoveryDriverPlugin.java:
##########
@@ -0,0 +1,317 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.gravitino.spark.connector.plugin;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import com.google.common.collect.ImmutableMap;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import org.apache.spark.SparkConf;
+import org.apache.spark.sql.internal.StaticSQLConf;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+public class TestGravitinoLakehouseRESTDiscoveryDriverPlugin {
+
+  private static final String DISCOVERY_PLUGIN =
+      GravitinoLakehouseRESTDiscoveryPlugin.class.getName();
+  private static final String GRAVITINO_PLUGIN = 
GravitinoSparkPlugin.class.getName();
+  private static final String URI_CONFIG = "spark.sql.gravitino.fakeREST.uri";
+  private static final String CATALOG_PREFIX = "spark.sql.catalog.";
+
+  @BeforeEach
+  void resetPolicies() {
+    TrackingPolicy.invocationCount = 0;
+  }
+
+  @Test
+  void testRequiresDiscoveryPluginBeforeGravitinoPlugin() {
+    SparkConf sparkConf =
+        baseConf().set("spark.plugins", GRAVITINO_PLUGIN + "," + 
DISCOVERY_PLUGIN);
+
+    IllegalArgumentException exception =
+        assertThrows(IllegalArgumentException.class, () -> 
driver().initialize(sparkConf));
+
+    assertTrue(exception.getMessage().contains("must be listed before"));
+    assertFalse(sparkConf.contains(CATALOG_PREFIX + "catalog_a"));
+  }
+
+  @Test
+  void testNoConfiguredUriDoesNotChangeSparkConf() {
+    SparkConf sparkConf =
+        new SparkConf(false).set("spark.plugins", DISCOVERY_PLUGIN + "," + 
GRAVITINO_PLUGIN);
+
+    new GravitinoLakehouseRESTDiscoveryDriverPlugin(
+            Collections.singletonList(new FailingProvider()))
+        .initialize(sparkConf);
+
+    
assertFalse(sparkConf.contains(StaticSQLConf.SPARK_SESSION_EXTENSIONS().key()));
+  }
+
+  @Test
+  void testGeneratedConfigurationAndPrecedence() {
+    SparkConf sparkConf =
+        baseConf()
+            .set("spark.sql.gravitino.fakeREST.catalogProperties.impl", 
"global-impl")
+            .set("spark.sql.gravitino.fakeREST.catalogProperties.uri", 
"global-uri")
+            .set("spark.sql.gravitino.fakeREST.catalogProperties.extra", 
"global-extra")
+            .set(CATALOG_PREFIX + "catalog_a.uri", "user-uri")
+            .set(
+                StaticSQLConf.SPARK_SESSION_EXTENSIONS().key(),
+                "example.UserExtension,java.lang.Runnable");
+
+    driver().initialize(sparkConf);
+
+    assertEquals(String.class.getName(), sparkConf.get(CATALOG_PREFIX + 
"catalog_a"));
+    assertEquals("rest", sparkConf.get(CATALOG_PREFIX + "catalog_a.impl"));
+    assertEquals("user-uri", sparkConf.get(CATALOG_PREFIX + "catalog_a.uri"));
+    assertEquals("catalog_a", sparkConf.get(CATALOG_PREFIX + 
"catalog_a.parent"));
+    assertEquals("global-extra", sparkConf.get(CATALOG_PREFIX + 
"catalog_a.extra"));
+    assertEquals(
+        "java.lang.Runnable,example.UserExtension",
+        sparkConf.get(StaticSQLConf.SPARK_SESSION_EXTENSIONS().key()));
+  }
+
+  @Test
+  void testUserOwnedCatalogDoesNotReachPolicy() {
+    SparkConf sparkConf =
+        baseConf()
+            .set(CATALOG_PREFIX + "catalog_a", "example.UserCatalog")
+            .set(
+                
GravitinoLakehouseRESTDiscoveryDriverPlugin.REGISTRATION_POLICY_CONFIG,
+                TrackingPolicy.class.getName());
+
+    driver().initialize(sparkConf);
+
+    assertEquals(0, TrackingPolicy.invocationCount);
+    assertEquals("example.UserCatalog", sparkConf.get(CATALOG_PREFIX + 
"catalog_a"));
+    assertFalse(sparkConf.contains(CATALOG_PREFIX + "catalog_a.parent"));
+  }
+
+  @Test
+  void testPolicyFiltersAndRenamesCatalogs() {
+    FakeProvider provider = new FakeProvider(Arrays.asList("catalog_a", 
"catalog_b"));
+    SparkConf sparkConf =
+        baseConf()
+            .set(
+                
GravitinoLakehouseRESTDiscoveryDriverPlugin.REGISTRATION_POLICY_CONFIG,
+                RenamePolicy.class.getName());
+
+    new 
GravitinoLakehouseRESTDiscoveryDriverPlugin(Collections.singletonList(provider))
+        .initialize(sparkConf);
+
+    assertFalse(sparkConf.contains(CATALOG_PREFIX + "catalog_a"));
+    assertEquals(String.class.getName(), sparkConf.get(CATALOG_PREFIX + 
"renamed_b"));
+    assertEquals("catalog_b", sparkConf.get(CATALOG_PREFIX + 
"renamed_b.parent"));
+  }
+
+  @Test
+  void testDuplicatePolicyOutputDoesNotPartiallyModifySparkConf() {
+    FakeProvider provider = new FakeProvider(Arrays.asList("catalog_a", 
"catalog_b"));
+    SparkConf sparkConf =
+        baseConf()
+            .set(
+                
GravitinoLakehouseRESTDiscoveryDriverPlugin.REGISTRATION_POLICY_CONFIG,
+                DuplicatePolicy.class.getName());
+
+    IllegalArgumentException exception =
+        assertThrows(
+            IllegalArgumentException.class,
+            () ->
+                new 
GravitinoLakehouseRESTDiscoveryDriverPlugin(Collections.singletonList(provider))
+                    .initialize(sparkConf));
+
+    assertTrue(exception.getMessage().contains("duplicate name"));
+    assertFalse(sparkConf.contains(CATALOG_PREFIX + "duplicate"));
+    
assertFalse(sparkConf.contains(StaticSQLConf.SPARK_SESSION_EXTENSIONS().key()));
+  }
+
+  @Test
+  void testInvalidPolicyOutputFails() {
+    SparkConf sparkConf =
+        baseConf()
+            .set(
+                
GravitinoLakehouseRESTDiscoveryDriverPlugin.REGISTRATION_POLICY_CONFIG,
+                InvalidNamePolicy.class.getName());
+
+    IllegalArgumentException exception =
+        assertThrows(IllegalArgumentException.class, () -> 
driver().initialize(sparkConf));
+
+    assertTrue(exception.getMessage().contains("invalid Spark identifier"));
+    assertFalse(sparkConf.contains(CATALOG_PREFIX + "invalid-name"));
+  }
+
+  @Test
+  void testConfiguredFormatWithoutProviderFails() {
+    SparkConf sparkConf = baseConf();
+
+    IllegalArgumentException exception =
+        assertThrows(
+            IllegalArgumentException.class,
+            () ->
+                new 
GravitinoLakehouseRESTDiscoveryDriverPlugin(Collections.emptyList())
+                    .initialize(sparkConf));
+
+    assertTrue(exception.getMessage().contains("No lakehouse REST catalog 
provider"));
+  }
+
+  private static SparkConf baseConf() {
+    return new SparkConf(false).set("spark.plugins", 
DISCOVERY_PLUGIN).set(URI_CONFIG, "rest-uri");
+  }
+
+  private static GravitinoLakehouseRESTDiscoveryDriverPlugin driver() {
+    return new GravitinoLakehouseRESTDiscoveryDriverPlugin(
+        Collections.singletonList(new 
FakeProvider(Collections.singletonList("catalog_a"))));
+  }
+
+  private static class FakeProvider implements LakehouseRESTCatalogProvider {
+    private final List<String> catalogs;
+
+    private FakeProvider(List<String> catalogs) {
+      this.catalogs = new ArrayList<>(catalogs);
+    }
+
+    @Override
+    public String format() {
+      return "fake";
+    }
+
+    @Override
+    public List<String> listCatalogs(String uri, Map<String, String> 
catalogProperties) {
+      return catalogs;
+    }
+
+    @Override
+    public String catalogClassName() {
+      return String.class.getName();
+    }
+
+    @Override
+    public Map<String, String> generatedCatalogProperties(
+        String uri, String advertisedCatalogName) {
+      return ImmutableMap.of("impl", "rest", "uri", uri, "parent", 
advertisedCatalogName);
+    }
+
+    @Override
+    public String[] sparkExtensions() {
+      return new String[] {Runnable.class.getName()};
+    }
+  }
+
+  private static class FailingProvider implements LakehouseRESTCatalogProvider 
{
+    @Override
+    public String format() {
+      throw new AssertionError("Provider must not be loaded without a 
configured URI");
+    }
+
+    @Override
+    public List<String> listCatalogs(String uri, Map<String, String> 
catalogProperties) {
+      throw new AssertionError("Provider must not be called without a 
configured URI");
+    }
+
+    @Override
+    public String catalogClassName() {
+      throw new AssertionError("Provider must not be called without a 
configured URI");
+    }
+
+    @Override
+    public Map<String, String> generatedCatalogProperties(
+        String uri, String advertisedCatalogName) {
+      throw new AssertionError("Provider must not be called without a 
configured URI");
+    }
+
+    @Override
+    public String[] sparkExtensions() {
+      throw new AssertionError("Provider must not be called without a 
configured URI");
+    }
+  }
+
+  /** Policy used to verify user-owned catalogs are filtered before policy 
invocation. */
+  public static class TrackingPolicy implements CatalogRegistrationPolicy {
+    private static int invocationCount;
+
+    /** Creates the policy. */
+    public TrackingPolicy() {}
+
+    @Override
+    public boolean shouldRegister(String format, String catalogName) {
+      invocationCount++;
+      return true;
+    }

Review Comment:
   `TrackingPolicy.invocationCount` is a mutable static used for assertions; if 
the build enables JUnit 5 parallel execution, this test can become flaky due to 
cross-test interference. Prefer an `AtomicInteger` (or make the counter 
instance-scoped) to keep the test deterministic under parallel runs.



##########
spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/plugin/GravitinoLakehouseRESTDiscoveryDriverPlugin.java:
##########
@@ -0,0 +1,434 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.gravitino.spark.connector.plugin;
+
+import static org.apache.gravitino.spark.connector.ConnectorConstants.COMMA;
+import static 
org.apache.gravitino.spark.connector.utils.ConnectorUtil.removeDuplicateSparkExtensions;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import java.lang.reflect.InvocationTargetException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.ServiceConfigurationError;
+import java.util.ServiceLoader;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.spark.SparkConf;
+import org.apache.spark.SparkContext;
+import org.apache.spark.api.plugin.DriverPlugin;
+import org.apache.spark.api.plugin.PluginContext;
+import org.apache.spark.sql.catalyst.parser.CatalystSqlParser$;
+import org.apache.spark.sql.internal.StaticSQLConf;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import scala.Tuple2;
+import scala.collection.Seq;
+
+class GravitinoLakehouseRESTDiscoveryDriverPlugin implements DriverPlugin {
+
+  @VisibleForTesting
+  static final String REGISTRATION_POLICY_CONFIG = 
"spark.sql.gravitino.REST.registrationPolicy";
+
+  private static final Logger LOG =
+      
LoggerFactory.getLogger(GravitinoLakehouseRESTDiscoveryDriverPlugin.class);
+  private static final String GRAVITINO_PREFIX = "spark.sql.gravitino.";
+  private static final String SPARK_CATALOG_PREFIX = "spark.sql.catalog.";
+  private static final String URI_SUFFIX = "REST.uri";
+  private static final String CATALOG_PROPERTIES_INFIX = 
"REST.catalogProperties.";
+  private static final Pattern PROVIDER_URI_PATTERN =
+      
Pattern.compile("^spark\\.sql\\.gravitino\\.([A-Za-z][A-Za-z0-9]*)REST\\.uri$");
+  private static final CatalogRegistrationPolicy DEFAULT_POLICY = (format, 
catalogName) -> true;
+
+  private final List<LakehouseRESTCatalogProvider> providersForTesting;
+
+  GravitinoLakehouseRESTDiscoveryDriverPlugin() {
+    this.providersForTesting = null;
+  }
+
+  @VisibleForTesting
+  GravitinoLakehouseRESTDiscoveryDriverPlugin(
+      List<LakehouseRESTCatalogProvider> providersForTesting) {
+    this.providersForTesting = new ArrayList<>(providersForTesting);
+  }
+
+  @Override
+  public Map<String, String> init(SparkContext sc, PluginContext 
pluginContext) {
+    initialize(sc.conf());
+    return Collections.emptyMap();
+  }
+
+  @VisibleForTesting
+  void initialize(SparkConf sparkConf) {
+    validatePluginOrder(sparkConf);
+    SparkConf userConf = sparkConf.clone();
+    Map<String, String> activeFormats = findActiveFormats(userConf);
+    if (activeFormats.isEmpty()) {
+      return;
+    }
+
+    ClassLoader classLoader = contextClassLoader();
+    Map<String, LakehouseRESTCatalogProvider> providers = 
loadProviders(classLoader);
+    CatalogRegistrationPolicy policy = loadRegistrationPolicy(userConf, 
classLoader);
+    List<CatalogRegistration> registrations = new ArrayList<>();
+    Set<String> registeredNames = new LinkedHashSet<>();
+    Set<String> extensions = new LinkedHashSet<>();
+
+    activeFormats.forEach(
+        (format, uri) -> {
+          LakehouseRESTCatalogProvider provider = providers.get(format);
+          Preconditions.checkArgument(
+              provider != null,
+              "No lakehouse REST catalog provider found for configured format: 
%s",
+              format);
+          validateProviderRuntime(provider, classLoader);
+
+          Map<String, String> globalProperties = 
extractCatalogProperties(userConf, format);
+          List<String> advertisedCatalogs =
+              provider.listCatalogs(uri, 
Collections.unmodifiableMap(globalProperties));
+          Preconditions.checkState(
+              advertisedCatalogs != null,
+              "Lakehouse REST catalog provider %s returned a null catalog 
list",
+              format);
+
+          List<String> sortedCatalogs = new ArrayList<>(advertisedCatalogs);
+          Collections.sort(sortedCatalogs);
+          for (String catalogName : sortedCatalogs) {
+            addRegistration(
+                userConf,
+                provider,
+                policy,
+                format,
+                uri,
+                catalogName,
+                globalProperties,
+                registeredNames,
+                registrations);
+          }
+          extensions.addAll(Arrays.asList(provider.sparkExtensions()));
+        });
+
+    applyRegistrations(sparkConf, userConf, registrations);
+    registerSqlExtensions(sparkConf, extensions);
+  }
+
+  private static void validatePluginOrder(SparkConf sparkConf) {
+    String configuredPlugins = sparkConf.get("spark.plugins", "");
+    List<String> plugins = new ArrayList<>();
+    for (String plugin : configuredPlugins.split(COMMA)) {
+      if (StringUtils.isNotBlank(plugin)) {
+        plugins.add(plugin.trim());
+      }
+    }
+
+    int discoveryPluginIndex =
+        plugins.indexOf(GravitinoLakehouseRESTDiscoveryPlugin.class.getName());
+    int gravitinoPluginIndex = 
plugins.indexOf(GravitinoSparkPlugin.class.getName());
+    Preconditions.checkArgument(
+        discoveryPluginIndex < 0
+            || gravitinoPluginIndex < 0
+            || discoveryPluginIndex < gravitinoPluginIndex,
+        "%s must be listed before %s in spark.plugins",
+        GravitinoLakehouseRESTDiscoveryPlugin.class.getName(),
+        GravitinoSparkPlugin.class.getName());
+  }
+
+  private static Map<String, String> findActiveFormats(SparkConf userConf) {
+    Map<String, String> activeFormats = new TreeMap<>();
+    for (Tuple2<String, String> entry : userConf.getAll()) {
+      Matcher matcher = PROVIDER_URI_PATTERN.matcher(entry._1);
+      if (matcher.matches()) {
+        String format = matcher.group(1);
+        String uri = entry._2;
+        Preconditions.checkArgument(
+            StringUtils.isNotBlank(uri),
+            "%s%s%s must not be blank",
+            GRAVITINO_PREFIX,
+            format,
+            URI_SUFFIX);
+        activeFormats.put(format, uri);
+      }
+    }
+    return activeFormats;
+  }
+
+  private Map<String, LakehouseRESTCatalogProvider> loadProviders(ClassLoader 
classLoader) {
+    List<LakehouseRESTCatalogProvider> loadedProviders = new ArrayList<>();
+    if (providersForTesting != null) {
+      loadedProviders.addAll(providersForTesting);
+    } else {
+      try {
+        ServiceLoader.load(LakehouseRESTCatalogProvider.class, classLoader)
+            .forEach(loadedProviders::add);
+      } catch (ServiceConfigurationError e) {
+        throw new IllegalArgumentException("Failed to load lakehouse REST 
catalog providers", e);
+      }
+    }
+
+    Map<String, LakehouseRESTCatalogProvider> providers = new HashMap<>();
+    for (LakehouseRESTCatalogProvider provider : loadedProviders) {
+      String format = provider.format();
+      Preconditions.checkArgument(
+          StringUtils.isNotBlank(format), "Lakehouse REST catalog provider 
format is blank");
+      Preconditions.checkArgument(
+          format.matches("[A-Za-z][A-Za-z0-9]*"),
+          "Invalid lakehouse REST catalog provider format: %s",
+          format);
+      Preconditions.checkArgument(
+          providers.put(format, provider) == null,
+          "Multiple lakehouse REST catalog providers found for format: %s",
+          format);
+    }
+    return providers;
+  }
+
+  private static CatalogRegistrationPolicy loadRegistrationPolicy(
+      SparkConf userConf, ClassLoader classLoader) {
+    if (!userConf.contains(REGISTRATION_POLICY_CONFIG)) {
+      return DEFAULT_POLICY;
+    }
+
+    String policyClassName = userConf.get(REGISTRATION_POLICY_CONFIG);
+    Preconditions.checkArgument(
+        StringUtils.isNotBlank(policyClassName),
+        "%s must not be blank",
+        REGISTRATION_POLICY_CONFIG);
+    try {
+      Class<?> policyClass = Class.forName(policyClassName, true, classLoader);
+      Preconditions.checkArgument(
+          CatalogRegistrationPolicy.class.isAssignableFrom(policyClass),
+          "%s does not implement %s",
+          policyClassName,
+          CatalogRegistrationPolicy.class.getName());
+      return 
CatalogRegistrationPolicy.class.cast(policyClass.getConstructor().newInstance());
+    } catch (ClassNotFoundException
+        | NoSuchMethodException
+        | InstantiationException
+        | IllegalAccessException
+        | InvocationTargetException e) {
+      throw new IllegalArgumentException(
+          "Failed to instantiate catalog registration policy " + 
policyClassName, e);
+    }
+  }
+
+  private static void validateProviderRuntime(
+      LakehouseRESTCatalogProvider provider, ClassLoader classLoader) {
+    validateRuntimeClass(provider.format(), provider.catalogClassName(), 
classLoader);
+    String[] providerExtensions = provider.sparkExtensions();
+    Preconditions.checkState(
+        providerExtensions != null,
+        "Lakehouse REST catalog provider %s returned null Spark extensions",
+        provider.format());
+    for (String extension : providerExtensions) {
+      validateRuntimeClass(provider.format(), extension, classLoader);
+    }
+  }
+
+  private static void validateRuntimeClass(
+      String format, String className, ClassLoader classLoader) {
+    Preconditions.checkState(
+        StringUtils.isNotBlank(className),
+        "Lakehouse REST catalog provider %s returned a blank runtime class",
+        format);
+    try {
+      Class.forName(className, false, classLoader);
+    } catch (ClassNotFoundException | LinkageError e) {
+      throw new IllegalArgumentException(
+          String.format(
+              "Required runtime class %s for lakehouse REST format %s is not 
available",
+              className, format),
+          e);
+    }
+  }
+
+  private static Map<String, String> extractCatalogProperties(SparkConf 
userConf, String format) {
+    String prefix = GRAVITINO_PREFIX + format + CATALOG_PROPERTIES_INFIX;
+    Map<String, String> properties = new LinkedHashMap<>();
+    for (Tuple2<String, String> entry : userConf.getAllWithPrefix(prefix)) {
+      Preconditions.checkArgument(
+          StringUtils.isNotBlank(entry._1), "%s must include a property name", 
prefix);
+      properties.put(entry._1, entry._2);
+    }
+    return properties;
+  }
+
+  private static void addRegistration(
+      SparkConf userConf,
+      LakehouseRESTCatalogProvider provider,
+      CatalogRegistrationPolicy policy,
+      String format,
+      String uri,
+      String advertisedCatalogName,
+      Map<String, String> globalProperties,
+      Set<String> registeredNames,
+      List<CatalogRegistration> registrations) {
+    Preconditions.checkState(
+        StringUtils.isNotBlank(advertisedCatalogName),
+        "Lakehouse REST catalog provider %s advertised a blank catalog name",
+        format);
+    if (userConf.contains(SPARK_CATALOG_PREFIX + advertisedCatalogName)) {
+      LOG.info(
+          "Skip auto-registering {} catalog {} because it is configured by the 
user.",
+          format,
+          advertisedCatalogName);
+      return;
+    }
+    if (!policy.shouldRegister(format, advertisedCatalogName)) {
+      return;
+    }
+
+    String registeredCatalogName = policy.registeredCatalogName(format, 
advertisedCatalogName);
+    validateCatalogName(registeredCatalogName);
+    Preconditions.checkArgument(
+        !userConf.contains(SPARK_CATALOG_PREFIX + registeredCatalogName),
+        "Catalog registration policy returned name %s, which is configured by 
the user",
+        registeredCatalogName);
+    Preconditions.checkArgument(
+        registeredNames.add(registeredCatalogName),
+        "Catalog registration policy returned duplicate name: %s",
+        registeredCatalogName);
+
+    Map<String, String> generatedProperties =
+        provider.generatedCatalogProperties(uri, advertisedCatalogName);
+    Preconditions.checkState(
+        generatedProperties != null,
+        "Lakehouse REST catalog provider %s returned null generated 
properties",
+        format);
+    Map<String, String> mergedProperties = new 
LinkedHashMap<>(globalProperties);
+    generatedProperties.forEach(
+        (key, value) -> {
+          Preconditions.checkState(
+              StringUtils.isNotBlank(key),
+              "Lakehouse REST catalog provider %s returned a blank property 
name",
+              format);
+          Preconditions.checkState(
+              value != null,
+              "Lakehouse REST catalog provider %s returned null for property 
%s",
+              format,
+              key);
+          mergedProperties.put(key, value);
+        });
+
+    registrations.add(
+        new CatalogRegistration(
+            format,
+            advertisedCatalogName,
+            registeredCatalogName,
+            provider.catalogClassName(),
+            mergedProperties));
+  }
+
+  private static void validateCatalogName(String catalogName) {
+    Preconditions.checkArgument(
+        StringUtils.isNotBlank(catalogName),
+        "Catalog registration policy returned a blank catalog name");
+    try {
+      Seq<String> parts = 
CatalystSqlParser$.MODULE$.parseMultipartIdentifier(catalogName);
+      Preconditions.checkArgument(
+          parts.size() == 1 && catalogName.equals(parts.apply(0)),
+          "Catalog registration policy returned invalid Spark identifier: %s",
+          catalogName);
+    } catch (Exception e) {
+      throw new IllegalArgumentException(
+          "Catalog registration policy returned invalid Spark identifier: " + 
catalogName, e);
+    }
+  }
+
+  private static void applyRegistrations(
+      SparkConf sparkConf, SparkConf userConf, List<CatalogRegistration> 
registrations) {
+    for (CatalogRegistration registration : registrations) {
+      String catalogPrefix = SPARK_CATALOG_PREFIX + 
registration.registeredCatalogName;
+      sparkConf.set(catalogPrefix, registration.catalogClassName);
+      registration.properties.forEach(
+          (key, value) -> {
+            String sparkConfigKey = catalogPrefix + "." + key;
+            if (!userConf.contains(sparkConfigKey)) {
+              sparkConf.set(sparkConfigKey, value);
+            }
+          });
+      if 
(!registration.advertisedCatalogName.equals(registration.registeredCatalogName))
 {
+        LOG.info(
+            "Register {} REST catalog {} as Spark catalog {}.",
+            registration.format,
+            registration.advertisedCatalogName,
+            registration.registeredCatalogName);
+      } else {
+        LOG.info(
+            "Register {} REST catalog {} in Spark.",
+            registration.format,
+            registration.advertisedCatalogName);
+      }
+    }
+  }
+
+  private static void registerSqlExtensions(SparkConf sparkConf, Set<String> 
extensions) {
+    if (extensions.isEmpty()) {
+      return;
+    }
+
+    String extensionsKey = StaticSQLConf.SPARK_SESSION_EXTENSIONS().key();
+    String[] providerExtensions = extensions.toArray(new String[0]);
+    if (sparkConf.contains(extensionsKey) && 
StringUtils.isNotBlank(sparkConf.get(extensionsKey))) {
+      sparkConf.set(
+          extensionsKey,
+          removeDuplicateSparkExtensions(
+              providerExtensions, sparkConf.get(extensionsKey).split(COMMA)));

Review Comment:
   Splitting `spark.sql.extensions` on `,` without trimming/filtering can 
preserve whitespace (e.g., `"a, b"` → `" b"`) which may prevent deduplication 
and can yield invalid class names at Spark load time. Trim tokens and drop 
blanks before passing them to `removeDuplicateSparkExtensions` (and before 
joining) so the resulting config is robust to user formatting.



##########
spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/plugin/TestGravitinoLakehouseRESTDiscoveryDriverPlugin.java:
##########
@@ -0,0 +1,317 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.gravitino.spark.connector.plugin;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import com.google.common.collect.ImmutableMap;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import org.apache.spark.SparkConf;
+import org.apache.spark.sql.internal.StaticSQLConf;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+public class TestGravitinoLakehouseRESTDiscoveryDriverPlugin {
+
+  private static final String DISCOVERY_PLUGIN =
+      GravitinoLakehouseRESTDiscoveryPlugin.class.getName();
+  private static final String GRAVITINO_PLUGIN = 
GravitinoSparkPlugin.class.getName();
+  private static final String URI_CONFIG = "spark.sql.gravitino.fakeREST.uri";
+  private static final String CATALOG_PREFIX = "spark.sql.catalog.";
+
+  @BeforeEach
+  void resetPolicies() {
+    TrackingPolicy.invocationCount = 0;
+  }
+
+  @Test
+  void testRequiresDiscoveryPluginBeforeGravitinoPlugin() {
+    SparkConf sparkConf =
+        baseConf().set("spark.plugins", GRAVITINO_PLUGIN + "," + 
DISCOVERY_PLUGIN);
+
+    IllegalArgumentException exception =
+        assertThrows(IllegalArgumentException.class, () -> 
driver().initialize(sparkConf));
+
+    assertTrue(exception.getMessage().contains("must be listed before"));
+    assertFalse(sparkConf.contains(CATALOG_PREFIX + "catalog_a"));
+  }
+
+  @Test
+  void testNoConfiguredUriDoesNotChangeSparkConf() {
+    SparkConf sparkConf =
+        new SparkConf(false).set("spark.plugins", DISCOVERY_PLUGIN + "," + 
GRAVITINO_PLUGIN);
+
+    new GravitinoLakehouseRESTDiscoveryDriverPlugin(
+            Collections.singletonList(new FailingProvider()))
+        .initialize(sparkConf);
+
+    
assertFalse(sparkConf.contains(StaticSQLConf.SPARK_SESSION_EXTENSIONS().key()));
+  }
+
+  @Test
+  void testGeneratedConfigurationAndPrecedence() {
+    SparkConf sparkConf =
+        baseConf()
+            .set("spark.sql.gravitino.fakeREST.catalogProperties.impl", 
"global-impl")
+            .set("spark.sql.gravitino.fakeREST.catalogProperties.uri", 
"global-uri")
+            .set("spark.sql.gravitino.fakeREST.catalogProperties.extra", 
"global-extra")
+            .set(CATALOG_PREFIX + "catalog_a.uri", "user-uri")
+            .set(
+                StaticSQLConf.SPARK_SESSION_EXTENSIONS().key(),
+                "example.UserExtension,java.lang.Runnable");
+
+    driver().initialize(sparkConf);
+
+    assertEquals(String.class.getName(), sparkConf.get(CATALOG_PREFIX + 
"catalog_a"));
+    assertEquals("rest", sparkConf.get(CATALOG_PREFIX + "catalog_a.impl"));
+    assertEquals("user-uri", sparkConf.get(CATALOG_PREFIX + "catalog_a.uri"));
+    assertEquals("catalog_a", sparkConf.get(CATALOG_PREFIX + 
"catalog_a.parent"));
+    assertEquals("global-extra", sparkConf.get(CATALOG_PREFIX + 
"catalog_a.extra"));
+    assertEquals(
+        "java.lang.Runnable,example.UserExtension",
+        sparkConf.get(StaticSQLConf.SPARK_SESSION_EXTENSIONS().key()));
+  }
+
+  @Test
+  void testUserOwnedCatalogDoesNotReachPolicy() {
+    SparkConf sparkConf =
+        baseConf()
+            .set(CATALOG_PREFIX + "catalog_a", "example.UserCatalog")
+            .set(
+                
GravitinoLakehouseRESTDiscoveryDriverPlugin.REGISTRATION_POLICY_CONFIG,
+                TrackingPolicy.class.getName());
+
+    driver().initialize(sparkConf);
+
+    assertEquals(0, TrackingPolicy.invocationCount);
+    assertEquals("example.UserCatalog", sparkConf.get(CATALOG_PREFIX + 
"catalog_a"));
+    assertFalse(sparkConf.contains(CATALOG_PREFIX + "catalog_a.parent"));
+  }
+
+  @Test
+  void testPolicyFiltersAndRenamesCatalogs() {
+    FakeProvider provider = new FakeProvider(Arrays.asList("catalog_a", 
"catalog_b"));
+    SparkConf sparkConf =
+        baseConf()
+            .set(
+                
GravitinoLakehouseRESTDiscoveryDriverPlugin.REGISTRATION_POLICY_CONFIG,
+                RenamePolicy.class.getName());
+
+    new 
GravitinoLakehouseRESTDiscoveryDriverPlugin(Collections.singletonList(provider))
+        .initialize(sparkConf);
+
+    assertFalse(sparkConf.contains(CATALOG_PREFIX + "catalog_a"));
+    assertEquals(String.class.getName(), sparkConf.get(CATALOG_PREFIX + 
"renamed_b"));
+    assertEquals("catalog_b", sparkConf.get(CATALOG_PREFIX + 
"renamed_b.parent"));
+  }
+
+  @Test
+  void testDuplicatePolicyOutputDoesNotPartiallyModifySparkConf() {
+    FakeProvider provider = new FakeProvider(Arrays.asList("catalog_a", 
"catalog_b"));
+    SparkConf sparkConf =
+        baseConf()
+            .set(
+                
GravitinoLakehouseRESTDiscoveryDriverPlugin.REGISTRATION_POLICY_CONFIG,
+                DuplicatePolicy.class.getName());
+
+    IllegalArgumentException exception =
+        assertThrows(
+            IllegalArgumentException.class,
+            () ->
+                new 
GravitinoLakehouseRESTDiscoveryDriverPlugin(Collections.singletonList(provider))
+                    .initialize(sparkConf));
+
+    assertTrue(exception.getMessage().contains("duplicate name"));
+    assertFalse(sparkConf.contains(CATALOG_PREFIX + "duplicate"));
+    
assertFalse(sparkConf.contains(StaticSQLConf.SPARK_SESSION_EXTENSIONS().key()));
+  }
+
+  @Test
+  void testInvalidPolicyOutputFails() {
+    SparkConf sparkConf =
+        baseConf()
+            .set(
+                
GravitinoLakehouseRESTDiscoveryDriverPlugin.REGISTRATION_POLICY_CONFIG,
+                InvalidNamePolicy.class.getName());
+
+    IllegalArgumentException exception =
+        assertThrows(IllegalArgumentException.class, () -> 
driver().initialize(sparkConf));
+
+    assertTrue(exception.getMessage().contains("invalid Spark identifier"));
+    assertFalse(sparkConf.contains(CATALOG_PREFIX + "invalid-name"));
+  }
+
+  @Test
+  void testConfiguredFormatWithoutProviderFails() {
+    SparkConf sparkConf = baseConf();
+
+    IllegalArgumentException exception =
+        assertThrows(
+            IllegalArgumentException.class,
+            () ->
+                new 
GravitinoLakehouseRESTDiscoveryDriverPlugin(Collections.emptyList())
+                    .initialize(sparkConf));
+
+    assertTrue(exception.getMessage().contains("No lakehouse REST catalog 
provider"));
+  }
+
+  private static SparkConf baseConf() {
+    return new SparkConf(false).set("spark.plugins", 
DISCOVERY_PLUGIN).set(URI_CONFIG, "rest-uri");
+  }
+
+  private static GravitinoLakehouseRESTDiscoveryDriverPlugin driver() {
+    return new GravitinoLakehouseRESTDiscoveryDriverPlugin(
+        Collections.singletonList(new 
FakeProvider(Collections.singletonList("catalog_a"))));
+  }
+
+  private static class FakeProvider implements LakehouseRESTCatalogProvider {
+    private final List<String> catalogs;
+
+    private FakeProvider(List<String> catalogs) {
+      this.catalogs = new ArrayList<>(catalogs);
+    }
+
+    @Override
+    public String format() {
+      return "fake";
+    }
+
+    @Override
+    public List<String> listCatalogs(String uri, Map<String, String> 
catalogProperties) {
+      return catalogs;
+    }
+
+    @Override
+    public String catalogClassName() {
+      return String.class.getName();
+    }
+
+    @Override
+    public Map<String, String> generatedCatalogProperties(
+        String uri, String advertisedCatalogName) {
+      return ImmutableMap.of("impl", "rest", "uri", uri, "parent", 
advertisedCatalogName);
+    }
+
+    @Override
+    public String[] sparkExtensions() {
+      return new String[] {Runnable.class.getName()};
+    }
+  }
+
+  private static class FailingProvider implements LakehouseRESTCatalogProvider 
{
+    @Override
+    public String format() {
+      throw new AssertionError("Provider must not be loaded without a 
configured URI");
+    }
+
+    @Override
+    public List<String> listCatalogs(String uri, Map<String, String> 
catalogProperties) {
+      throw new AssertionError("Provider must not be called without a 
configured URI");
+    }
+
+    @Override
+    public String catalogClassName() {
+      throw new AssertionError("Provider must not be called without a 
configured URI");
+    }
+
+    @Override
+    public Map<String, String> generatedCatalogProperties(
+        String uri, String advertisedCatalogName) {
+      throw new AssertionError("Provider must not be called without a 
configured URI");
+    }
+
+    @Override
+    public String[] sparkExtensions() {
+      throw new AssertionError("Provider must not be called without a 
configured URI");
+    }
+  }
+
+  /** Policy used to verify user-owned catalogs are filtered before policy 
invocation. */
+  public static class TrackingPolicy implements CatalogRegistrationPolicy {
+    private static int invocationCount;

Review Comment:
   `TrackingPolicy.invocationCount` is a mutable static used for assertions; if 
the build enables JUnit 5 parallel execution, this test can become flaky due to 
cross-test interference. Prefer an `AtomicInteger` (or make the counter 
instance-scoped) to keep the test deterministic under parallel runs.



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

Reply via email to