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

diqiu50 pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/gravitino.git


The following commit(s) were added to refs/heads/main by this push:
     new 527742baac [#14196] fix(spark-connector): Preserve Paimon primary keys 
and bucket distributions (#14197)
527742baac is described below

commit 527742baac1b63367dbf7e3436b13f1bd328a32d
Author: kamisama0002 <[email protected]>
AuthorDate: Mon Nov 16 00:11:10 2026 -0700

    [#14196] fix(spark-connector): Preserve Paimon primary keys and bucket 
distributions (#14197)
    
    ### What changes were proposed in this pull request?
    
    Use the full create-table API in the Paimon Spark adapter: `primary-key`
    becomes one ordered composite index, and `bucket` / `bucket-key` become
    distribution metadata. Convert unsorted `CLUSTERED BY` through the same
    path, keeping bucket transforms separate from identity partitions.
    Return the key and bucket properties when Spark creates or loads a
    table.
    
    Resolve column references to the schema's actual names according to
    `spark.sql.caseSensitive`, including ordinary partitioned tables. Reject
    ambiguous references and check distribution expression types before
    reconstructing bucket properties. Keep conversion and
    conflicting-declaration checks in the adapter, and leave Paimon schema
    semantics to the server. Bind the optional Iceberg adapter by name so
    Paimon-only Spark 3.5 startup does not link its runtime interfaces.
    
    ### Why are the changes needed?
    
    `TBLPROPERTIES ('primary-key'='id', 'bucket'='-1')` currently reaches
    Gravitino as reserved properties without an index. Creation fails before
    reaching Paimon. `CLUSTERED BY` also fails because its bucket transform
    is treated as a partition.
    
    Fixes #14196. Fixes #10367. Related to #10721, which added Flink bucket
    conversion and server-side support.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. Paimon primary-key and bucket options, including dynamic buckets
    without an explicit bucket key, work through the Gravitino catalog.
    `CLUSTERED BY ... INTO ... BUCKETS` is supported; `SORTED BY` remains
    unsupported. Column names follow Spark's case-sensitivity setting, and
    invalid distribution expressions produce an explicit validation error.
    Server-side reserved-property and Paimon schema validation remain
    enabled.
    
    ### How was this patch tested?
    
    - Windows / JDK 17: **307 Spark 3.5 module tests passed**, with 0
    failures, errors or skipped tests, including **60 Paimon cases**.
    Command: `./gradlew :spark-connector:spark-3.5:test -PskipITs
    --configure-on-demand --offline --max-workers=4 --no-parallel`. Scoped
    Spotless checks and `git diff --check` passed.
    - The review regressions reproduced 17 failures before this update. An
    additional regression reproduced the ordinary partition fallback
    retaining an unresolved name. Tests now cover case-sensitive and
    insensitive resolution, ambiguous names, literal-dot columns,
    property/transform conflicts, and invalid distribution expression types.
    Native Paimon tests verify metadata round trips and that invalid
    bucket-key semantics are still rejected on table creation.
    - GitHub [Fork CI run
    
#40671449996](https://github.com/kamisama0002/gravitino/actions/runs/40671449996)
    passed for `4c684f41` with the updated workflow, including the required
    `tms` caller. The full build, Spark connector build, both Spark
    integration modes, frontend integration, core unit/MySQL/PostgreSQL/H2
    tests, and coverage all passed.
    - Earlier CentOS / JDK 17 testing passed the isolated filesystem SQL
    tests for dynamic-key replay and `CLUSTERED BY` reads/writes. Those
    integration suites and the full-repository checks were not rerun locally
    for this follow-up; the current CI result is reported in Checks.
    
    Latest locally tested commit:
    `4c684f4172bc9d1499ac5e8c192ff680c4130d70`.
    
    ---------
    
    Signed-off-by: 付继发 <[email protected]>
    Co-authored-by: Qi Yu <[email protected]>
---
 docs/spark-connector/spark-catalog-paimon.md       |  41 +-
 .../spark/connector/catalog/BaseCatalog.java       |  21 +-
 .../connector/paimon/GravitinoPaimonCatalog.java   | 205 ++++++
 .../spark/connector/paimon/SparkPaimonTable.java   |  48 +-
 .../test/paimon/SparkPaimonCatalogIT.java          |  75 ++
 .../paimon/TestGravitinoPaimonCatalog.java         | 820 +++++++++++++++++++++
 spark-connector/v3.5/spark/build.gradle.kts        |   9 +
 .../connector/plugin/GravitinoSparkPlugin.java     |  12 +-
 .../connector/plugin/TestGravitinoSparkPlugin.java |  55 ++
 9 files changed, 1272 insertions(+), 14 deletions(-)

diff --git a/docs/spark-connector/spark-catalog-paimon.md 
b/docs/spark-connector/spark-catalog-paimon.md
index 02dde3b683..d947b9730e 100644
--- a/docs/spark-connector/spark-catalog-paimon.md
+++ b/docs/spark-connector/spark-catalog-paimon.md
@@ -30,7 +30,9 @@ without the Paimon classes.
 - `LOAD NAMESPACE`
   - Returning user-specified configs is not supported; the spark-connector 
currently only supports FilesystemCatalog.
 - `CREATE TABLE`
-  - Doesn't support distribution and sort orders.
+  - Supports primary keys and bucket options through `TBLPROPERTIES`.
+  - Supports fixed buckets through `CLUSTERED BY ... INTO ... BUCKETS`.
+  - Doesn't support sort orders.
 - `DROP TABLE`
 - `ALTER TABLE`
 - `LIST TABLE`
@@ -87,6 +89,43 @@ SHOW PARTITIONS employee;
 ALTER TABLE employee DROP PARTITION (`name`='Alice');
 ```
 
+## Creating primary-key tables
+
+Specify Paimon primary keys and buckets in `TBLPROPERTIES`. For example, this 
creates a table with a composite primary key and dynamic buckets:
+
+```sql
+CREATE TABLE source_events (
+  source STRING NOT NULL,
+  event_id BIGINT NOT NULL,
+  payload STRING,
+  dt STRING
+)
+PARTITIONED BY (dt)
+TBLPROPERTIES (
+  'primary-key' = 'source,event_id',
+  'bucket' = '-1',
+  'merge-engine' = 'deduplicate'
+);
+```
+
+Primary-key column order is preserved, and primary-key columns become 
non-nullable, matching Paimon's behavior. Other column definitions are 
preserved. Use `bucket = '-1'` for dynamic buckets without an explicit 
`bucket-key`. For fixed buckets, specify a positive bucket count. An optional 
`bucket-key` specifies comma-separated top-level bucket columns.
+
+Column references are resolved to the schema's actual names according to 
`spark.sql.caseSensitive`. Ambiguous or missing names are rejected. The 
connector checks property parsing and conflicting bucket declarations; Paimon 
validates primary-key, bucket and partition combinations when the server 
creates the table.
+
+Use `PARTITIONED BY` for identity partitions. Fixed buckets can also be 
specified with `CLUSTERED BY`:
+
+```sql
+CREATE TABLE bucketed_events (
+  event_id BIGINT,
+  payload STRING,
+  dt STRING
+) USING paimon
+PARTITIONED BY (dt)
+CLUSTERED BY (event_id) INTO 4 BUCKETS;
+```
+
+If `CLUSTERED BY` and `TBLPROPERTIES` both specify a bucket count or bucket 
keys, their values must match. Bucket columns are represented as Paimon bucket 
metadata, separately from identity partitions. `SORTED BY` and non-identity 
partition transforms are not supported.
+
 ## Catalog Properties
 
 Gravitino spark connector will transform below property names which are 
defined in catalog properties to Spark Paimon connector configuration.
diff --git 
a/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/catalog/BaseCatalog.java
 
b/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/catalog/BaseCatalog.java
index 7c0120df57..2430b8d812 100644
--- 
a/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/catalog/BaseCatalog.java
+++ 
b/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/catalog/BaseCatalog.java
@@ -724,12 +724,6 @@ public abstract class BaseCatalog implements TableCatalog, 
SupportsNamespaces, F
         sparkTypeConverter);
   }
 
-  private void validateNamespace(String[] namespace) {
-    Preconditions.checkArgument(
-        namespace.length == 1,
-        "Doesn't support multi level namespaces: " + String.join(".", 
namespace));
-  }
-
   protected String getCatalogDefaultNamespace() {
     String[] catalogDefaultNamespace = sparkCatalog.defaultNamespace();
     Preconditions.checkArgument(
@@ -738,7 +732,14 @@ public abstract class BaseCatalog implements TableCatalog, 
SupportsNamespaces, F
     return catalogDefaultNamespace[0];
   }
 
-  private static org.apache.gravitino.rel.Column createGravitinoColumn(
+  /**
+   * Converts a Spark field to a Gravitino column for catalog-specific table 
creation.
+   *
+   * @param structField the Spark field
+   * @param typeConverter the converter for the table's format
+   * @return the converted column, including its comment and nullability
+   */
+  protected static org.apache.gravitino.rel.Column createGravitinoColumn(
       StructField structField, SparkTypeConverter typeConverter) {
     return org.apache.gravitino.rel.Column.of(
         structField.name(),
@@ -751,6 +752,12 @@ public abstract class BaseCatalog implements TableCatalog, 
SupportsNamespaces, F
         org.apache.gravitino.rel.Column.DEFAULT_VALUE_NOT_SET);
   }
 
+  private void validateNamespace(String[] namespace) {
+    Preconditions.checkArgument(
+        namespace.length == 1,
+        "Doesn't support multi level namespaces: " + String.join(".", 
namespace));
+  }
+
   private String getDatabase(NameIdentifier gravitinoIdentifier) {
     Preconditions.checkArgument(
         gravitinoIdentifier.namespace().length() == 1,
diff --git 
a/spark-connector/spark-common/src/main/spark35/org/apache/gravitino/spark/connector/paimon/GravitinoPaimonCatalog.java
 
b/spark-connector/spark-common/src/main/spark35/org/apache/gravitino/spark/connector/paimon/GravitinoPaimonCatalog.java
index 0f6e9dfd10..53f8860787 100644
--- 
a/spark-connector/spark-common/src/main/spark35/org/apache/gravitino/spark/connector/paimon/GravitinoPaimonCatalog.java
+++ 
b/spark-connector/spark-common/src/main/spark35/org/apache/gravitino/spark/connector/paimon/GravitinoPaimonCatalog.java
@@ -19,10 +19,29 @@
 
 package org.apache.gravitino.spark.connector.paimon;
 
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
 import java.util.Map;
+import java.util.Set;
+import javax.annotation.Nullable;
+import org.apache.commons.lang3.StringUtils;
 import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.catalog.lakehouse.paimon.PaimonConstants;
 import org.apache.gravitino.catalog.lakehouse.paimon.PaimonPropertiesUtils;
 import org.apache.gravitino.credential.CredentialPropertyUtils;
+import org.apache.gravitino.rel.Column;
+import org.apache.gravitino.rel.expressions.Expression;
+import org.apache.gravitino.rel.expressions.NamedReference;
+import org.apache.gravitino.rel.expressions.distributions.Distribution;
+import org.apache.gravitino.rel.expressions.distributions.Distributions;
+import org.apache.gravitino.rel.expressions.distributions.Strategy;
+import org.apache.gravitino.rel.expressions.sorts.SortOrder;
+import org.apache.gravitino.rel.indexes.Index;
+import org.apache.gravitino.rel.indexes.Indexes;
+import org.apache.gravitino.spark.connector.ConnectorConstants;
 import org.apache.gravitino.spark.connector.PropertiesConverter;
 import org.apache.gravitino.spark.connector.SparkTransformConverter;
 import org.apache.gravitino.spark.connector.SparkTypeConverter;
@@ -38,10 +57,111 @@ import org.apache.paimon.spark.procedure.ProcedureBuilder;
 import org.apache.spark.sql.connector.catalog.Identifier;
 import org.apache.spark.sql.connector.catalog.Table;
 import org.apache.spark.sql.connector.catalog.TableCatalog;
+import org.apache.spark.sql.connector.expressions.BucketTransform;
+import org.apache.spark.sql.connector.expressions.Expressions;
+import org.apache.spark.sql.connector.expressions.IdentityTransform;
+import org.apache.spark.sql.connector.expressions.SortedBucketTransform;
+import org.apache.spark.sql.connector.expressions.Transform;
+import org.apache.spark.sql.internal.SQLConf;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
 import org.apache.spark.sql.util.CaseInsensitiveStringMap;
 
 public class GravitinoPaimonCatalog extends BaseCatalog implements 
ProcedureCatalog {
 
+  private static final String PRIMARY_KEY_INDEX_NAME = 
"PAIMON_PRIMARY_KEY_INDEX";
+
+  /**
+   * Creates Paimon table metadata with structured primary keys and bucket 
distribution.
+   *
+   * @param ident the Spark table identifier
+   * @param schema the Spark table schema
+   * @param transforms the requested partition and bucket transforms
+   * @param properties the requested Paimon table properties
+   * @return the created Gravitino table
+   */
+  @Override
+  protected org.apache.gravitino.rel.Table createGravitinoTable(
+      Identifier ident, StructType schema, Transform[] transforms, Map<String, 
String> properties) {
+    List<Transform> partitions = new ArrayList<>();
+    BucketTransform bucketTransform = null;
+    if (transforms != null) {
+      for (Transform transform : transforms) {
+        if (transform instanceof SortedBucketTransform) {
+          throw new UnsupportedOperationException("Paimon does not support 
SORTED BY.");
+        }
+        if (transform instanceof BucketTransform) {
+          Preconditions.checkArgument(
+              bucketTransform == null, "Paimon only supports one bucket 
transform.");
+          bucketTransform = (BucketTransform) transform;
+          continue;
+        }
+        if (!(transform instanceof IdentityTransform)) {
+          throw new UnsupportedOperationException(
+              "Paimon only supports identity partition transforms.");
+        }
+        String[] fields = ((IdentityTransform) 
transform).reference().fieldNames();
+        Preconditions.checkArgument(
+            fields.length == 1, "Paimon partitions must reference top-level 
columns.");
+        String column = resolveColumns("partition", fields, schema)[0];
+        partitions.add(Expressions.identity("`" + column.replace("`", "``") + 
"`"));
+      }
+    }
+
+    if (!properties.containsKey(PaimonConstants.PRIMARY_KEY)
+        && !properties.containsKey(PaimonConstants.BUCKET_NUM)
+        && !properties.containsKey(PaimonConstants.BUCKET_KEY)
+        && bucketTransform == null) {
+      return super.createGravitinoTable(
+          ident, schema, partitions.toArray(new Transform[0]), properties);
+    }
+
+    String[] primaryKeys =
+        properties.containsKey(PaimonConstants.PRIMARY_KEY)
+            ? parseColumns(PaimonConstants.PRIMARY_KEY, properties, schema)
+            : new String[0];
+    Index[] indexes =
+        primaryKeys.length == 0
+            ? Indexes.EMPTY_INDEXES
+            : new Index[] {
+              Indexes.primary(
+                  PRIMARY_KEY_INDEX_NAME,
+                  Arrays.stream(primaryKeys)
+                      .map(key -> new String[] {key})
+                      .toArray(String[][]::new))
+            };
+    Set<String> primaryKeyColumns = new HashSet<>(Arrays.asList(primaryKeys));
+    Distribution distribution = toDistribution(properties, schema, 
bucketTransform);
+    Map<String, String> tableProperties =
+        propertiesConverter.toGravitinoTableProperties(properties);
+    SparkTypeConverter typeConverter = getSparkTypeConverter(tableProperties);
+    Column[] columns =
+        Arrays.stream(schema.fields())
+            .map(
+                field ->
+                    primaryKeyColumns.contains(field.name())
+                        ? new StructField(field.name(), field.dataType(), 
false, field.metadata())
+                        : field)
+            .map(field -> createGravitinoColumn(field, typeConverter))
+            .toArray(Column[]::new);
+    tableProperties.remove(PaimonConstants.PRIMARY_KEY);
+    tableProperties.remove(PaimonConstants.BUCKET_NUM);
+    tableProperties.remove(PaimonConstants.BUCKET_KEY);
+    String comment = tableProperties.remove(ConnectorConstants.COMMENT);
+
+    return gravitinoCatalog()
+        .asTableCatalog()
+        .createTable(
+            NameIdentifier.of(getDatabase(ident), ident.name()),
+            columns,
+            comment,
+            tableProperties,
+            
sparkTransformConverter.toGravitinoPartitionings(partitions.toArray(new 
Transform[0])),
+            distribution,
+            new SortOrder[0],
+            indexes);
+  }
+
   @Override
   protected TableCatalog createAndInitSparkCatalog(
       String name, CaseInsensitiveStringMap options, Map<String, String> 
properties) {
@@ -107,4 +227,89 @@ public class GravitinoPaimonCatalog extends BaseCatalog 
implements ProcedureCata
     }
     throw new NoSuchProcedureException(identifier);
   }
+
+  private static String[] parseColumns(
+      String option, Map<String, String> properties, StructType schema) {
+    String value = properties.get(option);
+    Preconditions.checkArgument(StringUtils.isNotBlank(value), "%s must not be 
empty.", option);
+    String[] columns = Arrays.stream(value.split(",", 
-1)).map(String::trim).toArray(String[]::new);
+    return resolveColumns(option, columns, schema);
+  }
+
+  private static String[] resolveColumns(String option, String[] columns, 
StructType schema) {
+    boolean caseSensitive = SQLConf.get().caseSensitiveAnalysis();
+    return Arrays.stream(columns)
+        .map(
+            column -> {
+              Preconditions.checkArgument(
+                  !column.isEmpty(), "%s must contain non-empty, top-level 
column names.", option);
+              String[] matches =
+                  Arrays.stream(schema.fieldNames())
+                      .filter(
+                          name ->
+                              caseSensitive ? name.equals(column) : 
name.equalsIgnoreCase(column))
+                      .toArray(String[]::new);
+              Preconditions.checkArgument(
+                  matches.length > 0, "Column %s in %s does not exist.", 
column, option);
+              Preconditions.checkArgument(
+                  matches.length == 1, "Column %s in %s is ambiguous.", 
column, option);
+              return matches[0];
+            })
+        .toArray(String[]::new);
+  }
+
+  private static Distribution toDistribution(
+      Map<String, String> properties,
+      StructType schema,
+      @Nullable BucketTransform bucketTransform) {
+    boolean hasBucket = properties.containsKey(PaimonConstants.BUCKET_NUM);
+    boolean hasBucketKey = properties.containsKey(PaimonConstants.BUCKET_KEY);
+    if (!hasBucket && !hasBucketKey && bucketTransform == null) {
+      return Distributions.NONE;
+    }
+
+    String[] bucketKeys =
+        hasBucketKey ? parseColumns(PaimonConstants.BUCKET_KEY, properties, 
schema) : new String[0];
+    int buckets = Distributions.AUTO;
+    if (hasBucket) {
+      String value = properties.get(PaimonConstants.BUCKET_NUM);
+      Preconditions.checkArgument(StringUtils.isNotBlank(value), "bucket must 
not be empty.");
+      try {
+        buckets = Integer.parseInt(value.trim());
+      } catch (NumberFormatException e) {
+        throw new IllegalArgumentException("Paimon bucket must be a valid 
integer: " + value, e);
+      }
+    }
+    if (bucketTransform != null) {
+      int clusteredBuckets = (Integer) bucketTransform.numBuckets().value();
+      Preconditions.checkArgument(
+          clusteredBuckets > 0, "CLUSTERED BY requires a positive bucket 
number.");
+      Preconditions.checkArgument(
+          !hasBucket || buckets == clusteredBuckets,
+          "CLUSTERED BY conflicts with the Paimon bucket property.");
+      String[] clusteredColumns =
+          Arrays.stream(bucketTransform.references())
+              .map(
+                  reference -> {
+                    String[] fields = reference.fieldNames();
+                    Preconditions.checkArgument(
+                        fields.length == 1, "Paimon bucket keys must reference 
top-level columns.");
+                    return fields[0];
+                  })
+              .toArray(String[]::new);
+      Preconditions.checkArgument(
+          clusteredColumns.length > 0, "CLUSTERED BY requires bucket keys.");
+      String[] clusteredKeys = resolveColumns(PaimonConstants.BUCKET_KEY, 
clusteredColumns, schema);
+      Preconditions.checkArgument(
+          !hasBucketKey || Arrays.equals(bucketKeys, clusteredKeys),
+          "CLUSTERED BY conflicts with the Paimon bucket-key property.");
+      buckets = clusteredBuckets;
+      bucketKeys = clusteredKeys;
+    }
+    Expression[] expressions =
+        
Arrays.stream(bucketKeys).map(NamedReference::field).toArray(Expression[]::new);
+    return buckets == Distributions.AUTO
+        ? Distributions.auto(Strategy.HASH, expressions)
+        : Distributions.hash(buckets, expressions);
+  }
 }
diff --git 
a/spark-connector/spark-common/src/main/spark35/org/apache/gravitino/spark/connector/paimon/SparkPaimonTable.java
 
b/spark-connector/spark-common/src/main/spark35/org/apache/gravitino/spark/connector/paimon/SparkPaimonTable.java
index f1db29b71b..85d060a4b0 100644
--- 
a/spark-connector/spark-common/src/main/spark35/org/apache/gravitino/spark/connector/paimon/SparkPaimonTable.java
+++ 
b/spark-connector/spark-common/src/main/spark35/org/apache/gravitino/spark/connector/paimon/SparkPaimonTable.java
@@ -19,8 +19,16 @@
 
 package org.apache.gravitino.spark.connector.paimon;
 
+import com.google.common.base.Preconditions;
+import java.util.Arrays;
 import java.util.Map;
+import java.util.stream.Collectors;
+import org.apache.gravitino.catalog.lakehouse.paimon.PaimonConstants;
 import org.apache.gravitino.rel.Table;
+import org.apache.gravitino.rel.expressions.NamedReference;
+import org.apache.gravitino.rel.expressions.distributions.Distribution;
+import org.apache.gravitino.rel.expressions.distributions.Distributions;
+import org.apache.gravitino.rel.indexes.Index;
 import org.apache.gravitino.spark.connector.PropertiesConverter;
 import org.apache.gravitino.spark.connector.SparkTransformConverter;
 import org.apache.gravitino.spark.connector.SparkTypeConverter;
@@ -36,6 +44,7 @@ public class SparkPaimonTable extends SparkTable {
 
   private GravitinoTableInfoHelper gravitinoTableInfoHelper;
   private org.apache.spark.sql.connector.catalog.Table sparkTable;
+  private final Table gravitinoTable;
 
   public SparkPaimonTable(
       Identifier identifier,
@@ -45,6 +54,7 @@ public class SparkPaimonTable extends SparkTable {
       SparkTransformConverter sparkTransformConverter,
       SparkTypeConverter sparkTypeConverter) {
     super(sparkTable.getTable());
+    this.gravitinoTable = gravitinoTable;
     this.gravitinoTableInfoHelper =
         new GravitinoTableInfoHelper(
             true,
@@ -69,7 +79,43 @@ public class SparkPaimonTable extends SparkTable {
 
   @Override
   public Map<String, String> properties() {
-    return gravitinoTableInfoHelper.properties();
+    Map<String, String> properties = gravitinoTableInfoHelper.properties();
+    Index[] indexes = gravitinoTable.index();
+    if (indexes != null) {
+      Arrays.stream(indexes)
+          .filter(index -> index.type() == Index.IndexType.PRIMARY_KEY)
+          .findFirst()
+          .ifPresent(
+              index ->
+                  properties.put(
+                      PaimonConstants.PRIMARY_KEY,
+                      Arrays.stream(index.fieldNames())
+                          .map(fieldName -> String.join(".", fieldName))
+                          .collect(Collectors.joining(","))));
+    }
+    Distribution distribution = gravitinoTable.distribution();
+    if (!Distributions.isNone(distribution)) {
+      properties.put(PaimonConstants.BUCKET_NUM, 
String.valueOf(distribution.number()));
+      properties.remove(PaimonConstants.BUCKET_KEY);
+      if (distribution.expressions() != null && 
distribution.expressions().length > 0) {
+        properties.put(
+            PaimonConstants.BUCKET_KEY,
+            Arrays.stream(distribution.expressions())
+                .map(
+                    expression -> {
+                      Preconditions.checkArgument(
+                          expression instanceof NamedReference.FieldReference,
+                          "Paimon bucket keys must be plain column 
references.");
+                      String[] fields = ((NamedReference.FieldReference) 
expression).fieldName();
+                      Preconditions.checkArgument(
+                          fields.length == 1,
+                          "Paimon bucket keys must reference top-level 
columns.");
+                      return fields[0];
+                    })
+                .collect(Collectors.joining(",")));
+      }
+    }
+    return properties;
   }
 
   @Override
diff --git 
a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/integration/test/paimon/SparkPaimonCatalogIT.java
 
b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/integration/test/paimon/SparkPaimonCatalogIT.java
index 1996ccff70..ebb941d64e 100644
--- 
a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/integration/test/paimon/SparkPaimonCatalogIT.java
+++ 
b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/integration/test/paimon/SparkPaimonCatalogIT.java
@@ -28,6 +28,9 @@ import 
org.apache.gravitino.spark.connector.integration.test.util.SparkTableInfo
 import org.apache.gravitino.spark.connector.paimon.PaimonPropertiesConstants;
 import org.apache.hadoop.fs.Path;
 import org.apache.spark.sql.Row;
+import org.apache.spark.sql.connector.catalog.Identifier;
+import org.apache.spark.sql.connector.catalog.Table;
+import org.apache.spark.sql.connector.catalog.TableCatalog;
 import org.apache.spark.sql.types.DataTypes;
 import org.junit.jupiter.api.Assertions;
 import org.junit.jupiter.api.Test;
@@ -46,6 +49,7 @@ public abstract class SparkPaimonCatalogIT extends 
SparkCommonIT {
 
   @Override
   protected boolean supportsSparkSQLClusteredBy() {
+    // The common bucket suite also requires SORTED BY; use the 
Paimon-specific test below.
     return false;
   }
 
@@ -120,6 +124,77 @@ public abstract class SparkPaimonCatalogIT extends 
SparkCommonIT {
     checkDirExists(partitionPath);
   }
 
+  @Test
+  @SuppressWarnings("deprecation")
+  void testPrimaryKeyTableWithDynamicBuckets() throws Exception {
+    String tableName = "test_paimon_primary_key_dynamic_bucket";
+    dropTableIfExists(tableName);
+    sql(
+        String.format(
+            "CREATE TABLE %s (source STRING, event_id BIGINT, payload STRING, 
dt STRING) USING paimon "
+                + "PARTITIONED BY (dt) TBLPROPERTIES ("
+                + "'primary-key'='source,event_id', 'bucket'='-1', 
'merge-engine'='deduplicate')",
+            tableName));
+
+    TableCatalog catalog =
+        (TableCatalog) 
getSparkSession().sessionState().catalogManager().catalog(getCatalogName());
+    Table table = catalog.loadTable(Identifier.of(new String[] 
{getDefaultDatabase()}, tableName));
+    Assertions.assertEquals("source,event_id", 
table.properties().get("primary-key"));
+    Assertions.assertEquals("-1", table.properties().get("bucket"));
+    Assertions.assertFalse(table.properties().containsKey("bucket-key"));
+    Assertions.assertFalse(table.schema().apply("event_id").nullable());
+    Assertions.assertEquals(1, table.partitioning().length);
+
+    sql(String.format("INSERT INTO %s VALUES ('input', 1, 'first', 
'2026-10-23')", tableName));
+    sql(
+        String.format(
+            "INSERT INTO %s VALUES ('input', 1, 'replayed', '2026-10-23'), "
+                + "('input', 2, 'different offset', '2026-10-23')",
+            tableName));
+    List<Row> rows =
+        getSparkSession()
+            .sql(String.format("SELECT event_id, payload FROM %s ORDER BY 
event_id", tableName))
+            .collectAsList();
+    Assertions.assertEquals(2, rows.size());
+    Assertions.assertEquals(1L, rows.get(0).getLong(0));
+    Assertions.assertEquals("replayed", rows.get(0).getString(1));
+    Assertions.assertEquals(2L, rows.get(1).getLong(0));
+    Assertions.assertEquals("different offset", rows.get(1).getString(1));
+  }
+
+  @Test
+  void testClusteredByDistributionRoundTrip() throws Exception {
+    String tableName = "test_paimon_clustered_by";
+    dropTableIfExists(tableName);
+    sql(
+        String.format(
+            "CREATE TABLE %s (id INT, payload STRING, dt STRING) USING paimon "
+                + "PARTITIONED BY (dt) CLUSTERED BY (id) INTO 4 BUCKETS",
+            tableName));
+
+    TableCatalog catalog =
+        (TableCatalog) 
getSparkSession().sessionState().catalogManager().catalog(getCatalogName());
+    Table table = catalog.loadTable(Identifier.of(new String[] 
{getDefaultDatabase()}, tableName));
+    Assertions.assertEquals("4", table.properties().get("bucket"));
+    Assertions.assertEquals("id", table.properties().get("bucket-key"));
+    Assertions.assertEquals(1, table.partitioning().length);
+    Assertions.assertEquals("identity", table.partitioning()[0].name());
+
+    sql(
+        String.format(
+            "INSERT INTO %s VALUES (1, 'first', '2026-10-23'), (2, 'second', 
'2026-10-23')",
+            tableName));
+    List<Row> rows =
+        getSparkSession()
+            .sql(String.format("SELECT id, payload FROM %s ORDER BY id", 
tableName))
+            .collectAsList();
+    Assertions.assertEquals(2, rows.size());
+    Assertions.assertEquals(1, rows.get(0).getInt(0));
+    Assertions.assertEquals("first", rows.get(0).getString(1));
+    Assertions.assertEquals(2, rows.get(1).getInt(0));
+    Assertions.assertEquals("second", rows.get(1).getString(1));
+  }
+
   @Test
   void testPaimonCompactProcedure() {
     String tableName = "test_paimon_compact";
diff --git 
a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/paimon/TestGravitinoPaimonCatalog.java
 
b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/paimon/TestGravitinoPaimonCatalog.java
new file mode 100644
index 0000000000..eea4f00772
--- /dev/null
+++ 
b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/paimon/TestGravitinoPaimonCatalog.java
@@ -0,0 +1,820 @@
+/*
+ * 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.paimon;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+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 static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.nullable;
+import static org.mockito.Mockito.CALLS_REAL_METHODS;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.gravitino.Catalog;
+import org.apache.gravitino.catalog.PropertiesMetadataHelpers;
+import org.apache.gravitino.catalog.lakehouse.paimon.GravitinoPaimonTable;
+import 
org.apache.gravitino.catalog.lakehouse.paimon.PaimonTablePropertiesMetadata;
+import org.apache.gravitino.client.GravitinoClient;
+import org.apache.gravitino.rel.Column;
+import org.apache.gravitino.rel.Table;
+import org.apache.gravitino.rel.expressions.NamedReference;
+import org.apache.gravitino.rel.expressions.distributions.Distribution;
+import org.apache.gravitino.rel.expressions.distributions.Distributions;
+import org.apache.gravitino.rel.expressions.distributions.Strategy;
+import org.apache.gravitino.rel.expressions.literals.Literals;
+import org.apache.gravitino.rel.expressions.sorts.SortOrder;
+import org.apache.gravitino.rel.expressions.transforms.Transform;
+import org.apache.gravitino.rel.indexes.Index;
+import org.apache.gravitino.spark.connector.SparkTransformConverter;
+import org.apache.gravitino.spark.connector.SparkTypeConverter;
+import org.apache.gravitino.spark.connector.catalog.GravitinoCatalogManager;
+import org.apache.paimon.catalog.CatalogContext;
+import org.apache.paimon.catalog.CatalogFactory;
+import org.apache.paimon.options.Options;
+import org.apache.paimon.spark.SparkTable;
+import org.apache.spark.SparkConf;
+import org.apache.spark.sql.connector.catalog.Identifier;
+import org.apache.spark.sql.connector.catalog.TableCatalog;
+import org.apache.spark.sql.connector.expressions.Expressions;
+import org.apache.spark.sql.internal.SQLConf;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.MetadataBuilder;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.sql.util.CaseInsensitiveStringMap;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+/** Tests the Paimon-specific Spark create-table request and native metadata 
round trip. */
+public class TestGravitinoPaimonCatalog {
+
+  private static final StructType SCHEMA =
+      new StructType()
+          .add("source_namespace", DataTypes.StringType, false)
+          .add("source_topic", DataTypes.StringType, false)
+          .add("source_partition", DataTypes.IntegerType, false)
+          .add("source_offset", DataTypes.LongType, false)
+          .add(
+              new StructField(
+                  "payload",
+                  DataTypes.StringType,
+                  true,
+                  new MetadataBuilder().putString("comment", "event 
payload").build()))
+          .add("dt", DataTypes.StringType)
+          .add("hr", DataTypes.StringType);
+  private static final String PRIMARY_KEY =
+      "source_namespace,source_topic,source_partition,source_offset";
+
+  private org.apache.gravitino.rel.TableCatalog tableCatalog;
+  private TestCatalog catalog;
+  private Column[] columns;
+  private String comment;
+  private Map<String, String> properties;
+  private Transform[] partitioning;
+  private Distribution distribution;
+  private SortOrder[] sortOrders;
+  private Index[] indexes;
+  private boolean previousCaseSensitive;
+
+  @BeforeEach
+  void setUp() {
+    previousCaseSensitive = SQLConf.get().caseSensitiveAnalysis();
+    SQLConf.get().setConfString("spark.sql.caseSensitive", "false");
+    GravitinoClient client = mock(GravitinoClient.class);
+    Catalog gravitinoCatalog = mock(Catalog.class);
+    tableCatalog = mock(org.apache.gravitino.rel.TableCatalog.class, 
CALLS_REAL_METHODS);
+    when(gravitinoCatalog.type()).thenReturn(Catalog.Type.RELATIONAL);
+    when(gravitinoCatalog.provider()).thenReturn("lakehouse-paimon");
+    when(gravitinoCatalog.properties()).thenReturn(Map.of());
+    when(gravitinoCatalog.supportsSecrets()).thenThrow(new 
UnsupportedOperationException());
+    when(gravitinoCatalog.supportsCredentials()).thenThrow(new 
UnsupportedOperationException());
+    when(gravitinoCatalog.asTableCatalog()).thenReturn(tableCatalog);
+    when(client.loadCatalog(any())).thenReturn(gravitinoCatalog);
+    GravitinoCatalogManager.create(new SparkConf(false), "user", identity -> 
client);
+    when(tableCatalog.createTable(
+            any(),
+            any(Column[].class),
+            nullable(String.class),
+            any(),
+            any(Transform[].class),
+            nullable(Distribution.class),
+            nullable(SortOrder[].class),
+            any(Index[].class)))
+        .thenAnswer(
+            invocation -> {
+              columns = invocation.getArgument(1);
+              comment = invocation.getArgument(2);
+              properties = invocation.getArgument(3);
+              partitioning = invocation.getArgument(4);
+              distribution = invocation.getArgument(5);
+              sortOrders = invocation.getArgument(6);
+              indexes = invocation.getArgument(7);
+              return mock(Table.class);
+            });
+    catalog = new TestCatalog();
+    catalog.initialize("paimon", new CaseInsensitiveStringMap(Map.of()));
+  }
+
+  @AfterEach
+  void tearDown() {
+    SQLConf.get().setConfString("spark.sql.caseSensitive", 
String.valueOf(previousCaseSensitive));
+    GravitinoCatalogManager.get().close();
+  }
+
+  @Test
+  void testResolveCaseInsensitivePrimaryKeyBucketAndPartitionNames() {
+    StructType schema =
+        new StructType().add("Id", DataTypes.IntegerType).add("Dt", 
DataTypes.StringType);
+    catalog.create(
+        schema,
+        new org.apache.spark.sql.connector.expressions.Transform[] {
+          Expressions.identity("DT"), Expressions.bucket(4, "id")
+        },
+        Map.of("primary-key", "ID,dt", "bucket", "4", "bucket-key", "ID"));
+
+    assertArrayEquals(new String[][] {{"Id"}, {"Dt"}}, 
indexes[0].fieldNames());
+    assertArrayEquals(
+        new String[] {"Id"},
+        ((NamedReference.FieldReference) 
distribution.expressions()[0]).fieldName());
+    assertEquals("Dt", partitioning[0].references()[0].fieldName()[0]);
+    assertFalse(columns[0].nullable());
+    assertFalse(columns[1].nullable());
+  }
+
+  @ParameterizedTest
+  @ValueSource(strings = {"primary-key", "bucket-key"})
+  void testRejectCaseMismatchWhenSparkIsCaseSensitive(String option) {
+    SQLConf.get().setConfString("spark.sql.caseSensitive", "true");
+    assertThrows(
+        IllegalArgumentException.class,
+        () ->
+            catalog.create(
+                new StructType().add("id", DataTypes.IntegerType),
+                new org.apache.spark.sql.connector.expressions.Transform[0],
+                Map.of(option, "ID", "bucket", "4")));
+    verifyNoInteractions(tableCatalog);
+  }
+
+  @ParameterizedTest
+  @ValueSource(strings = {"primary-key", "bucket-key"})
+  void testRejectAmbiguousCaseInsensitiveColumnNames(String option) {
+    IllegalArgumentException error =
+        assertThrows(
+            IllegalArgumentException.class,
+            () ->
+                catalog.create(
+                    new StructType()
+                        .add("id", DataTypes.IntegerType)
+                        .add("ID", DataTypes.IntegerType),
+                    new 
org.apache.spark.sql.connector.expressions.Transform[0],
+                    Map.of(option, "Id", "bucket", "4")));
+    assertTrue(error.getMessage().contains("ambiguous"));
+    verifyNoInteractions(tableCatalog);
+  }
+
+  @Test
+  void testKeepDistinctCaseSensitiveColumnNames() {
+    SQLConf.get().setConfString("spark.sql.caseSensitive", "true");
+    catalog.create(
+        new StructType().add("id", DataTypes.IntegerType).add("ID", 
DataTypes.IntegerType),
+        new org.apache.spark.sql.connector.expressions.Transform[0],
+        Map.of("primary-key", "ID,id", "bucket", "4", "bucket-key", "ID"));
+    assertArrayEquals(new String[][] {{"ID"}, {"id"}}, 
indexes[0].fieldNames());
+    assertArrayEquals(
+        new String[] {"ID"},
+        ((NamedReference.FieldReference) 
distribution.expressions()[0]).fieldName());
+  }
+
+  @Test
+  void testResolveCaseInsensitiveLiteralDotColumns() {
+    catalog.create(
+        new StructType().add("Literal.Dot", DataTypes.IntegerType),
+        new org.apache.spark.sql.connector.expressions.Transform[0],
+        Map.of("primary-key", "literal.dot", "bucket", "4", "bucket-key", 
"LITERAL.DOT"));
+    assertArrayEquals(new String[][] {{"Literal.Dot"}}, 
indexes[0].fieldNames());
+    assertArrayEquals(
+        new String[] {"Literal.Dot"},
+        ((NamedReference.FieldReference) 
distribution.expressions()[0]).fieldName());
+  }
+
+  @Test
+  void testResolvePartitionNamesWithoutPrimaryKeyOrBuckets() {
+    catalog.create(
+        new StructType().add("Id", DataTypes.IntegerType).add("Part.Date", 
DataTypes.StringType),
+        new org.apache.spark.sql.connector.expressions.Transform[] {
+          Expressions.identity("`PART.DATE`")
+        },
+        Map.of("custom.option", "value"));
+    assertArrayEquals(new String[] {"Part.Date"}, 
partitioning[0].references()[0].fieldName());
+    assertEquals(Map.of("custom.option", "value"), properties);
+  }
+
+  @Test
+  void testRejectNonFieldDistributionExpressionWithClearMessage() {
+    SparkPaimonTable table =
+        sparkTableWithDistribution(Distributions.hash(4, 
Literals.integerLiteral(1)));
+    IllegalArgumentException error =
+        assertThrows(IllegalArgumentException.class, table::properties);
+    assertTrue(error.getMessage().contains("plain column references"));
+  }
+
+  @Test
+  void testRejectNestedDistributionReferenceWithClearMessage() {
+    SparkPaimonTable table =
+        sparkTableWithDistribution(
+            Distributions.hash(4, NamedReference.field(new String[] 
{"payload", "nested"})));
+    IllegalArgumentException error =
+        assertThrows(IllegalArgumentException.class, table::properties);
+    assertTrue(error.getMessage().contains("top-level columns"));
+  }
+
+  @Test
+  void testNativePaimonRejectsBucketKeyOutsidePrimaryKey(@TempDir Path 
warehouse) throws Exception {
+    catalog.create(
+        SCHEMA,
+        new org.apache.spark.sql.connector.expressions.Transform[0],
+        Map.of("primary-key", PRIMARY_KEY, "bucket", "4", "bucket-key", 
"payload"));
+    GravitinoPaimonTable table =
+        GravitinoPaimonTable.builder()
+            .withName("invalid_events")
+            .withColumns(columns)
+            .withProperties(properties)
+            .withPartitioning(partitioning)
+            .withDistribution(distribution)
+            .withIndexes(indexes)
+            .build();
+    try (org.apache.paimon.catalog.Catalog nativeCatalog =
+        CatalogFactory.createCatalog(
+            CatalogContext.create(
+                Options.fromMap(Map.of("warehouse", 
warehouse.toUri().toString()))))) {
+      nativeCatalog.createDatabase("default", true);
+      RuntimeException error =
+          assertThrows(
+              RuntimeException.class,
+              () ->
+                  nativeCatalog.createTable(
+                      org.apache.paimon.catalog.Identifier.create("default", 
"invalid_events"),
+                      table.toPaimonTableSchema(),
+                      false));
+      
assertTrue(error.getMessage().toLowerCase(Locale.ROOT).contains("bucket"));
+    }
+  }
+
+  @Test
+  void testCreateCompositePrimaryKeyWithDynamicBuckets() {
+    Map<String, String> options = new HashMap<>();
+    options.put("primary-key", PRIMARY_KEY);
+    options.put("bucket", "-1");
+    options.put("merge-engine", "deduplicate");
+    options.put("snapshot.time-retained", "7 d");
+    options.put("comment", "source events");
+    Map<String, String> original = new HashMap<>(options);
+
+    catalog.create(
+        SCHEMA,
+        new org.apache.spark.sql.connector.expressions.Transform[] {
+          Expressions.identity("dt"), Expressions.identity("hr")
+        },
+        options);
+
+    assertEquals(1, indexes.length);
+    assertEquals(Index.IndexType.PRIMARY_KEY, indexes[0].type());
+    assertArrayEquals(
+        new String[][] {
+          {"source_namespace"}, {"source_topic"}, {"source_partition"}, 
{"source_offset"}
+        },
+        indexes[0].fieldNames());
+    assertEquals(Strategy.HASH, distribution.strategy());
+    assertEquals(-1, distribution.number());
+    assertEquals(0, distribution.expressions().length);
+    assertEquals(2, partitioning.length);
+    assertEquals("identity", partitioning[0].name());
+    assertEquals("dt", partitioning[0].references()[0].toString());
+    assertEquals("hr", partitioning[1].references()[0].toString());
+    assertEquals("source events", comment);
+    assertEquals(
+        Map.of("merge-engine", "deduplicate", "snapshot.time-retained", "7 
d"), properties);
+    assertEquals(SCHEMA.fields().length, columns.length);
+    assertFalse(columns[0].nullable());
+    assertEquals("event payload", columns[4].comment());
+    assertEquals(0, sortOrders.length);
+    assertEquals(original, options);
+  }
+
+  @Test
+  void testCreateFixedBucketsWithExplicitKeys() {
+    catalog.create(
+        SCHEMA,
+        new org.apache.spark.sql.connector.expressions.Transform[0],
+        Map.of(
+            "primary-key", PRIMARY_KEY,
+            "bucket", " 4 ",
+            "bucket-key", " source_topic, source_partition "));
+
+    assertEquals(4, distribution.number());
+    assertEquals(2, distribution.expressions().length);
+    assertArrayEquals(
+        new String[] {"source_topic"},
+        ((NamedReference.FieldReference) 
distribution.expressions()[0]).fieldName());
+    assertArrayEquals(
+        new String[] {"source_partition"},
+        ((NamedReference.FieldReference) 
distribution.expressions()[1]).fieldName());
+    assertEquals(Map.of(), properties);
+  }
+
+  @Test
+  void testCreateClusteredByAppendTableWithPartitions() {
+    catalog.create(
+        SCHEMA,
+        new org.apache.spark.sql.connector.expressions.Transform[] {
+          Expressions.identity("dt"), Expressions.bucket(4, "source_topic", 
"source_partition")
+        },
+        Map.of("custom.option", "value"));
+
+    assertEquals(0, indexes.length);
+    assertEquals(Strategy.HASH, distribution.strategy());
+    assertEquals(4, distribution.number());
+    assertEquals(2, distribution.expressions().length);
+    assertArrayEquals(
+        new String[] {"source_topic"},
+        ((NamedReference.FieldReference) 
distribution.expressions()[0]).fieldName());
+    assertArrayEquals(
+        new String[] {"source_partition"},
+        ((NamedReference.FieldReference) 
distribution.expressions()[1]).fieldName());
+    assertEquals(1, partitioning.length);
+    assertEquals("identity", partitioning[0].name());
+    assertEquals("dt", partitioning[0].references()[0].toString());
+    assertEquals(Map.of("custom.option", "value"), properties);
+  }
+
+  @Test
+  void testCreateClusteredByPrimaryKeyTableWithMatchingProperties() {
+    catalog.create(
+        SCHEMA,
+        new org.apache.spark.sql.connector.expressions.Transform[] {
+          Expressions.bucket(4, "source_topic", "source_partition")
+        },
+        Map.of(
+            "primary-key", PRIMARY_KEY,
+            "bucket", " 4 ",
+            "bucket-key", " source_topic, source_partition "));
+
+    assertEquals(1, indexes.length);
+    assertEquals(4, distribution.number());
+    assertEquals(2, distribution.expressions().length);
+    assertEquals(0, partitioning.length);
+    assertEquals(Map.of(), properties);
+  }
+
+  @ParameterizedTest
+  @ValueSource(strings = {"-1", "8", "0", "invalid"})
+  void testRejectConflictingClusteredByBucketCount(String bucket) {
+    assertThrows(
+        IllegalArgumentException.class,
+        () ->
+            catalog.create(
+                SCHEMA,
+                new org.apache.spark.sql.connector.expressions.Transform[] {
+                  Expressions.bucket(4, "source_topic")
+                },
+                Map.of("bucket", bucket)));
+    verifyNoInteractions(tableCatalog);
+  }
+
+  @Test
+  void testRejectConflictingClusteredByBucketKeys() {
+    assertThrows(
+        IllegalArgumentException.class,
+        () ->
+            catalog.create(
+                SCHEMA,
+                new org.apache.spark.sql.connector.expressions.Transform[] {
+                  Expressions.bucket(4, "source_topic")
+                },
+                Map.of("bucket-key", "source_partition")));
+    verifyNoInteractions(tableCatalog);
+  }
+
+  @ParameterizedTest
+  @ValueSource(ints = {0, -1})
+  void testRejectNonPositiveClusteredByBucketCount(int buckets) {
+    assertThrows(
+        IllegalArgumentException.class,
+        () ->
+            catalog.create(
+                SCHEMA,
+                new org.apache.spark.sql.connector.expressions.Transform[] {
+                  Expressions.bucket(buckets, "source_topic")
+                },
+                Map.of()));
+    verifyNoInteractions(tableCatalog);
+  }
+
+  @Test
+  void testRejectMultipleBucketTransforms() {
+    assertThrows(
+        IllegalArgumentException.class,
+        () ->
+            catalog.create(
+                SCHEMA,
+                new org.apache.spark.sql.connector.expressions.Transform[] {
+                  Expressions.bucket(4, "source_topic"), Expressions.bucket(4, 
"source_partition")
+                },
+                Map.of()));
+    verifyNoInteractions(tableCatalog);
+  }
+
+  @ParameterizedTest
+  @ValueSource(strings = {"missing", "payload.nested"})
+  void testRejectInvalidClusteredByColumns(String column) {
+    assertThrows(
+        IllegalArgumentException.class,
+        () ->
+            catalog.create(
+                SCHEMA,
+                new org.apache.spark.sql.connector.expressions.Transform[] {
+                  Expressions.bucket(4, column)
+                },
+                Map.of()));
+    verifyNoInteractions(tableCatalog);
+  }
+
+  @Test
+  void testRejectSortedBuckets() {
+    assertThrows(
+        UnsupportedOperationException.class,
+        () ->
+            catalog.create(
+                SCHEMA,
+                new org.apache.spark.sql.connector.expressions.Transform[] {
+                  SparkTransformConverter.createSortBucketTransform(
+                      4, new String[] {"source_topic"}, new String[] 
{"source_partition"})
+                },
+                Map.of()));
+    verifyNoInteractions(tableCatalog);
+  }
+
+  @Test
+  void testCreateSinglePrimaryKeyWithoutBucketOptions() {
+    catalog.create(
+        SCHEMA,
+        new org.apache.spark.sql.connector.expressions.Transform[0],
+        Map.of("primary-key", " source_offset "));
+
+    assertEquals(1, indexes.length);
+    assertArrayEquals(new String[][] {{"source_offset"}}, 
indexes[0].fieldNames());
+    assertEquals(Strategy.NONE, distribution.strategy());
+    assertEquals(Map.of(), properties);
+  }
+
+  @Test
+  void testCreateFixedBucketsWithoutExplicitKeys() {
+    catalog.create(
+        SCHEMA,
+        new org.apache.spark.sql.connector.expressions.Transform[0],
+        Map.of("primary-key", PRIMARY_KEY, "bucket", "8"));
+
+    assertEquals(8, distribution.number());
+    assertEquals(0, distribution.expressions().length);
+    assertEquals(Map.of(), properties);
+  }
+
+  @Test
+  void testDelegateBucketKeysWithoutExplicitBucketCount() {
+    catalog.create(
+        SCHEMA,
+        new org.apache.spark.sql.connector.expressions.Transform[0],
+        Map.of("primary-key", PRIMARY_KEY, "bucket-key", "source_topic"));
+    assertEquals(-1, distribution.number());
+    assertEquals(1, distribution.expressions().length);
+  }
+
+  @Test
+  void testCreateWithoutPrimaryKeyOrBuckets() {
+    catalog.create(
+        SCHEMA,
+        new org.apache.spark.sql.connector.expressions.Transform[0],
+        Map.of("custom.option", "value", "owner", "spark-user"));
+
+    assertEquals(0, indexes.length);
+    assertEquals(Map.of("custom.option", "value"), properties);
+  }
+
+  @ParameterizedTest
+  @CsvSource({"true,false", "false,false", "false,true"})
+  void testPaimonSchemaRoundTrip(boolean primaryKey, boolean clusteredBy, 
@TempDir Path warehouse)
+      throws Exception {
+    Map<String, String> options = new HashMap<>();
+    options.put("bucket", primaryKey ? "-1" : "4");
+    options.put("merge-engine", "deduplicate");
+    if (primaryKey) {
+      options.put("primary-key", PRIMARY_KEY);
+    } else {
+      options.put("bucket-key", "source_topic");
+    }
+    if (clusteredBy) {
+      options.remove("bucket");
+      options.remove("bucket-key");
+    }
+    StructType inputSchema =
+        primaryKey
+            ? new StructType(
+                Arrays.stream(SCHEMA.fields())
+                    .map(
+                        field ->
+                            new StructField(field.name(), field.dataType(), 
true, field.metadata()))
+                    .toArray(StructField[]::new))
+            : SCHEMA;
+    catalog.create(
+        inputSchema,
+        clusteredBy
+            ? new org.apache.spark.sql.connector.expressions.Transform[] {
+              Expressions.identity("dt"),
+              Expressions.identity("hr"),
+              Expressions.bucket(4, "source_topic")
+            }
+            : new org.apache.spark.sql.connector.expressions.Transform[] {
+              Expressions.identity("dt"), Expressions.identity("hr")
+            },
+        options);
+    PropertiesMetadataHelpers.validatePropertyForCreate(
+        new PaimonTablePropertiesMetadata(), properties);
+    GravitinoPaimonTable table =
+        GravitinoPaimonTable.builder()
+            .withName("events")
+            .withColumns(columns)
+            .withComment(comment)
+            .withProperties(properties)
+            .withPartitioning(partitioning)
+            .withDistribution(distribution)
+            .withIndexes(indexes)
+            .build();
+    try (org.apache.paimon.catalog.Catalog nativeCatalog =
+        CatalogFactory.createCatalog(
+            CatalogContext.create(
+                Options.fromMap(Map.of("warehouse", 
warehouse.toUri().toString()))))) {
+      nativeCatalog.createDatabase("default", true);
+      org.apache.paimon.catalog.Identifier identifier =
+          org.apache.paimon.catalog.Identifier.create("default", "events");
+      nativeCatalog.createTable(identifier, table.toPaimonTableSchema(), 
false);
+      org.apache.paimon.table.Table nativeTable = 
nativeCatalog.getTable(identifier);
+      assertEquals(
+          primaryKey
+              ? List.of("source_namespace", "source_topic", 
"source_partition", "source_offset")
+              : List.of(),
+          nativeTable.primaryKeys());
+      assertEquals(List.of("dt", "hr"), nativeTable.partitionKeys());
+      assertEquals(primaryKey ? "-1" : "4", 
nativeTable.options().get("bucket"));
+      assertEquals(primaryKey ? null : "source_topic", 
nativeTable.options().get("bucket-key"));
+      GravitinoPaimonTable loaded = 
GravitinoPaimonTable.fromPaimonTable(nativeTable);
+      assertEquals(primaryKey ? 1 : 0, loaded.index().length);
+      if (primaryKey) {
+        assertArrayEquals(indexes[0].fieldNames(), 
loaded.index()[0].fieldNames());
+      }
+      assertEquals(primaryKey ? -1 : 4, loaded.distribution().number());
+      assertEquals(primaryKey ? 0 : 1, 
loaded.distribution().expressions().length);
+      assertEquals("deduplicate", loaded.properties().get("merge-engine"));
+      for (GravitinoPaimonTable metadata : List.of(table, loaded)) {
+        SparkPaimonTable sparkTable =
+            new SparkPaimonTable(
+                Identifier.of(new String[] {"default"}, "events"),
+                metadata,
+                new SparkTable(nativeTable),
+                PaimonPropertiesConverter.getInstance(),
+                catalog.getSparkTransformConverter(),
+                new SparkTypeConverter());
+        assertEquals(SCHEMA, sparkTable.schema());
+        assertEquals(primaryKey ? PRIMARY_KEY : null, 
sparkTable.properties().get("primary-key"));
+        assertEquals(primaryKey ? "-1" : "4", 
sparkTable.properties().get("bucket"));
+        assertEquals(primaryKey ? null : "source_topic", 
sparkTable.properties().get("bucket-key"));
+        assertEquals(2, sparkTable.partitioning().length);
+      }
+    }
+  }
+
+  @ParameterizedTest
+  @ValueSource(strings = {"", " ", "missing", "payload.nested", 
"source_topic,"})
+  void testRejectInvalidPrimaryKeys(String primaryKey) {
+    assertThrows(
+        IllegalArgumentException.class,
+        () ->
+            catalog.create(
+                SCHEMA,
+                new org.apache.spark.sql.connector.expressions.Transform[0],
+                Map.of("primary-key", primaryKey)));
+    verifyNoInteractions(tableCatalog);
+  }
+
+  @ParameterizedTest
+  @ValueSource(strings = {"", " ", "abc", "2147483648"})
+  void testRejectInvalidBucketNumbers(String bucket) {
+    assertThrows(
+        IllegalArgumentException.class,
+        () ->
+            catalog.create(
+                SCHEMA,
+                new org.apache.spark.sql.connector.expressions.Transform[0],
+                Map.of("primary-key", PRIMARY_KEY, "bucket", bucket)));
+    verifyNoInteractions(tableCatalog);
+  }
+
+  @ParameterizedTest
+  @ValueSource(strings = {"", "missing", "payload.nested", "source_topic,"})
+  void testRejectInvalidBucketKeys(String bucketKey) {
+    assertThrows(
+        IllegalArgumentException.class,
+        () ->
+            catalog.create(
+                SCHEMA,
+                new org.apache.spark.sql.connector.expressions.Transform[0],
+                Map.of("primary-key", PRIMARY_KEY, "bucket", "4", 
"bucket-key", bucketKey)));
+    verifyNoInteractions(tableCatalog);
+  }
+
+  @Test
+  void testDelegateBucketKeyOutsidePrimaryKey() {
+    catalog.create(
+        SCHEMA,
+        new org.apache.spark.sql.connector.expressions.Transform[0],
+        Map.of("primary-key", PRIMARY_KEY, "bucket", "4", "bucket-key", 
"payload"));
+    assertEquals("payload", 
distribution.expressions()[0].references()[0].fieldName()[0]);
+  }
+
+  @Test
+  void testDelegateDynamicBucketsWithExplicitKeys() {
+    catalog.create(
+        SCHEMA,
+        new org.apache.spark.sql.connector.expressions.Transform[0],
+        Map.of("primary-key", PRIMARY_KEY, "bucket", "-1", "bucket-key", 
"source_topic"));
+    assertEquals(-1, distribution.number());
+    assertEquals(1, distribution.expressions().length);
+  }
+
+  @Test
+  void testDelegateBucketedAppendWithoutKeys() {
+    catalog.create(
+        SCHEMA, new org.apache.spark.sql.connector.expressions.Transform[0], 
Map.of("bucket", "4"));
+    assertEquals(4, distribution.number());
+    assertEquals(0, distribution.expressions().length);
+  }
+
+  @Test
+  void testDelegatePartitionColumnsAsBucketKeys() {
+    catalog.create(
+        SCHEMA,
+        new org.apache.spark.sql.connector.expressions.Transform[] 
{Expressions.identity("dt")},
+        Map.of("primary-key", "source_topic,dt", "bucket", "4", "bucket-key", 
"dt"));
+    assertEquals("dt", 
distribution.expressions()[0].references()[0].fieldName()[0]);
+  }
+
+  @Test
+  void testDelegateFixedBucketsForCrossPartitionPrimaryKeys() {
+    catalog.create(
+        SCHEMA,
+        new org.apache.spark.sql.connector.expressions.Transform[] 
{Expressions.identity("dt")},
+        Map.of("primary-key", PRIMARY_KEY, "bucket", "4"));
+    assertEquals(4, distribution.number());
+    assertArrayEquals(new String[] {"source_namespace"}, 
indexes[0].fieldNames()[0]);
+  }
+
+  @Test
+  void testDelegatePrimaryKeyOnlyPartitionColumns() {
+    catalog.create(
+        SCHEMA,
+        new org.apache.spark.sql.connector.expressions.Transform[] 
{Expressions.identity("dt")},
+        Map.of("primary-key", "dt", "bucket", "-1"));
+    assertArrayEquals(new String[][] {{"dt"}}, indexes[0].fieldNames());
+  }
+
+  @ParameterizedTest
+  @ValueSource(strings = {"missing", "payload.nested"})
+  void testRejectInvalidPartitionColumns(String partitionColumn) {
+    assertThrows(
+        IllegalArgumentException.class,
+        () ->
+            catalog.create(
+                SCHEMA,
+                new org.apache.spark.sql.connector.expressions.Transform[] {
+                  Expressions.identity(partitionColumn)
+                },
+                Map.of("primary-key", PRIMARY_KEY, "bucket", "-1")));
+    verifyNoInteractions(tableCatalog);
+  }
+
+  @Test
+  void testDelegateDuplicatePartitionColumns() {
+    catalog.create(
+        SCHEMA,
+        new org.apache.spark.sql.connector.expressions.Transform[] {
+          Expressions.identity("dt"), Expressions.identity("dt")
+        },
+        Map.of("primary-key", PRIMARY_KEY, "bucket", "-1"));
+    assertEquals(2, partitioning.length);
+  }
+
+  @Test
+  void testPrimaryKeyWithLiteralDotColumn() {
+    catalog.create(
+        new StructType().add("literal.dot", DataTypes.IntegerType, false),
+        new org.apache.spark.sql.connector.expressions.Transform[0],
+        Map.of("primary-key", "literal.dot", "bucket", "-1"));
+    assertArrayEquals(new String[][] {{"literal.dot"}}, 
indexes[0].fieldNames());
+  }
+
+  @Test
+  void testRejectBucketTransformBeforeCreatingTable() {
+    assertThrows(
+        IllegalArgumentException.class,
+        () ->
+            catalog.create(
+                SCHEMA,
+                new org.apache.spark.sql.connector.expressions.Transform[] {
+                  Expressions.bucket(4, "source_topic")
+                },
+                Map.of("primary-key", PRIMARY_KEY, "bucket", "-1")));
+    verifyNoInteractions(tableCatalog);
+  }
+
+  @Test
+  void testRejectNonIdentityPartitionBeforeCreatingTable() {
+    assertThrows(
+        UnsupportedOperationException.class,
+        () ->
+            catalog.create(
+                SCHEMA,
+                new org.apache.spark.sql.connector.expressions.Transform[] 
{Expressions.days("dt")},
+                Map.of("primary-key", PRIMARY_KEY, "bucket", "-1")));
+    verifyNoInteractions(tableCatalog);
+  }
+
+  @ParameterizedTest
+  @ValueSource(strings = {"0", "-2"})
+  void testDelegatePaimonBucketModes(String bucket) {
+    catalog.create(
+        SCHEMA,
+        new org.apache.spark.sql.connector.expressions.Transform[0],
+        Map.of("bucket", bucket));
+    assertEquals(Integer.parseInt(bucket), distribution.number());
+  }
+
+  private SparkPaimonTable sparkTableWithDistribution(Distribution value) {
+    Table metadata = mock(Table.class);
+    when(metadata.distribution()).thenReturn(value);
+    return new SparkPaimonTable(
+        Identifier.of(new String[] {"default"}, "events"),
+        metadata,
+        new SparkTable(mock(org.apache.paimon.table.Table.class)),
+        PaimonPropertiesConverter.getInstance(),
+        catalog.getSparkTransformConverter(),
+        new SparkTypeConverter());
+  }
+
+  private static class TestCatalog extends GravitinoPaimonCatalog {
+
+    private void create(
+        StructType schema,
+        org.apache.spark.sql.connector.expressions.Transform[] transforms,
+        Map<String, String> properties) {
+      createGravitinoTable(
+          Identifier.of(new String[] {"default"}, "events"), schema, 
transforms, properties);
+    }
+
+    @Override
+    protected TableCatalog createAndInitSparkCatalog(
+        String name, CaseInsensitiveStringMap options, Map<String, String> 
properties) {
+      return mock(TableCatalog.class);
+    }
+  }
+}
diff --git a/spark-connector/v3.5/spark/build.gradle.kts 
b/spark-connector/v3.5/spark/build.gradle.kts
index 4286bb770d..0ba92711a8 100644
--- a/spark-connector/v3.5/spark/build.gradle.kts
+++ b/spark-connector/v3.5/spark/build.gradle.kts
@@ -133,6 +133,15 @@ dependencies {
   testImplementation(project(":api")) {
     exclude("org.apache.logging.log4j")
   }
+  if (scalaVersion == "2.12") {
+    // Reuse backend metadata conversion without adding another Hive 
dependency tree.
+    testImplementation(project(":catalogs:catalog-lakehouse-paimon")) {
+      isTransitive = false
+    }
+    tasks.named("compileTestJava") {
+      dependsOn(":catalogs:catalog-lakehouse-paimon:runtimeJars")
+    }
+  }
   testImplementation(project(":catalogs:catalog-glue")) {
     exclude("org.apache.logging.log4j")
   }
diff --git 
a/spark-connector/v3.5/spark/src/main/java/org/apache/gravitino/spark/connector/plugin/GravitinoSparkPlugin.java
 
b/spark-connector/v3.5/spark/src/main/java/org/apache/gravitino/spark/connector/plugin/GravitinoSparkPlugin.java
index ec19cc6753..9cce2cb935 100644
--- 
a/spark-connector/v3.5/spark/src/main/java/org/apache/gravitino/spark/connector/plugin/GravitinoSparkPlugin.java
+++ 
b/spark-connector/v3.5/spark/src/main/java/org/apache/gravitino/spark/connector/plugin/GravitinoSparkPlugin.java
@@ -24,7 +24,6 @@ import 
org.apache.gravitino.spark.connector.authorization.GravitinoAuthorization
 import org.apache.gravitino.spark.connector.catalog.SparkCatalogKind;
 import org.apache.gravitino.spark.connector.glue.GravitinoGlueCatalogSpark35;
 import org.apache.gravitino.spark.connector.hive.GravitinoHiveCatalogSpark35;
-import 
org.apache.gravitino.spark.connector.iceberg.GravitinoIcebergCatalogSpark35;
 import org.apache.gravitino.spark.connector.jdbc.GravitinoJdbcCatalogSpark35;
 import 
org.apache.gravitino.spark.connector.jdbc.postgresql.GravitinoPostgreSqlCatalogSpark35;
 import org.apache.spark.api.plugin.DriverPlugin;
@@ -37,9 +36,9 @@ import org.slf4j.LoggerFactory;
  * The entrypoint for Apache Gravitino Spark connector on Spark 3.5.
  *
  * <p>Every supported Spark version has a class of this name in this package, 
which is what users
- * name in {@code spark.plugins}. Each one binds the classes its own Spark 
version needs, as
- * compile-time class references, so a renamed or missing class fails the 
build rather than the
- * session, and a jar can only bind classes it actually contains.
+ * name in {@code spark.plugins}. Each one binds the classes its own Spark 
version needs. Adapters
+ * that link optional runtime interfaces are bound by name so unused catalogs 
do not prevent plugin
+ * startup.
  */
 public class GravitinoSparkPlugin implements SparkPlugin {
 
@@ -70,7 +69,10 @@ public class GravitinoSparkPlugin implements SparkPlugin {
         SparkBindings.builder()
             
.authorizationExtension(GravitinoAuthorizationSparkSessionExtensions.class)
             .catalog(SparkCatalogKind.HIVE, GravitinoHiveCatalogSpark35.class)
-            .catalog(SparkCatalogKind.LAKEHOUSE_ICEBERG, 
GravitinoIcebergCatalogSpark35.class)
+            // Its ProcedureCatalog interface is supplied by the optional 
Iceberg runtime.
+            .catalog(
+                SparkCatalogKind.LAKEHOUSE_ICEBERG,
+                
"org.apache.gravitino.spark.connector.iceberg.GravitinoIcebergCatalogSpark35")
             .catalog(SparkCatalogKind.GLUE, GravitinoGlueCatalogSpark35.class)
             .catalog(SparkCatalogKind.JDBC, GravitinoJdbcCatalogSpark35.class)
             .catalog(SparkCatalogKind.JDBC_POSTGRESQL, 
GravitinoPostgreSqlCatalogSpark35.class);
diff --git 
a/spark-connector/v3.5/spark/src/test/java/org/apache/gravitino/spark/connector/plugin/TestGravitinoSparkPlugin.java
 
b/spark-connector/v3.5/spark/src/test/java/org/apache/gravitino/spark/connector/plugin/TestGravitinoSparkPlugin.java
index e7577f662b..8d3d8b1dc4 100644
--- 
a/spark-connector/v3.5/spark/src/test/java/org/apache/gravitino/spark/connector/plugin/TestGravitinoSparkPlugin.java
+++ 
b/spark-connector/v3.5/spark/src/test/java/org/apache/gravitino/spark/connector/plugin/TestGravitinoSparkPlugin.java
@@ -19,6 +19,9 @@
 
 package org.apache.gravitino.spark.connector.plugin;
 
+import java.io.IOException;
+import java.io.InputStream;
+import org.apache.spark.api.plugin.SparkPlugin;
 import org.junit.jupiter.api.Assertions;
 import org.junit.jupiter.api.Test;
 
@@ -33,4 +36,56 @@ public class TestGravitinoSparkPlugin {
   void testTheBindingsThisModuleDeclaresAreComplete() {
     Assertions.assertNotNull(new GravitinoSparkPlugin().driverPlugin());
   }
+
+  @Test
+  void testDriverPluginDoesNotRequireOptionalIcebergRuntime() throws Exception 
{
+    ClassLoader loader = new 
WithoutIcebergClassLoader(GravitinoSparkPlugin.class.getClassLoader());
+    ClassLoader previous = Thread.currentThread().getContextClassLoader();
+    try {
+      Thread.currentThread().setContextClassLoader(loader);
+      Class<?> pluginClass = 
Class.forName(GravitinoSparkPlugin.class.getName(), true, loader);
+      SparkPlugin plugin = (SparkPlugin) 
pluginClass.getConstructor().newInstance();
+
+      Assertions.assertNotNull(plugin.driverPlugin());
+    } finally {
+      Thread.currentThread().setContextClassLoader(previous);
+    }
+  }
+
+  private static class WithoutIcebergClassLoader extends ClassLoader {
+
+    private WithoutIcebergClassLoader(ClassLoader parent) {
+      super(parent);
+    }
+
+    @Override
+    protected Class<?> loadClass(String name, boolean resolve) throws 
ClassNotFoundException {
+      if (name.startsWith("org.apache.iceberg.")
+          || name.startsWith("org.apache.spark.sql.connector.iceberg.")) {
+        throw new ClassNotFoundException(name);
+      }
+      if (!name.startsWith("org.apache.gravitino.spark.connector.")) {
+        return super.loadClass(name, resolve);
+      }
+      synchronized (getClassLoadingLock(name)) {
+        Class<?> loaded = findLoadedClass(name);
+        if (loaded == null) {
+          try (InputStream input =
+              getParent().getResourceAsStream(name.replace('.', '/') + 
".class")) {
+            if (input == null) {
+              throw new ClassNotFoundException(name);
+            }
+            byte[] bytes = input.readAllBytes();
+            loaded = defineClass(name, bytes, 0, bytes.length);
+          } catch (IOException e) {
+            throw new ClassNotFoundException(name, e);
+          }
+        }
+        if (resolve) {
+          resolveClass(loaded);
+        }
+        return loaded;
+      }
+    }
+  }
 }

Reply via email to