You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@gravitino.apache.org by "FANNG1 (via GitHub)" <gi...@apache.org> on 2026/08/21 01:04:36 UTC

[PR] [#12525] feat(spark-connector): Add lakehouse REST catalog discovery [gravitino]

FANNG1 opened a new pull request, #12541:
URL: https://github.com/apache/gravitino/pull/12541

   ### What changes were proposed in this pull request?
   
   Add `GravitinoLakehouseRESTDiscoveryPlugin`, a format-agnostic Spark plugin that
   discovers lakehouse REST catalogs and registers them during driver startup.
   
   This change:
   
   - Adds provider and registration policy APIs.
   - Enforces user configuration precedence and atomic Spark configuration updates.
   - Adds a Lance provider using the Lance Namespace API with pagination support.
   - Injects the required Lance Spark extension.
   - Treats catalogs already configured in Spark as normal skips in `GravitinoDriverPlugin`.
   - Adds unit tests, Lance integration coverage, and user documentation.
   
   ### Why are the changes needed?
   
   Spark users currently need to configure every Lance REST catalog manually.
   Automatic discovery allows the Lance REST server to provide the authoritative
   catalog list while preserving user-defined Spark catalog configuration.
   
   Fix: #12525
   
   ### Does this PR introduce _any_ user-facing change?
   
   Yes.
   
   Users can enable Lance REST catalog discovery with:
   
   ```text
   spark.plugins=org.apache.gravitino.spark.connector.plugin.GravitinoLakehouseRESTDiscoveryPlugin
   spark.sql.gravitino.lanceREST.uri=http://127.0.0.1:9101/lance
   ```
   
   The change also introduces:
   
   - `CatalogRegistrationPolicy`
   - `LakehouseRESTCatalogProvider`
   - `spark.sql.gravitino.REST.registrationPolicy`
   - `spark.sql.gravitino.lanceREST.catalogProperties.<key>`
   
   Authenticated Lance REST listing is not supported in this change.
   
   ### How was this patch tested?
   
   - `./gradlew :spark-connector:spark-common:check`
   - Lance Spark integration matrix with bundle versions 0.2.0, 0.4.0, and 0.5.1.
   - Spark 3.3, 3.4, and 3.5 runtime shadow JAR builds.
   - Packaged runtime smoke test using only the shadow runtime and external Lance bundle.
   - Verified the packaged provider has no shaded Apache HttpClient linkage.
   - `git diff --check`


-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12525] feat(spark-connector): Add lakehouse REST catalog discovery for lance [gravitino]

Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #12541:
URL: https://github.com/apache/gravitino/pull/12541#discussion_r3976602801


##########
spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/plugin/restcatalog/lance/LanceRESTCatalogProvider.java:
##########
@@ -0,0 +1,121 @@
+/*
+ * 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.restcatalog.lance;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableMap;
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.spark.connector.plugin.restcatalog.LakehouseRESTCatalogProvider;
+import org.lance.namespace.client.apache.ApiClient;
+import org.lance.namespace.client.apache.ApiException;
+import org.lance.namespace.client.apache.api.NamespaceApi;
+import org.lance.namespace.model.ListNamespacesResponse;
+
+/** Discovers and configures Lance REST catalogs. */
+public class LanceRESTCatalogProvider implements LakehouseRESTCatalogProvider {
+
+  static final String FORMAT = "lance";
+  static final String CATALOG_CLASS = "org.lance.spark.LanceNamespaceSparkCatalog";
+  static final String SPARK_EXTENSIONS = "org.lance.spark.extensions.LanceSparkSessionExtensions";
+
+  private static final String ROOT_NAMESPACE_ID = "$";
+  private static final String NAMESPACE_DELIMITER = "$";
+
+  @Override
+  public String format() {
+    return FORMAT;
+  }
+
+  @Override
+  public List<String> listCatalogs(String uri, Map<String, String> catalogProperties) {
+    List<String> catalogs = new ArrayList<>();
+    Set<String> seenPageTokens = new HashSet<>();
+    String pageToken = null;
+
+    ApiClient apiClient = new ApiClient().setBasePath(normalizeUri(uri));
+    try (Closeable httpClient = getHttpClient(apiClient)) {
+      NamespaceApi namespaceApi = new NamespaceApi(apiClient);
+      do {
+        ListNamespacesResponse response =
+            namespaceApi.listNamespaces(ROOT_NAMESPACE_ID, NAMESPACE_DELIMITER, pageToken, null);
+        Preconditions.checkState(response != null, "Lance REST server returned an empty response");
+        Preconditions.checkState(
+            response.getNamespaces() != null,
+            "Lance REST server returned a response without namespaces");
+        catalogs.addAll(response.getNamespaces());
+
+        pageToken = StringUtils.trimToNull(response.getPageToken());
+        Preconditions.checkState(
+            pageToken == null || seenPageTokens.add(pageToken),
+            "Lance REST server returned repeated page token: %s",
+            pageToken);
+      } while (pageToken != null);
+    } catch (ApiException | IOException e) {
+      throw new IllegalStateException("Failed to list catalogs from Lance REST server " + uri, e);
+    }
+
+    return catalogs;
+  }
+
+  @Override
+  public String catalogClassName() {
+    return CATALOG_CLASS;
+  }
+
+  @Override
+  public Map<String, String> generatedCatalogProperties(String uri, String advertisedCatalogName) {

Review Comment:
   What is the meaning of `advertised` here?



##########
spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/plugin/restcatalog/GravitinoLakehouseRESTDiscoveryDriverPlugin.java:
##########
@@ -0,0 +1,420 @@
+/*
+ * 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.restcatalog;
+
+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.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+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.gravitino.spark.connector.plugin.GravitinoSparkPlugin;
+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;
+
+  GravitinoLakehouseRESTDiscoveryDriverPlugin() {}
+
+  @Override
+  public Map<String, String> init(SparkContext sc, PluginContext pluginContext) {
+    initialize(sc.conf());
+    return Collections.emptyMap();
+  }
+
+  @VisibleForTesting
+  void initialize(SparkConf sparkConf) {
+    initialize(sparkConf, BuiltinRESTCatalogProviders.providerClassNames());
+  }
+
+  @VisibleForTesting
+  void initialize(SparkConf sparkConf, Map<String, String> providerClassNames) {
+    validatePluginOrder(sparkConf);
+    SparkConf userConf = sparkConf.clone();
+    Map<String, String> activeFormats = findActiveFormats(userConf);
+    if (activeFormats.isEmpty()) {
+      return;
+    }
+
+    ClassLoader classLoader = contextClassLoader();
+    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 =
+              loadProvider(format, providerClassNames, classLoader);
+          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);

Review Comment:
   Why do we need to sort them?



##########
spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/plugin/restcatalog/CatalogRegistrationPolicy.java:
##########
@@ -0,0 +1,47 @@
+/*
+ * 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.restcatalog;
+
+import org.apache.gravitino.annotation.DeveloperApi;
+
+/** Decides whether an advertised REST catalog is registered, and under what Spark name. */
+@DeveloperApi
+public interface CatalogRegistrationPolicy {
+
+  /**
+   * Returns whether to register an advertised catalog automatically.
+   *
+   * @param format the lakehouse format that advertised the catalog
+   * @param catalogName the catalog name advertised by the format's REST server
+   * @return true to register the catalog, false to skip it
+   */
+  boolean shouldRegister(String format, String catalogName);

Review Comment:
   So the default value is `true` or `false`? I mean: for each catalog, will we register it or not by default?



##########
spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/plugin/restcatalog/BuiltinRESTCatalogProviders.java:
##########
@@ -0,0 +1,38 @@
+/*
+ * 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.restcatalog;
+
+import java.util.Collections;
+import java.util.Map;
+
+final class BuiltinRESTCatalogProviders {
+
+  private static final String LANCE_FORMAT = "lance";

Review Comment:
   Will `iceberg` also be added in the future?



##########
spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/plugin/restcatalog/GravitinoLakehouseRESTDiscoveryDriverPlugin.java:
##########
@@ -0,0 +1,420 @@
+/*
+ * 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.restcatalog;
+
+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.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+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.gravitino.spark.connector.plugin.GravitinoSparkPlugin;
+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;
+
+  GravitinoLakehouseRESTDiscoveryDriverPlugin() {}
+
+  @Override
+  public Map<String, String> init(SparkContext sc, PluginContext pluginContext) {
+    initialize(sc.conf());
+    return Collections.emptyMap();
+  }
+
+  @VisibleForTesting
+  void initialize(SparkConf sparkConf) {
+    initialize(sparkConf, BuiltinRESTCatalogProviders.providerClassNames());
+  }
+
+  @VisibleForTesting
+  void initialize(SparkConf sparkConf, Map<String, String> providerClassNames) {
+    validatePluginOrder(sparkConf);
+    SparkConf userConf = sparkConf.clone();
+    Map<String, String> activeFormats = findActiveFormats(userConf);
+    if (activeFormats.isEmpty()) {
+      return;
+    }
+
+    ClassLoader classLoader = contextClassLoader();
+    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 =
+              loadProvider(format, providerClassNames, classLoader);
+          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 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());

Review Comment:
   `policyClass.getConstructor().newInstance()` depends on a constructor with empty parameter; you'd better add some restriction or description on the `Policy`.



##########
spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/plugin/restcatalog/GravitinoLakehouseRESTDiscoveryDriverPlugin.java:
##########
@@ -0,0 +1,420 @@
+/*
+ * 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.restcatalog;
+
+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.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+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.gravitino.spark.connector.plugin.GravitinoSparkPlugin;
+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;
+
+  GravitinoLakehouseRESTDiscoveryDriverPlugin() {}
+
+  @Override
+  public Map<String, String> init(SparkContext sc, PluginContext pluginContext) {
+    initialize(sc.conf());
+    return Collections.emptyMap();
+  }
+
+  @VisibleForTesting
+  void initialize(SparkConf sparkConf) {
+    initialize(sparkConf, BuiltinRESTCatalogProviders.providerClassNames());
+  }
+
+  @VisibleForTesting
+  void initialize(SparkConf sparkConf, Map<String, String> providerClassNames) {
+    validatePluginOrder(sparkConf);
+    SparkConf userConf = sparkConf.clone();
+    Map<String, String> activeFormats = findActiveFormats(userConf);
+    if (activeFormats.isEmpty()) {
+      return;
+    }
+
+    ClassLoader classLoader = contextClassLoader();
+    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 =
+              loadProvider(format, providerClassNames, classLoader);
+          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 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 LakehouseRESTCatalogProvider loadProvider(
+      String format, Map<String, String> providerClassNames, ClassLoader classLoader) {
+    String providerClassName = providerClassNames.get(format);
+    Preconditions.checkArgument(
+        providerClassName != null,
+        "No lakehouse REST catalog provider found for configured format: %s",
+        format);
+    try {
+      Class<?> providerClass = Class.forName(providerClassName, true, classLoader);
+      Preconditions.checkArgument(
+          LakehouseRESTCatalogProvider.class.isAssignableFrom(providerClass),
+          "%s does not implement %s",
+          providerClassName,
+          LakehouseRESTCatalogProvider.class.getName());
+      return providerClass
+          .asSubclass(LakehouseRESTCatalogProvider.class)
+          .getConstructor()
+          .newInstance();
+    } catch (ReflectiveOperationException | LinkageError e) {
+      throw new IllegalArgumentException(
+          String.format(
+              "Failed to instantiate lakehouse REST catalog provider %s for format %s",
+              providerClassName, format),
+          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(

Review Comment:
   loadRuntimeClass



-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12525] feat(spark-connector): Add lakehouse REST catalog discovery for lance [gravitino]

Posted by "FANNG1 (via GitHub)" <gi...@apache.org>.
FANNG1 commented on code in PR #12541:
URL: https://github.com/apache/gravitino/pull/12541#discussion_r3977641545


##########
spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/plugin/restcatalog/lance/LanceRESTCatalogProvider.java:
##########
@@ -0,0 +1,121 @@
+/*
+ * 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.restcatalog.lance;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableMap;
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.spark.connector.plugin.restcatalog.LakehouseRESTCatalogProvider;
+import org.lance.namespace.client.apache.ApiClient;
+import org.lance.namespace.client.apache.ApiException;
+import org.lance.namespace.client.apache.api.NamespaceApi;
+import org.lance.namespace.model.ListNamespacesResponse;
+
+/** Discovers and configures Lance REST catalogs. */
+public class LanceRESTCatalogProvider implements LakehouseRESTCatalogProvider {
+
+  static final String FORMAT = "lance";
+  static final String CATALOG_CLASS = "org.lance.spark.LanceNamespaceSparkCatalog";
+  static final String SPARK_EXTENSIONS = "org.lance.spark.extensions.LanceSparkSessionExtensions";
+
+  private static final String ROOT_NAMESPACE_ID = "$";
+  private static final String NAMESPACE_DELIMITER = "$";
+
+  @Override
+  public String format() {
+    return FORMAT;
+  }
+
+  @Override
+  public List<String> listCatalogs(String uri, Map<String, String> catalogProperties) {
+    List<String> catalogs = new ArrayList<>();
+    Set<String> seenPageTokens = new HashSet<>();
+    String pageToken = null;
+
+    ApiClient apiClient = new ApiClient().setBasePath(normalizeUri(uri));
+    try (Closeable httpClient = getHttpClient(apiClient)) {
+      NamespaceApi namespaceApi = new NamespaceApi(apiClient);
+      do {
+        ListNamespacesResponse response =
+            namespaceApi.listNamespaces(ROOT_NAMESPACE_ID, NAMESPACE_DELIMITER, pageToken, null);

Review Comment:
   Good catch. I will add `spark.sql.gravitino.lanceREST.catalogProperties.namespaceDelimiter`, defaulting to `$`, and pass it to the `listNamespaces` request. I will also add coverage for a non-default delimiter and reject blank values.



-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12525] feat(spark-connector): Add lakehouse REST catalog discovery for lance [gravitino]

Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #12541:
URL: https://github.com/apache/gravitino/pull/12541#discussion_r3976544917


##########
spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/plugin/restcatalog/lance/LanceRESTCatalogProvider.java:
##########
@@ -0,0 +1,121 @@
+/*
+ * 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.restcatalog.lance;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableMap;
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.spark.connector.plugin.restcatalog.LakehouseRESTCatalogProvider;
+import org.lance.namespace.client.apache.ApiClient;
+import org.lance.namespace.client.apache.ApiException;
+import org.lance.namespace.client.apache.api.NamespaceApi;
+import org.lance.namespace.model.ListNamespacesResponse;
+
+/** Discovers and configures Lance REST catalogs. */
+public class LanceRESTCatalogProvider implements LakehouseRESTCatalogProvider {
+
+  static final String FORMAT = "lance";
+  static final String CATALOG_CLASS = "org.lance.spark.LanceNamespaceSparkCatalog";
+  static final String SPARK_EXTENSIONS = "org.lance.spark.extensions.LanceSparkSessionExtensions";
+
+  private static final String ROOT_NAMESPACE_ID = "$";
+  private static final String NAMESPACE_DELIMITER = "$";
+
+  @Override
+  public String format() {
+    return FORMAT;
+  }
+
+  @Override
+  public List<String> listCatalogs(String uri, Map<String, String> catalogProperties) {
+    List<String> catalogs = new ArrayList<>();
+    Set<String> seenPageTokens = new HashSet<>();
+    String pageToken = null;
+
+    ApiClient apiClient = new ApiClient().setBasePath(normalizeUri(uri));
+    try (Closeable httpClient = getHttpClient(apiClient)) {
+      NamespaceApi namespaceApi = new NamespaceApi(apiClient);
+      do {
+        ListNamespacesResponse response =
+            namespaceApi.listNamespaces(ROOT_NAMESPACE_ID, NAMESPACE_DELIMITER, pageToken, null);

Review Comment:
   What if the separator is not `$`? `$` is the default separator, and the user can customize it. 



-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12525] feat(spark-connector): Add lakehouse REST catalog discovery for lance [gravitino]

Posted by "FANNG1 (via GitHub)" <gi...@apache.org>.
FANNG1 commented on code in PR #12541:
URL: https://github.com/apache/gravitino/pull/12541#discussion_r3977644941


##########
spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/plugin/restcatalog/BuiltinRESTCatalogProviders.java:
##########
@@ -0,0 +1,38 @@
+/*
+ * 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.restcatalog;
+
+import java.util.Collections;
+import java.util.Map;
+
+final class BuiltinRESTCatalogProviders {
+
+  private static final String LANCE_FORMAT = "lance";

Review Comment:
   Not in this PR. This PR wires only the Lance provider; the built-in registry is structured so another format-specific provider, such as Iceberg, can be added later with its own runtime and configuration contract.



##########
spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/plugin/restcatalog/CatalogRegistrationPolicy.java:
##########
@@ -0,0 +1,47 @@
+/*
+ * 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.restcatalog;
+
+import org.apache.gravitino.annotation.DeveloperApi;
+
+/** Decides whether an advertised REST catalog is registered, and under what Spark name. */
+@DeveloperApi
+public interface CatalogRegistrationPolicy {
+
+  /**
+   * Returns whether to register an advertised catalog automatically.
+   *
+   * @param format the lakehouse format that advertised the catalog
+   * @param catalogName the catalog name advertised by the format's REST server
+   * @return true to register the catalog, false to skip it
+   */
+  boolean shouldRegister(String format, String catalogName);

Review Comment:
   The default is `true`: every discovered catalog is registered under its discovered name unless that Spark catalog name is already explicitly configured by the user. I will make this default explicit in the policy Javadoc.



-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12525] feat(spark-connector): Add lakehouse REST catalog discovery for lance [gravitino]

Posted by "FANNG1 (via GitHub)" <gi...@apache.org>.
FANNG1 commented on PR #12541:
URL: https://github.com/apache/gravitino/pull/12541#issuecomment-5435133827

   The CI failure seems not related.


-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12525] feat(spark-connector): Add lakehouse REST catalog discovery for lance [gravitino]

Posted by "FANNG1 (via GitHub)" <gi...@apache.org>.
FANNG1 commented on PR #12541:
URL: https://github.com/apache/gravitino/pull/12541#issuecomment-5715007470

    @roryqi @diqiu50 any other comments?


-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12525] feat(spark-connector): Add lakehouse REST catalog discovery for lance [gravitino]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12525] feat(spark-connector): Add lakehouse REST catalog discovery for lance [gravitino]

Posted by "roryqi (via GitHub)" <gi...@apache.org>.
roryqi commented on code in PR #12541:
URL: https://github.com/apache/gravitino/pull/12541#discussion_r4012627009


##########
spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/plugin/restcatalog/BuiltinRESTCatalogProviders.java:
##########
@@ -0,0 +1,38 @@
+/*
+ * 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.restcatalog;

Review Comment:
   Ok.



-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12525] feat(spark-connector): Add lakehouse REST catalog discovery for lance [gravitino]

Posted by "FANNG1 (via GitHub)" <gi...@apache.org>.
FANNG1 commented on code in PR #12541:
URL: https://github.com/apache/gravitino/pull/12541#discussion_r3869186112


##########
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:
   Fixed. The  mechanism has been removed.  now stores only format-to-provider-FQCN strings, and the driver reflectively loads only the provider for an active configured format after detecting its . The common package has no static reference to the Lance provider or Lance SDK classes.



##########
spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/plugin/restcatalog/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:
   We do not enable JUnit 5 parallel execution in this project. Also, replacing this with an  would make increments atomic but would not isolate the reset/increment sequence across concurrently executing test methods, so it would not solve the described interference. The counter is intentionally static because the policy instance is created reflectively, and it is reset in .



##########
spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/plugin/restcatalog/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:
   We do not enable JUnit 5 parallel execution in this project. Also, replacing this with an  would make increments atomic but would not isolate the reset/increment sequence across concurrently executing test methods, so it would not solve the described interference. The counter is intentionally static because the policy instance is created reflectively, and it is reset in .



-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12525] feat(spark-connector): Add lakehouse REST catalog discovery for lance [gravitino]

Posted by "FANNG1 (via GitHub)" <gi...@apache.org>.
FANNG1 commented on code in PR #12541:
URL: https://github.com/apache/gravitino/pull/12541#discussion_r3977642732


##########
spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/plugin/restcatalog/GravitinoLakehouseRESTDiscoveryDriverPlugin.java:
##########
@@ -0,0 +1,420 @@
+/*
+ * 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.restcatalog;
+
+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.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+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.gravitino.spark.connector.plugin.GravitinoSparkPlugin;
+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;
+
+  GravitinoLakehouseRESTDiscoveryDriverPlugin() {}
+
+  @Override
+  public Map<String, String> init(SparkContext sc, PluginContext pluginContext) {
+    initialize(sc.conf());
+    return Collections.emptyMap();
+  }
+
+  @VisibleForTesting
+  void initialize(SparkConf sparkConf) {
+    initialize(sparkConf, BuiltinRESTCatalogProviders.providerClassNames());
+  }
+
+  @VisibleForTesting
+  void initialize(SparkConf sparkConf, Map<String, String> providerClassNames) {
+    validatePluginOrder(sparkConf);
+    SparkConf userConf = sparkConf.clone();
+    Map<String, String> activeFormats = findActiveFormats(userConf);
+    if (activeFormats.isEmpty()) {
+      return;
+    }
+
+    ClassLoader classLoader = contextClassLoader();
+    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 =
+              loadProvider(format, providerClassNames, classLoader);
+          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);

Review Comment:
   Good point. Sorting is not required for registration, so I will remove it and preserve the provider response order.



##########
spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/plugin/restcatalog/lance/LanceRESTCatalogProvider.java:
##########
@@ -0,0 +1,121 @@
+/*
+ * 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.restcatalog.lance;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableMap;
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.spark.connector.plugin.restcatalog.LakehouseRESTCatalogProvider;
+import org.lance.namespace.client.apache.ApiClient;
+import org.lance.namespace.client.apache.ApiException;
+import org.lance.namespace.client.apache.api.NamespaceApi;
+import org.lance.namespace.model.ListNamespacesResponse;
+
+/** Discovers and configures Lance REST catalogs. */
+public class LanceRESTCatalogProvider implements LakehouseRESTCatalogProvider {
+
+  static final String FORMAT = "lance";
+  static final String CATALOG_CLASS = "org.lance.spark.LanceNamespaceSparkCatalog";
+  static final String SPARK_EXTENSIONS = "org.lance.spark.extensions.LanceSparkSessionExtensions";
+
+  private static final String ROOT_NAMESPACE_ID = "$";
+  private static final String NAMESPACE_DELIMITER = "$";
+
+  @Override
+  public String format() {
+    return FORMAT;
+  }
+
+  @Override
+  public List<String> listCatalogs(String uri, Map<String, String> catalogProperties) {
+    List<String> catalogs = new ArrayList<>();
+    Set<String> seenPageTokens = new HashSet<>();
+    String pageToken = null;
+
+    ApiClient apiClient = new ApiClient().setBasePath(normalizeUri(uri));
+    try (Closeable httpClient = getHttpClient(apiClient)) {
+      NamespaceApi namespaceApi = new NamespaceApi(apiClient);
+      do {
+        ListNamespacesResponse response =
+            namespaceApi.listNamespaces(ROOT_NAMESPACE_ID, NAMESPACE_DELIMITER, pageToken, null);
+        Preconditions.checkState(response != null, "Lance REST server returned an empty response");
+        Preconditions.checkState(
+            response.getNamespaces() != null,
+            "Lance REST server returned a response without namespaces");
+        catalogs.addAll(response.getNamespaces());
+
+        pageToken = StringUtils.trimToNull(response.getPageToken());
+        Preconditions.checkState(
+            pageToken == null || seenPageTokens.add(pageToken),
+            "Lance REST server returned repeated page token: %s",
+            pageToken);
+      } while (pageToken != null);
+    } catch (ApiException | IOException e) {
+      throw new IllegalStateException("Failed to list catalogs from Lance REST server " + uri, e);
+    }
+
+    return catalogs;
+  }
+
+  @Override
+  public String catalogClassName() {
+    return CATALOG_CLASS;
+  }
+
+  @Override
+  public Map<String, String> generatedCatalogProperties(String uri, String advertisedCatalogName) {

Review Comment:
   It means the catalog name returned by the REST discovery endpoint, before the registration policy filters or renames it. I will rename it to `discoveredCatalogName` to distinguish it from the Spark registered name.



-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12525] feat(spark-connector): Add lakehouse REST catalog discovery for lance [gravitino]

Posted by "FANNG1 (via GitHub)" <gi...@apache.org>.
FANNG1 commented on code in PR #12541:
URL: https://github.com/apache/gravitino/pull/12541#discussion_r3979945291


##########
spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/plugin/restcatalog/BuiltinRESTCatalogProviders.java:
##########
@@ -0,0 +1,38 @@
+/*
+ * 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.restcatalog;
+
+import java.util.Collections;
+import java.util.Map;
+
+final class BuiltinRESTCatalogProviders {
+
+  private static final String LANCE_FORMAT = "lance";

Review Comment:
   https://github.com/apache/gravitino/pull/12710 proxys the all the request to Iceberg REST server which do similar logic to Iceberg catalog providers, I'm not sure wether we should support Iceberg latter, do you have any suggestion?



-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12525] feat(spark-connector): Add lakehouse REST catalog discovery for lance [gravitino]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #12541:
URL: https://github.com/apache/gravitino/pull/12541#issuecomment-5426684828

   <!-- coverage-report -->
   ### Code Coverage Report
   |Overall Project|68.29% **`-0.01%`**|:green_circle:|
   |:-|:-|:-:|
   |Files changed|67.68%|:green_circle:|
   <br>
   
   |Module|Coverage||
   |:-|:-|:-:|
   |aliyun|19.74%|:red_circle:|
   |api|52.87%|:green_circle:|
   |authorization-common|85.96%|:green_circle:|
   |authorization-ranger|4.38%|:red_circle:|
   |aws|53.54%|:green_circle:|
   |azure|32.1%|:red_circle:|
   |catalog-common|9.9%|:red_circle:|
   |catalog-fileset|80.17%|:green_circle:|
   |catalog-glue|69.24%|:green_circle:|
   |catalog-hive|82.96%|:green_circle:|
   |catalog-jdbc-common|45.69%|:green_circle:|
   |catalog-jdbc-doris|82.44%|:green_circle:|
   |catalog-jdbc-mysql|79.33%|:green_circle:|
   |catalog-jdbc-postgresql|83.39%|:green_circle:|
   |catalog-jdbc-starrocks|79.16%|:green_circle:|
   |catalog-kafka|76.99%|:green_circle:|
   |catalog-lakehouse-generic|60.55%|:green_circle:|
   |catalog-lakehouse-hudi|79.1%|:green_circle:|
   |catalog-lakehouse-iceberg|85.86%|:green_circle:|
   |catalog-lakehouse-paimon|84.26%|:green_circle:|
   |catalog-model|77.99%|:green_circle:|
   |cli|44.48%|:green_circle:|
   |client-java|78.16%|:green_circle:|
   |common|52.29%|:green_circle:|
   |core|83.56% **`-0.39%`**|:green_circle:|
   |filesystem-hadoop3|76.45%|:green_circle:|
   |flink|0.0%|:red_circle:|
   |flink-common|50.29%|:green_circle:|
   |flink-runtime|0.0%|:red_circle:|
   |gcp|32.2%|:red_circle:|
   |hadoop-auth|68.0%|:green_circle:|
   |hadoop-common|17.84%|:red_circle:|
   |hive-metastore-common|53.4%|:green_circle:|
   |iceberg-aliyun-bundle|0.0%|:red_circle:|
   |iceberg-common|64.75%|:green_circle:|
   |iceberg-rest-server|75.31%|:green_circle:|
   |idp-basic|85.98%|:green_circle:|
   |integration-test-common|0.0%|:red_circle:|
   |jobs|62.92%|:green_circle:|
   |lance-common|32.81% **`-7.77%`**|:red_circle:|
   |lance-rest-server|64.78%|:green_circle:|
   |lineage|53.02%|:green_circle:|
   |optimizer|83.17%|:green_circle:|
   |optimizer-api|21.95%|:red_circle:|
   |server|87.54%|:green_circle:|
   |server-common|79.59% **`-1.27%`**|:green_circle:|
   |spark|28.57%|:red_circle:|
   |spark-common|53.51% **`+4.0%`**|:green_circle:|
   |tencent|69.84%|:green_circle:|
   |trino-connector|47.41%|:green_circle:|
   
   <details>
   <summary>Files</summary>
   
   |Module|File|Coverage||
   |:-|:-|:-|:-:|
   |core|[PropertiesMetadataHelpers.java](https://github.com/FANNG1/gravitino/blob/f7cd55f2572794fffeb7d00289ca569cab1a54b4/core/src/main/java/org/apache/gravitino/catalog/PropertiesMetadataHelpers.java)|100.0%|:green_circle:|
   ||[EntityCombinedTable.java](https://github.com/FANNG1/gravitino/blob/f7cd55f2572794fffeb7d00289ca569cab1a54b4/core/src/main/java/org/apache/gravitino/catalog/EntityCombinedTable.java)|97.22%|:green_circle:|
   ||[EntityCombinedFileset.java](https://github.com/FANNG1/gravitino/blob/f7cd55f2572794fffeb7d00289ca569cab1a54b4/core/src/main/java/org/apache/gravitino/catalog/EntityCombinedFileset.java)|96.43%|:green_circle:|
   ||[OperationDispatcher.java](https://github.com/FANNG1/gravitino/blob/f7cd55f2572794fffeb7d00289ca569cab1a54b4/core/src/main/java/org/apache/gravitino/catalog/OperationDispatcher.java)|93.86%|:green_circle:|
   ||[EntityCombinedSchema.java](https://github.com/FANNG1/gravitino/blob/f7cd55f2572794fffeb7d00289ca569cab1a54b4/core/src/main/java/org/apache/gravitino/catalog/EntityCombinedSchema.java)|93.33%|:green_circle:|
   ||[EntityCombinedTopic.java](https://github.com/FANNG1/gravitino/blob/f7cd55f2572794fffeb7d00289ca569cab1a54b4/core/src/main/java/org/apache/gravitino/catalog/EntityCombinedTopic.java)|93.33%|:green_circle:|
   ||[EntityCombinedView.java](https://github.com/FANNG1/gravitino/blob/f7cd55f2572794fffeb7d00289ca569cab1a54b4/core/src/main/java/org/apache/gravitino/catalog/EntityCombinedView.java)|91.89%|:green_circle:|
   ||[EntityCombinedModelVersion.java](https://github.com/FANNG1/gravitino/blob/f7cd55f2572794fffeb7d00289ca569cab1a54b4/core/src/main/java/org/apache/gravitino/catalog/EntityCombinedModelVersion.java)|89.29%|:green_circle:|
   ||[EntityCombinedModel.java](https://github.com/FANNG1/gravitino/blob/f7cd55f2572794fffeb7d00289ca569cab1a54b4/core/src/main/java/org/apache/gravitino/catalog/EntityCombinedModel.java)|82.76%|:green_circle:|
   ||[MetalakeManager.java](https://github.com/FANNG1/gravitino/blob/f7cd55f2572794fffeb7d00289ca569cab1a54b4/core/src/main/java/org/apache/gravitino/metalake/MetalakeManager.java)|76.19%|:green_circle:|
   ||[CatalogManager.java](https://github.com/FANNG1/gravitino/blob/f7cd55f2572794fffeb7d00289ca569cab1a54b4/core/src/main/java/org/apache/gravitino/catalog/CatalogManager.java)|71.25%|:green_circle:|
   ||[BaseCatalog.java](https://github.com/FANNG1/gravitino/blob/f7cd55f2572794fffeb7d00289ca569cab1a54b4/core/src/main/java/org/apache/gravitino/connector/BaseCatalog.java)|63.64%|:green_circle:|
   |lance-common|[GravitinoLanceNameSpaceOperations.java](https://github.com/FANNG1/gravitino/blob/f7cd55f2572794fffeb7d00289ca569cab1a54b4/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/GravitinoLanceNameSpaceOperations.java)|1.4%|:red_circle:|
   |server-common|[MetadataAuthzHelper.java](https://github.com/FANNG1/gravitino/blob/f7cd55f2572794fffeb7d00289ca569cab1a54b4/server-common/src/main/java/org/apache/gravitino/server/authorization/MetadataAuthzHelper.java)|59.41%|:red_circle:|
   |spark-common|[CatalogRegistrationPolicy.java](https://github.com/FANNG1/gravitino/blob/f7cd55f2572794fffeb7d00289ca569cab1a54b4/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/plugin/CatalogRegistrationPolicy.java)|100.0%|:green_circle:|
   ||[GravitinoLakehouseRESTDiscoveryDriverPlugin.java](https://github.com/FANNG1/gravitino/blob/f7cd55f2572794fffeb7d00289ca569cab1a54b4/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/plugin/GravitinoLakehouseRESTDiscoveryDriverPlugin.java)|93.57%|:green_circle:|
   ||[LanceRESTCatalogProvider.java](https://github.com/FANNG1/gravitino/blob/f7cd55f2572794fffeb7d00289ca569cab1a54b4/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/plugin/LanceRESTCatalogProvider.java)|88.24%|:green_circle:|
   ||[ConnectorUtil.java](https://github.com/FANNG1/gravitino/blob/f7cd55f2572794fffeb7d00289ca569cab1a54b4/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/utils/ConnectorUtil.java)|68.42%|:green_circle:|
   ||[GravitinoDriverPlugin.java](https://github.com/FANNG1/gravitino/blob/f7cd55f2572794fffeb7d00289ca569cab1a54b4/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/plugin/GravitinoDriverPlugin.java)|48.77%|:red_circle:|
   ||[GravitinoLakehouseRESTDiscoveryPlugin.java](https://github.com/FANNG1/gravitino/blob/f7cd55f2572794fffeb7d00289ca569cab1a54b4/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/plugin/GravitinoLakehouseRESTDiscoveryPlugin.java)|0.0%|:red_circle:|
   ||[LakehouseRESTCatalogProvider.java](https://github.com/FANNG1/gravitino/blob/f7cd55f2572794fffeb7d00289ca569cab1a54b4/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/plugin/LakehouseRESTCatalogProvider.java)|0.0%|:red_circle:|
   
   </details>


-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12525] feat(spark-connector): Add lakehouse REST catalog discovery for lance [gravitino]

Posted by "FANNG1 (via GitHub)" <gi...@apache.org>.
FANNG1 commented on code in PR #12541:
URL: https://github.com/apache/gravitino/pull/12541#discussion_r3869187905


##########
spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/plugin/restcatalog/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:
   We do not enable JUnit 5 parallel execution in this project. Also, replacing this with an  would make increments atomic but would not isolate the reset/increment sequence across concurrently executing test methods, so it would not solve the described interference. The counter is intentionally static because the policy instance is created reflectively, and it is reset in .



-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12525] feat(spark-connector): Add lakehouse REST catalog discovery for lance [gravitino]

Posted by "FANNG1 (via GitHub)" <gi...@apache.org>.
FANNG1 commented on PR #12541:
URL: https://github.com/apache/gravitino/pull/12541#issuecomment-5694601156

   @diqiu50 Thanks for the detailed review. I went through each point and made the following updates or clarifications.
   
   1. `GravitinoDriverPlugin` already preserved user-defined `spark.sql.catalog.<name>` entries before this PR: `registerCatalog()` rejected a collision, and its caller retained the user configuration after logging the failure. The new early return changes the diagnostic level, not the precedence behavior. I do not think a release note is needed. The same path also handles discovery-generated entries, for which WARN would be noisy; distinguishing those sources for logging can be improved separately.
   
   2. Fixed. A catalog name that the default policy passes through but Spark cannot reference unquoted now logs a WARN and is skipped, so it does not abort Spark startup. A custom policy that returns such a name still fails fast. The parser call now goes through `ParserInterface`, allowing the code to catch only `ParseException`.
   
   3. This is a valid test-coverage observation. The current IT proves the supported bundle matrix works, but its provider is defined by the application classloader, so it does not by itself prove the Namespace client is loaded from the bundle. The supported client APIs are compatible across the tested bundle versions, and the provider avoids a static Apache HttpClient method descriptor by using reflection, which is important for the relocated runtime JAR. I consider a stricter published-artifact and classpath-isolation test a follow-up enhancement rather than a blocker for this PR. I will also make the supported bundle-version boundary explicit in the documentation.
   
   4-6. Fixed in `eefa646da`: added discovery and skip diagnostics, improved Lance REST error messages including HTTP status and response body, and made policy/provider loading failures include the relevant configuration and REST endpoint context.
   
   7. Fixed in `eefa646da`: added coverage for runtime validation, policy loading and collisions, listing failures, misspelled configuration keys, and Lance REST error responses. The HTTP-server assertions now run on the test thread.
   
   8. Agreed that the design document was stale. I updated it to state that Lance is the first supported provider. The Lance root list is authenticated but intentionally not per-catalog authorization-filtered: authenticated callers that can access the endpoint can discover its catalog names. This is the discovery contract for this PR, not a prerequisite for support; existing table and namespace authorization remains unchanged. Per-principal catalog-name filtering can be added later if that visibility restriction becomes required.
   
   9. Fixed in `eefa646da`: the user documentation now states that discovery is a startup dependency with no fallback, so an unreachable REST server fails Spark session initialization.
   
   Please let me know if you think the root-list visibility contract should instead be treated as a product requirement for this PR.


-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12525] feat(spark-connector): Add lakehouse REST catalog discovery for lance [gravitino]

Posted by "FANNG1 (via GitHub)" <gi...@apache.org>.
FANNG1 commented on code in PR #12541:
URL: https://github.com/apache/gravitino/pull/12541#discussion_r3869184927


##########
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:
   The generated Lance client always sends the non-null NAMESPACE_DELIMITER argument on every listNamespaces request, so the first request still has a query string; it only omits page_token. Keeping this assertion strict also detects a regression in the generated client request shape. The focused pagination test and Spark IT pass with this behavior.



##########
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:
   removeDuplicateSparkExtensions already filters blank values and trims every element in ConnectorUtil.addSparkExtensions before deduplication and joining. Therefore the values produced by split(COMMA) cannot retain leading or trailing whitespace in the resulting Spark configuration, so no additional trimming is needed here.



##########
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:
   Fixed. The ServiceLoader mechanism has been removed. BuiltinRESTCatalogProviders now stores only format-to-provider-FQCN strings, and the driver reflectively loads only the provider for an active configured format after detecting its REST.uri. The common package has no static reference to the Lance provider or Lance SDK classes.



##########
spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/plugin/restcatalog/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:
   We do not enable JUnit 5 parallel execution in this project. Also, replacing this with an AtomicInteger would make increments atomic but would not isolate the reset and increment sequence across concurrently executing test methods, so it would not solve the described interference. The counter is intentionally static because the policy instance is created reflectively, and it is reset in BeforeEach.



##########
spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/plugin/restcatalog/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:
   We do not enable JUnit 5 parallel execution in this project. Also, replacing this with an AtomicInteger would make increments atomic but would not isolate the reset and increment sequence across concurrently executing test methods, so it would not solve the described interference. The counter is intentionally static because the policy instance is created reflectively, and it is reset in BeforeEach.



##########
spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/plugin/restcatalog/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:
   We do not enable JUnit 5 parallel execution in this project. Also, replacing this with an AtomicInteger would make increments atomic but would not isolate the reset and increment sequence across concurrently executing test methods, so it would not solve the described interference. The counter is intentionally static because the policy instance is created reflectively, and it is reset in BeforeEach.



-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12525] feat(spark-connector): Add lakehouse REST catalog discovery for lance [gravitino]

Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on PR #12541:
URL: https://github.com/apache/gravitino/pull/12541#issuecomment-5435157003

   > The CI failure seems not related.
   
   The problem has been fixed, and please just rebase this PR to the main branch.


-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12525] feat(spark-connector): Add lakehouse REST catalog discovery for lance [gravitino]

Posted by "FANNG1 (via GitHub)" <gi...@apache.org>.
FANNG1 merged PR #12541:
URL: https://github.com/apache/gravitino/pull/12541


-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12525] feat(spark-connector): Add lakehouse REST catalog discovery for lance [gravitino]

Posted by "FANNG1 (via GitHub)" <gi...@apache.org>.
FANNG1 commented on code in PR #12541:
URL: https://github.com/apache/gravitino/pull/12541#discussion_r3977646979


##########
spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/plugin/restcatalog/GravitinoLakehouseRESTDiscoveryDriverPlugin.java:
##########
@@ -0,0 +1,420 @@
+/*
+ * 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.restcatalog;
+
+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.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+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.gravitino.spark.connector.plugin.GravitinoSparkPlugin;
+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;
+
+  GravitinoLakehouseRESTDiscoveryDriverPlugin() {}
+
+  @Override
+  public Map<String, String> init(SparkContext sc, PluginContext pluginContext) {
+    initialize(sc.conf());
+    return Collections.emptyMap();
+  }
+
+  @VisibleForTesting
+  void initialize(SparkConf sparkConf) {
+    initialize(sparkConf, BuiltinRESTCatalogProviders.providerClassNames());
+  }
+
+  @VisibleForTesting
+  void initialize(SparkConf sparkConf, Map<String, String> providerClassNames) {
+    validatePluginOrder(sparkConf);
+    SparkConf userConf = sparkConf.clone();
+    Map<String, String> activeFormats = findActiveFormats(userConf);
+    if (activeFormats.isEmpty()) {
+      return;
+    }
+
+    ClassLoader classLoader = contextClassLoader();
+    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 =
+              loadProvider(format, providerClassNames, classLoader);
+          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 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());

Review Comment:
   Agreed. I will document on `CatalogRegistrationPolicy` that a configured implementation must provide a public no-argument constructor.



##########
spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/plugin/restcatalog/GravitinoLakehouseRESTDiscoveryDriverPlugin.java:
##########
@@ -0,0 +1,420 @@
+/*
+ * 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.restcatalog;
+
+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.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+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.gravitino.spark.connector.plugin.GravitinoSparkPlugin;
+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;
+
+  GravitinoLakehouseRESTDiscoveryDriverPlugin() {}
+
+  @Override
+  public Map<String, String> init(SparkContext sc, PluginContext pluginContext) {
+    initialize(sc.conf());
+    return Collections.emptyMap();
+  }
+
+  @VisibleForTesting
+  void initialize(SparkConf sparkConf) {
+    initialize(sparkConf, BuiltinRESTCatalogProviders.providerClassNames());
+  }
+
+  @VisibleForTesting
+  void initialize(SparkConf sparkConf, Map<String, String> providerClassNames) {
+    validatePluginOrder(sparkConf);
+    SparkConf userConf = sparkConf.clone();
+    Map<String, String> activeFormats = findActiveFormats(userConf);
+    if (activeFormats.isEmpty()) {
+      return;
+    }
+
+    ClassLoader classLoader = contextClassLoader();
+    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 =
+              loadProvider(format, providerClassNames, classLoader);
+          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 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 LakehouseRESTCatalogProvider loadProvider(
+      String format, Map<String, String> providerClassNames, ClassLoader classLoader) {
+    String providerClassName = providerClassNames.get(format);
+    Preconditions.checkArgument(
+        providerClassName != null,
+        "No lakehouse REST catalog provider found for configured format: %s",
+        format);
+    try {
+      Class<?> providerClass = Class.forName(providerClassName, true, classLoader);
+      Preconditions.checkArgument(
+          LakehouseRESTCatalogProvider.class.isAssignableFrom(providerClass),
+          "%s does not implement %s",
+          providerClassName,
+          LakehouseRESTCatalogProvider.class.getName());
+      return providerClass
+          .asSubclass(LakehouseRESTCatalogProvider.class)
+          .getConstructor()
+          .newInstance();
+    } catch (ReflectiveOperationException | LinkageError e) {
+      throw new IllegalArgumentException(
+          String.format(
+              "Failed to instantiate lakehouse REST catalog provider %s for format %s",
+              providerClassName, format),
+          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(

Review Comment:
   I think `validateRuntimeClass` better describes the intent here. The helper validates that a required runtime class is non-blank and loadable without initialization, then reports a clear configuration error otherwise. `loadRuntimeClass` would imply that the loaded `Class` is returned or used afterward, so I will keep the current name.



-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12525] feat(spark-connector): Add lakehouse REST catalog discovery for lance [gravitino]

Posted by "FANNG1 (via GitHub)" <gi...@apache.org>.
FANNG1 commented on code in PR #12541:
URL: https://github.com/apache/gravitino/pull/12541#discussion_r3977644941


##########
spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/plugin/restcatalog/BuiltinRESTCatalogProviders.java:
##########
@@ -0,0 +1,38 @@
+/*
+ * 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.restcatalog;
+
+import java.util.Collections;
+import java.util.Map;
+
+final class BuiltinRESTCatalogProviders {
+
+  private static final String LANCE_FORMAT = "lance";

Review Comment:
   Not in this PR. This PR wires only the Lance provider; the built-in registry is structured so another format-specific provider, such as Iceberg, can be added later with its own runtime and configuration contract.



-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12525] feat(spark-connector): Add lakehouse REST catalog discovery for lance [gravitino]

Posted by "FANNG1 (via GitHub)" <gi...@apache.org>.
FANNG1 commented on PR #12541:
URL: https://github.com/apache/gravitino/pull/12541#issuecomment-5620037304

   @yuqi1129 comments addressed, please take a look again


-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12525] feat(spark-connector): Add lakehouse REST catalog discovery for lance [gravitino]

Posted by "FANNG1 (via GitHub)" <gi...@apache.org>.
FANNG1 commented on code in PR #12541:
URL: https://github.com/apache/gravitino/pull/12541#discussion_r3869184927


##########
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:
   The generated Lance client always sends the non-null  argument on every  request, so the first request still has a query string; it only omits . Keeping this assertion strict also detects a regression in the generated client's request shape. The focused pagination test and Spark IT pass with this behavior.



##########
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:
    already filters blank values and trims every element in  before deduplication and joining. Therefore the values produced by  cannot retain leading/trailing whitespace in the resulting Spark configuration, so no additional trimming is needed here.



-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12525] feat(spark-connector): Add lakehouse REST catalog discovery for lance [gravitino]

Posted by "FANNG1 (via GitHub)" <gi...@apache.org>.
FANNG1 commented on code in PR #12541:
URL: https://github.com/apache/gravitino/pull/12541#discussion_r4010402994


##########
spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/plugin/restcatalog/BuiltinRESTCatalogProviders.java:
##########
@@ -0,0 +1,38 @@
+/*
+ * 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.restcatalog;

Review Comment:
   Google Java Style §5.2.1 specifies that consecutive words in a package name are simply concatenated with no separator — its own example is `com.example.deepspace` for "deep space", which likewise isn't a word. So a non-word is the expected result of the rule, not a violation of it. We already have the same pattern elsewhere in the repo: `org.apache.gravitino.trino.connector.system.storedprocedure` and `org.apache.gravitino.s3.credential.webidentity`.
   
   Splitting it into `rest.catalog` would also add an intermediate `plugin.rest` package containing nothing but the `catalog` subpackage, and `rest` is already used across the codebase for the REST resource layer (`iceberg.service.rest`, `server.web.rest`, `lineage.source.rest`), which could make `plugin.rest.catalog` read like a server-side REST implementation rather than a client-side catalog discovery plugin.
   
   I'd prefer to keep `restcatalog`, but happy to rename if you feel strongly — the package is new and unreleased, so it's a cheap change.
   



-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12525] feat(spark-connector): Add lakehouse REST catalog discovery for lance [gravitino]

Posted by "roryqi (via GitHub)" <gi...@apache.org>.
roryqi commented on code in PR #12541:
URL: https://github.com/apache/gravitino/pull/12541#discussion_r4006969180


##########
spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/plugin/restcatalog/BuiltinRESTCatalogProviders.java:
##########
@@ -0,0 +1,38 @@
+/*
+ * 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.restcatalog;

Review Comment:
   `restcatalog` isn't a word. Should we use `rest.catalog`?



-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org