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

[PR] [#12600] feat(store): Add Semantic Model create and load persistence [gravitino]

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

   ### What changes were proposed in this pull request?
   
   Add relational persistence for creating and loading Semantic Models, including persistence objects, definition SerDe, mappers, SQL providers, service routing, JDBC backend integration, and cache registration.
   
   The feature delta is 20 files, with 1,727 insertions and 5 deletions.
   
   ### Why are the changes needed?
   
   Semantic Models need durable relational persistence with correct definition, property, and transaction semantics.
   
   Fix: #12600
   
   ### Does this PR introduce _any_ user-facing change?
   
   No new public API, REST, OpenAPI, or client surface is introduced.
   
   ### How was this patch tested?
   
   - Spotless, Javadoc, compilation, test compilation, and `git diff --check` passed.
   - `TestSemanticModelJDBCBackend` passed 9/9 across H2, MySQL, and PostgreSQL.
   - `TestBaseEntityCache` passed 6/6.


-- 
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] [#12600] feat(store): Add Semantic Model create and load persistence [gravitino]

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


##########
core/src/test/java/org/apache/gravitino/storage/relational/TestSemanticModelJDBCBackend.java:
##########
@@ -0,0 +1,264 @@
+/*
+ * 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.storage.relational;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import com.google.common.collect.ImmutableMap;
+import java.io.IOException;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.List;
+import java.util.Map;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.EntityAlreadyExistsException;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.meta.SemanticModelEntity;
+import org.apache.gravitino.semantic.AIContext;
+import org.apache.gravitino.semantic.AIContextObject;
+import org.apache.gravitino.semantic.CustomExtension;
+import org.apache.gravitino.semantic.DataType;
+import org.apache.gravitino.semantic.Dataset;
+import org.apache.gravitino.semantic.DialectExpression;
+import org.apache.gravitino.semantic.Dimension;
+import org.apache.gravitino.semantic.Expression;
+import org.apache.gravitino.semantic.Field;
+import org.apache.gravitino.semantic.Metric;
+import org.apache.gravitino.semantic.Relationship;
+import org.apache.gravitino.semantic.SemanticModelDefinition;
+import org.apache.gravitino.storage.RandomIdGenerator;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelVersionInfoMapper;
+import org.apache.gravitino.storage.relational.po.SemanticModelPO;
+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.gravitino.utils.NamespaceUtil;
+import org.apache.ibatis.session.SqlSession;
+import org.junit.jupiter.api.TestTemplate;
+
+/** Tests Semantic Model create and load persistence through {@link JDBCBackend}. */
+public class TestSemanticModelJDBCBackend extends TestJDBCBackend {
+
+  @TestTemplate
+  public void testCreateAndLoadRoundTrip() throws IOException {
+    Namespace namespace = createParents("round_trip");
+    SemanticModelEntity absent =
+        semanticModel(
+            RandomIdGenerator.INSTANCE.nextId(),
+            namespace,
+            "absent_optional_model",
+            false,
+            ImmutableMap.of("domain", "sales"));
+    SemanticModelEntity empty =
+        semanticModel(
+            RandomIdGenerator.INSTANCE.nextId(),
+            namespace,
+            "empty_optional_model",
+            true,
+            ImmutableMap.of());
+
+    backend.insert(absent, false);
+    backend.insert(empty, false);
+
+    SemanticModelEntity loadedAbsent =
+        backend.get(absent.nameIdentifier(), Entity.EntityType.SEMANTIC_MODEL);
+    SemanticModelEntity loadedEmpty =
+        backend.get(empty.nameIdentifier(), Entity.EntityType.SEMANTIC_MODEL);
+
+    assertEquals(absent, loadedAbsent);
+    assertEquals(empty, loadedEmpty);
+    assertNull(loadedAbsent.definition().relationships());
+    assertNull(loadedAbsent.definition().metrics());
+    assertEquals(0, loadedEmpty.definition().relationships().length);
+    assertEquals(0, loadedEmpty.definition().metrics().length);
+    assertTrue(loadedEmpty.properties().isEmpty());
+    assertEquals(
+        new BigDecimal("1.50"),
+        loadedAbsent.definition().aiContext().object().additionalProperties().get("threshold"));
+    assertNull(loadedAbsent.definition().aiContext().object().examples());
+    assertEquals(0, loadedAbsent.definition().aiContext().object().synonyms().length);
+  }
+
+  @TestTemplate
+  public void testDuplicateAndMissingEntities() throws IOException {
+    Namespace namespace = createParents("duplicate");
+    SemanticModelEntity original =
+        semanticModel(
+            RandomIdGenerator.INSTANCE.nextId(),
+            namespace,
+            "sales_model",
+            false,
+            ImmutableMap.of("owner", "analytics"));
+    backend.insert(original, false);
+
+    SemanticModelEntity duplicate =
+        semanticModel(
+            RandomIdGenerator.INSTANCE.nextId(),
+            namespace,
+            original.name(),
+            true,
+            ImmutableMap.of());
+    assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(duplicate, false));
+    assertEquals(
+        original, backend.get(original.nameIdentifier(), Entity.EntityType.SEMANTIC_MODEL));
+
+    NameIdentifier missingModel = NameIdentifier.of(namespace, "missing_model");
+    assertThrows(
+        NoSuchEntityException.class,
+        () -> backend.get(missingModel, Entity.EntityType.SEMANTIC_MODEL));
+
+    String suffix = Long.toUnsignedString(RandomIdGenerator.INSTANCE.nextId());
+    String metalakeName = "missing_parent_metalake_" + suffix;
+    String catalogName = "missing_parent_catalog_" + suffix;
+    createAndInsertMakeLake(metalakeName);
+    createAndInsertCatalog(metalakeName, catalogName);
+    Namespace missingParentNamespace =
+        NamespaceUtil.ofSemanticModel(metalakeName, catalogName, "missing_schema");
+    SemanticModelEntity missingParent =
+        semanticModel(
+            RandomIdGenerator.INSTANCE.nextId(),
+            missingParentNamespace,
+            "orphan_model",
+            false,
+            ImmutableMap.of());
+
+    assertThrows(NoSuchEntityException.class, () -> backend.insert(missingParent, false));
+    assertEquals(0, countRows(SemanticModelMetaMapper.TABLE_NAME, missingParent.id()));
+    assertEquals(0, countRows(SemanticModelVersionInfoMapper.TABLE_NAME, missingParent.id()));
+  }
+
+  @TestTemplate
+  public void testCreateRollsBackIdentityWhenSnapshotInsertFails() throws IOException {
+    Namespace namespace = createParents("transaction");
+    SemanticModelEntity semanticModel =
+        semanticModel(
+            RandomIdGenerator.INSTANCE.nextId(),
+            namespace,
+            "transaction_model",
+            false,
+            ImmutableMap.of("domain", "finance"));
+    SemanticModelPO po =
+        SemanticModelPO.initializeSemanticModelPO(semanticModel, SemanticModelPO.builder());
+    SessionUtils.doWithCommit(
+        SemanticModelVersionInfoMapper.class,
+        mapper -> mapper.insertSemanticModelVersionInfo(po.getSemanticModelVersionInfoPO()));
+
+    assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(semanticModel, false));
+    assertEquals(0, countRows(SemanticModelMetaMapper.TABLE_NAME, semanticModel.id()));
+    assertEquals(1, countRows(SemanticModelVersionInfoMapper.TABLE_NAME, semanticModel.id()));
+  }

Review Comment:
   The current tests cover the initial create/load path well, but they never exercise `backend.insert(..., true)`, so they cannot detect version resets or identity/snapshot mismatches in the overwrite path. Please extend the coverage before merging:
   
   1. Overwrite an existing Semantic Model with the same stable ID and assert that `current_version` and `last_version` advance from N to N + 1, the new snapshot uses N + 1, and the previous snapshot is handled according to the retention design.
   2. Cover a natural-key overwrite (same schema/name with a different incoming ID) and assert consistent behavior across H2, MySQL, and PostgreSQL, with no orphan snapshot under the incoming ID.
   3. Exercise both read routes: cache-enabled parent-ID lookup and cache-disabled fully-qualified-name lookup, including missing metalake/catalog/schema/model cases and the Semantic Model branch of `RelationalEntityStoreIdResolver`.
   4. Add focused SerDe tests using a fully populated definition: non-empty relationships, metrics, and custom extensions; dataset unique keys and optional fields; text and structured AI contexts; all `DataType` values; multiple dialects; nested/null/boolean/integer/decimal additional properties; and null-vs-empty arrays. A golden persisted JSON fixture would also protect compatibility.
   5. Add concurrency/atomicity coverage for duplicate concurrent creates, overwrite races, and create-vs-schema-drop, asserting that the identity row, version row, and change log commit or roll back together.
   
   The existing rollback test validates snapshot-insert failure after the identity insert, which is valuable; the missing cases above are the paths most likely to expose cross-database and versioning bugs.



-- 
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] [#12600] feat(store): Add Semantic Model create and load persistence [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelPO.java:
##########
@@ -0,0 +1,225 @@
+/*
+ * 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.storage.relational.po;
+
+import static org.apache.gravitino.storage.relational.utils.POConverters.DEFAULT_DELETED_AT;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.base.Preconditions;
+import java.util.Collections;
+import java.util.Map;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+import lombok.ToString;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.json.JsonUtils;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.NamespacedEntityId;
+import org.apache.gravitino.meta.SemanticModelEntity;
+import org.apache.gravitino.semantic.SemanticModelDefinition;
+import org.apache.gravitino.storage.relational.service.EntityIdService;
+
+/** The persistent object for Semantic Model identity metadata and its current version snapshot. */
+@Getter
+@EqualsAndHashCode(exclude = "semanticModelVersionInfoPO")
+@ToString
+public class SemanticModelPO {
+
+  /** The initial version allocated to a newly created Semantic Model. */
+  public static final Integer INITIAL_VERSION = 1;
+
+  private Long semanticModelId;
+  private String semanticModelName;
+  private Long metalakeId;
+  private Long catalogId;
+  private Long schemaId;
+  private String auditInfo;
+  private Integer currentVersion;
+  private Integer lastVersion;
+  private Long deletedAt;
+  private SemanticModelVersionInfoPO semanticModelVersionInfoPO;
+
+  /** Creates an empty persistent object for MyBatis. */
+  public SemanticModelPO() {}
+
+  /** A Lombok builder for {@link SemanticModelPO}. */
+  public static class SemanticModelPOBuilder {
+    // Lombok generates the builder methods.
+  }
+
+  @lombok.Builder(setterPrefix = "with")
+  private SemanticModelPO(
+      Long semanticModelId,
+      String semanticModelName,
+      Long metalakeId,
+      Long catalogId,
+      Long schemaId,
+      String auditInfo,
+      Integer currentVersion,
+      Integer lastVersion,
+      Long deletedAt,
+      SemanticModelVersionInfoPO semanticModelVersionInfoPO) {
+    Preconditions.checkArgument(semanticModelId != null, "Semantic Model id is required");
+    Preconditions.checkArgument(semanticModelName != null, "Semantic Model name is required");
+    Preconditions.checkArgument(metalakeId != null, "Metalake id is required");
+    Preconditions.checkArgument(catalogId != null, "Catalog id is required");
+    Preconditions.checkArgument(schemaId != null, "Schema id is required");
+    Preconditions.checkArgument(auditInfo != null, "Audit info is required");
+    Preconditions.checkArgument(currentVersion != null, "Current version is required");
+    Preconditions.checkArgument(lastVersion != null, "Last version is required");
+    Preconditions.checkArgument(deletedAt != null, "Deleted at is required");
+
+    this.semanticModelId = semanticModelId;
+    this.semanticModelName = semanticModelName;
+    this.metalakeId = metalakeId;
+    this.catalogId = catalogId;
+    this.schemaId = schemaId;
+    this.auditInfo = auditInfo;
+    this.currentVersion = currentVersion;
+    this.lastVersion = lastVersion;
+    this.deletedAt = deletedAt;
+    this.semanticModelVersionInfoPO = semanticModelVersionInfoPO;
+  }
+
+  /**
+   * Converts a persistent object and its current version snapshot to a Semantic Model entity.
+   *
+   * @param semanticModelPO The persistent object to convert.
+   * @param namespace The Semantic Model namespace.
+   * @return The converted Semantic Model entity.
+   */
+  public static SemanticModelEntity fromSemanticModelPO(
+      SemanticModelPO semanticModelPO, Namespace namespace) {
+    try {
+      SemanticModelVersionInfoPO versionPO = semanticModelPO.getSemanticModelVersionInfoPO();
+      SemanticModelDefinition definition =
+          SemanticModelDefinitionSerDe.deserialize(versionPO.semanticModelDefinition());
+      Map<String, String> properties =
+          versionPO.properties() == null
+              ? Collections.emptyMap()
+              : JsonUtils.anyFieldMapper()
+                  .readValue(
+                      versionPO.properties(),
+                      JsonUtils.anyFieldMapper()
+                          .getTypeFactory()
+                          .constructMapType(Map.class, String.class, String.class));
+
+      return SemanticModelEntity.builder()
+          .withId(semanticModelPO.getSemanticModelId())
+          .withName(versionPO.semanticModelName())
+          .withNamespace(namespace)
+          .withComment(versionPO.semanticModelComment())
+          .withDefinition(definition)
+          .withProperties(properties)
+          .withAuditInfo(
+              JsonUtils.anyFieldMapper().readValue(semanticModelPO.getAuditInfo(), AuditInfo.class))
+          .build();
+    } catch (JsonProcessingException e) {
+      throw new RuntimeException("Failed to deserialize Semantic Model JSON", e);
+    }
+  }
+
+  /**
+   * Initializes a new Semantic Model identity and version-one snapshot.
+   *
+   * @param semanticModelEntity The Semantic Model entity.
+   * @param builder The identity persistent-object builder.
+   * @return The initialized persistent object.
+   */
+  public static SemanticModelPO initializeSemanticModelPO(
+      SemanticModelEntity semanticModelEntity, SemanticModelPOBuilder builder) {
+    return buildSemanticModelPO(semanticModelEntity, builder, INITIAL_VERSION);
+  }
+
+  /**
+   * Creates a complete version snapshot for a Semantic Model entity.
+   *
+   * @param semanticModelEntity The Semantic Model entity.
+   * @param namespacedEntityId The resolved schema and ancestor IDs.
+   * @param version The version to allocate.
+   * @return The version snapshot persistent object.
+   */
+  public static SemanticModelVersionInfoPO initializeSemanticModelVersionInfoPO(
+      SemanticModelEntity semanticModelEntity,
+      NamespacedEntityId namespacedEntityId,
+      Integer version) {
+    try {
+      String definitionJson =
+          SemanticModelDefinitionSerDe.serialize(semanticModelEntity.definition());

Review Comment:
   A null definition cannot reach this storage path through normal construction. `DEFINITION` is declared with `Field.required(...)`, and `Builder.build()` calls `Entity.super.validate()`, which rejects null required fields. `TestSemanticModelEntity#testRequiredFieldValidation` already covers this case, so the literal `"null"` cannot be persisted through this path.



-- 
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] [#12600] feat(store): Add Semantic Model create and load persistence [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetaService.java:
##########
@@ -0,0 +1,226 @@
+/*
+ * 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.storage.relational.service;
+
+import static org.apache.gravitino.metrics.source.MetricsSource.GRAVITINO_RELATIONAL_STORE_METRIC_NAME;
+import static org.apache.gravitino.storage.relational.po.SemanticModelPO.fromSemanticModelPO;
+import static org.apache.gravitino.storage.relational.po.SemanticModelPO.initializeSemanticModelPO;
+
+import com.google.common.base.Preconditions;
+import java.io.IOException;
+import java.util.Locale;
+import java.util.concurrent.atomic.AtomicReference;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.meta.SemanticModelEntity;
+import org.apache.gravitino.metrics.Monitored;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelVersionInfoMapper;
+import org.apache.gravitino.storage.relational.po.SemanticModelPO;
+import org.apache.gravitino.storage.relational.po.SemanticModelVersionInfoPO;
+import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.gravitino.utils.NameIdentifierUtil;
+
+/** Provides relational create and load operations for Semantic Model metadata. */
+public class SemanticModelMetaService {
+
+  private static final SemanticModelMetaService INSTANCE = new SemanticModelMetaService();
+
+  private final BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> ops;
+
+  /** Returns the singleton Semantic Model metadata service. */
+  public static SemanticModelMetaService getInstance() {
+    return INSTANCE;
+  }
+
+  private SemanticModelMetaService() {
+    this.ops = new HierarchicalConversionPOStorageOps<>(new SemanticModelPOStorageOps());
+  }
+
+  /**
+   * Resolves a Semantic Model stable ID by schema ID and name.
+   *
+   * @param schemaId The parent schema ID.
+   * @param semanticModelName The Semantic Model name.
+   * @return The stable Semantic Model ID.
+   * @throws NoSuchEntityException If the Semantic Model does not exist.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "getSemanticModelIdBySchemaIdAndName")
+  public Long getSemanticModelIdBySchemaIdAndName(long schemaId, String semanticModelName) {
+    Long semanticModelId =
+        SessionUtils.getWithoutCommit(
+            SemanticModelMetaMapper.class,
+            mapper -> mapper.selectSemanticModelIdBySchemaIdAndName(schemaId, semanticModelName));
+    if (semanticModelId == null) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.SEMANTIC_MODEL.name().toLowerCase(Locale.ROOT),
+          semanticModelName);
+    }
+    return semanticModelId;
+  }
+
+  /**
+   * Loads the current Semantic Model by identifier.
+   *
+   * @param identifier The Semantic Model identifier.
+   * @return The current Semantic Model entity.
+   * @throws NoSuchEntityException If the Semantic Model does not exist.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "getSemanticModelByIdentifier")
+  public SemanticModelEntity getSemanticModelByIdentifier(NameIdentifier identifier) {
+    SemanticModelPO semanticModelPO = getSemanticModelPOByIdentifier(identifier);
+    return fromSemanticModelPO(semanticModelPO, identifier.namespace());
+  }
+
+  /**
+   * Inserts a Semantic Model identity and its version-one snapshot atomically.
+   *
+   * @param semanticModelEntity The Semantic Model entity.
+   * @param overwrite Whether to overwrite rows for the same stable ID or natural key.
+   * @throws IOException If relational persistence fails.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "insertSemanticModel")
+  public void insertSemanticModel(SemanticModelEntity semanticModelEntity, boolean overwrite)
+      throws IOException {
+    NameIdentifierUtil.checkSemanticModel(semanticModelEntity.nameIdentifier());
+    try {
+      SemanticModelPO po =
+          initializeSemanticModelPO(semanticModelEntity, SemanticModelPO.builder());
+      AtomicReference<SemanticModelPO> persistedPO = new AtomicReference<>();
+      AtomicReference<SemanticModelVersionInfoPO> persistedVersionInfoPO =
+          new AtomicReference<>(po.getSemanticModelVersionInfoPO());
+      SessionUtils.doMultipleWithCommit(
+          () ->
+              SchemaMetaService.getInstance()
+                  .lockSchemaForEntityWrite(
+                      semanticModelEntity.nameIdentifier(),
+                      po.getSchemaId(),
+                      po.getCatalogId(),
+                      po.getMetalakeId()),
+          () ->
+              SessionUtils.doWithoutCommit(
+                  SemanticModelMetaMapper.class,
+                  mapper -> {
+                    if (overwrite) {

Review Comment:
   **correctness**: `insertSemanticModel`'s overwrite path is a check-then-act (SELECT-by-name, then `SELECT...FOR UPDATE`, then INSERT) rather than an atomic upsert, so two concurrent overwrites that each start from their own unresolved id can leave an orphaned version-info row.
   
   Two concurrent `insertSemanticModel(entity, overwrite=true)` calls target the same `(schema_id, semantic_model_name)` but each carries its own freshly-generated id. Both `selectSemanticModelIdBySchemaIdAndName` calls (lines 130-132) run before either commits and return `null`, so both treat this as a fresh row and skip `identityForOverwrite`/`versionInfoForOverwrite`. Thread A's INSERT commits first; Thread B's INSERT (with a different `semantic_model_id`) collides with Thread A's row on the `uk_sid_smn_del` unique key. On MySQL, `ON DUPLICATE KEY UPDATE` silently resolves this by updating Thread A's row (keeping Thread A's id) — but Thread B's version-info insert already used Thread B's own (now-unused) `semantic_model_id`, producing a permanently orphaned `semantic_model_version_info` row with no matching identity row. On PostgreSQL the same race instead throws an unhandled unique-constraint violation, since `ON CONFLICT (semantic_model_id)` only covers the PK. `TableMetaServi
 ce.insertTable` avoids this by inserting first and reading the DB-resolved identity back afterward; this code does the opposite (pre-fetch/lock/recompute), reintroducing the hazard that pattern was designed to avoid.



##########
core/src/main/java/org/apache/gravitino/cache/BaseEntityCache.java:
##########
@@ -58,6 +58,7 @@ public abstract class BaseEntityCache implements EntityCache {
           Entity.EntityType.CATALOG,
           Entity.EntityType.SCHEMA,
           Entity.EntityType.TABLE,
+          Entity.EntityType.SEMANTIC_MODEL,

Review Comment:
   **correctness**: `SEMANTIC_MODEL` was added to `CACHEABLE_TYPES` even though this class's own Javadoc says entities with a load-bearing version pointer (like `MODEL` and `FUNCTION`, which are deliberately excluded) must not be cached — and Semantic Model has exactly that structure (`current_version` pointing into a separate version-snapshot table).
   
   With `Coherence.LOCAL_PER_NODE` (the default, per this class's own doc), node A caches a `SemanticModelEntity` at version 1. A concurrent overwrite on node B bumps `current_version` to 2 with a new definition. Node A keeps serving the stale version-1 definition from cache until invalidation propagates — exactly the failure mode the class's Javadoc says `MODEL`/`MODEL_VERSION`/`FUNCTION` were excluded to avoid, since Semantic Model's storage layout (`SemanticModelPO` + `SemanticModelVersionInfoPO` joined via `current_version`) is structurally identical to Function's.



##########
core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelPO.java:
##########
@@ -0,0 +1,225 @@
+/*
+ * 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.storage.relational.po;
+
+import static org.apache.gravitino.storage.relational.utils.POConverters.DEFAULT_DELETED_AT;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.base.Preconditions;
+import java.util.Collections;
+import java.util.Map;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+import lombok.ToString;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.json.JsonUtils;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.NamespacedEntityId;
+import org.apache.gravitino.meta.SemanticModelEntity;
+import org.apache.gravitino.semantic.SemanticModelDefinition;
+import org.apache.gravitino.storage.relational.service.EntityIdService;
+
+/** The persistent object for Semantic Model identity metadata and its current version snapshot. */
+@Getter
+@EqualsAndHashCode(exclude = "semanticModelVersionInfoPO")
+@ToString
+public class SemanticModelPO {
+
+  /** The initial version allocated to a newly created Semantic Model. */
+  public static final Integer INITIAL_VERSION = 1;
+
+  private Long semanticModelId;
+  private String semanticModelName;
+  private Long metalakeId;
+  private Long catalogId;
+  private Long schemaId;
+  private String auditInfo;
+  private Integer currentVersion;
+  private Integer lastVersion;
+  private Long deletedAt;
+  private SemanticModelVersionInfoPO semanticModelVersionInfoPO;
+
+  /** Creates an empty persistent object for MyBatis. */
+  public SemanticModelPO() {}
+
+  /** A Lombok builder for {@link SemanticModelPO}. */
+  public static class SemanticModelPOBuilder {
+    // Lombok generates the builder methods.
+  }
+
+  @lombok.Builder(setterPrefix = "with")
+  private SemanticModelPO(
+      Long semanticModelId,
+      String semanticModelName,
+      Long metalakeId,
+      Long catalogId,
+      Long schemaId,
+      String auditInfo,
+      Integer currentVersion,
+      Integer lastVersion,
+      Long deletedAt,
+      SemanticModelVersionInfoPO semanticModelVersionInfoPO) {
+    Preconditions.checkArgument(semanticModelId != null, "Semantic Model id is required");
+    Preconditions.checkArgument(semanticModelName != null, "Semantic Model name is required");
+    Preconditions.checkArgument(metalakeId != null, "Metalake id is required");
+    Preconditions.checkArgument(catalogId != null, "Catalog id is required");
+    Preconditions.checkArgument(schemaId != null, "Schema id is required");
+    Preconditions.checkArgument(auditInfo != null, "Audit info is required");
+    Preconditions.checkArgument(currentVersion != null, "Current version is required");
+    Preconditions.checkArgument(lastVersion != null, "Last version is required");
+    Preconditions.checkArgument(deletedAt != null, "Deleted at is required");
+
+    this.semanticModelId = semanticModelId;
+    this.semanticModelName = semanticModelName;
+    this.metalakeId = metalakeId;
+    this.catalogId = catalogId;
+    this.schemaId = schemaId;
+    this.auditInfo = auditInfo;
+    this.currentVersion = currentVersion;
+    this.lastVersion = lastVersion;
+    this.deletedAt = deletedAt;
+    this.semanticModelVersionInfoPO = semanticModelVersionInfoPO;
+  }
+
+  /**
+   * Converts a persistent object and its current version snapshot to a Semantic Model entity.
+   *
+   * @param semanticModelPO The persistent object to convert.
+   * @param namespace The Semantic Model namespace.
+   * @return The converted Semantic Model entity.
+   */
+  public static SemanticModelEntity fromSemanticModelPO(
+      SemanticModelPO semanticModelPO, Namespace namespace) {
+    try {
+      SemanticModelVersionInfoPO versionPO = semanticModelPO.getSemanticModelVersionInfoPO();
+      SemanticModelDefinition definition =
+          SemanticModelDefinitionSerDe.deserialize(versionPO.semanticModelDefinition());
+      Map<String, String> properties =
+          versionPO.properties() == null
+              ? Collections.emptyMap()
+              : JsonUtils.anyFieldMapper()
+                  .readValue(
+                      versionPO.properties(),
+                      JsonUtils.anyFieldMapper()
+                          .getTypeFactory()
+                          .constructMapType(Map.class, String.class, String.class));
+
+      return SemanticModelEntity.builder()
+          .withId(semanticModelPO.getSemanticModelId())
+          .withName(versionPO.semanticModelName())
+          .withNamespace(namespace)
+          .withComment(versionPO.semanticModelComment())
+          .withDefinition(definition)
+          .withProperties(properties)
+          .withAuditInfo(
+              JsonUtils.anyFieldMapper().readValue(semanticModelPO.getAuditInfo(), AuditInfo.class))
+          .build();
+    } catch (JsonProcessingException e) {
+      throw new RuntimeException("Failed to deserialize Semantic Model JSON", e);
+    }
+  }
+
+  /**
+   * Initializes a new Semantic Model identity and version-one snapshot.
+   *
+   * @param semanticModelEntity The Semantic Model entity.
+   * @param builder The identity persistent-object builder.
+   * @return The initialized persistent object.
+   */
+  public static SemanticModelPO initializeSemanticModelPO(
+      SemanticModelEntity semanticModelEntity, SemanticModelPOBuilder builder) {
+    return buildSemanticModelPO(semanticModelEntity, builder, INITIAL_VERSION);
+  }
+
+  /**
+   * Creates a complete version snapshot for a Semantic Model entity.
+   *
+   * @param semanticModelEntity The Semantic Model entity.
+   * @param namespacedEntityId The resolved schema and ancestor IDs.
+   * @param version The version to allocate.
+   * @return The version snapshot persistent object.
+   */
+  public static SemanticModelVersionInfoPO initializeSemanticModelVersionInfoPO(
+      SemanticModelEntity semanticModelEntity,
+      NamespacedEntityId namespacedEntityId,
+      Integer version) {
+    try {
+      String definitionJson =
+          SemanticModelDefinitionSerDe.serialize(semanticModelEntity.definition());

Review Comment:
   **correctness**: `buildSemanticModelPO` calls `SemanticModelDefinitionSerDe.serialize(semanticModelEntity.definition())` with no null check; if `definition()` is null, Jackson serializes it to the literal string `"null"`, which passes the `StringUtils.isNotBlank` precondition meant to reject a missing definition.
   
   `SemanticModelEntity.validate()` (line 192) only delegates to `Entity.super.validate()` and never checks `definition` for null, and `Builder.withDefinition` (line 298) accepts null unchecked. If an entity is built without a definition, `serialize(null)` returns the 4-character string `"null"` (valid, non-blank text), which satisfies `SemanticModelVersionInfoPO`'s constructor check `Preconditions.checkArgument(StringUtils.isNotBlank(semanticModelDefinition), ...)`. The row persists with a literal `"null"` definition string instead of failing fast, and a later read deserializes it back into a broken/null definition, silently propagating a malformed Semantic Model instead of rejecting it at write time.



##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetaService.java:
##########
@@ -0,0 +1,226 @@
+/*
+ * 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.storage.relational.service;
+
+import static org.apache.gravitino.metrics.source.MetricsSource.GRAVITINO_RELATIONAL_STORE_METRIC_NAME;
+import static org.apache.gravitino.storage.relational.po.SemanticModelPO.fromSemanticModelPO;
+import static org.apache.gravitino.storage.relational.po.SemanticModelPO.initializeSemanticModelPO;
+
+import com.google.common.base.Preconditions;
+import java.io.IOException;
+import java.util.Locale;
+import java.util.concurrent.atomic.AtomicReference;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.meta.SemanticModelEntity;
+import org.apache.gravitino.metrics.Monitored;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelVersionInfoMapper;
+import org.apache.gravitino.storage.relational.po.SemanticModelPO;
+import org.apache.gravitino.storage.relational.po.SemanticModelVersionInfoPO;
+import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.gravitino.utils.NameIdentifierUtil;
+
+/** Provides relational create and load operations for Semantic Model metadata. */
+public class SemanticModelMetaService {
+
+  private static final SemanticModelMetaService INSTANCE = new SemanticModelMetaService();
+
+  private final BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> ops;
+
+  /** Returns the singleton Semantic Model metadata service. */
+  public static SemanticModelMetaService getInstance() {
+    return INSTANCE;
+  }
+
+  private SemanticModelMetaService() {
+    this.ops = new HierarchicalConversionPOStorageOps<>(new SemanticModelPOStorageOps());
+  }
+
+  /**
+   * Resolves a Semantic Model stable ID by schema ID and name.
+   *
+   * @param schemaId The parent schema ID.
+   * @param semanticModelName The Semantic Model name.
+   * @return The stable Semantic Model ID.
+   * @throws NoSuchEntityException If the Semantic Model does not exist.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "getSemanticModelIdBySchemaIdAndName")
+  public Long getSemanticModelIdBySchemaIdAndName(long schemaId, String semanticModelName) {
+    Long semanticModelId =
+        SessionUtils.getWithoutCommit(
+            SemanticModelMetaMapper.class,
+            mapper -> mapper.selectSemanticModelIdBySchemaIdAndName(schemaId, semanticModelName));
+    if (semanticModelId == null) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.SEMANTIC_MODEL.name().toLowerCase(Locale.ROOT),
+          semanticModelName);
+    }
+    return semanticModelId;
+  }
+
+  /**
+   * Loads the current Semantic Model by identifier.
+   *
+   * @param identifier The Semantic Model identifier.
+   * @return The current Semantic Model entity.
+   * @throws NoSuchEntityException If the Semantic Model does not exist.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "getSemanticModelByIdentifier")
+  public SemanticModelEntity getSemanticModelByIdentifier(NameIdentifier identifier) {
+    SemanticModelPO semanticModelPO = getSemanticModelPOByIdentifier(identifier);
+    return fromSemanticModelPO(semanticModelPO, identifier.namespace());
+  }
+
+  /**
+   * Inserts a Semantic Model identity and its version-one snapshot atomically.
+   *
+   * @param semanticModelEntity The Semantic Model entity.
+   * @param overwrite Whether to overwrite rows for the same stable ID or natural key.
+   * @throws IOException If relational persistence fails.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "insertSemanticModel")
+  public void insertSemanticModel(SemanticModelEntity semanticModelEntity, boolean overwrite)
+      throws IOException {
+    NameIdentifierUtil.checkSemanticModel(semanticModelEntity.nameIdentifier());
+    try {
+      SemanticModelPO po =
+          initializeSemanticModelPO(semanticModelEntity, SemanticModelPO.builder());
+      AtomicReference<SemanticModelPO> persistedPO = new AtomicReference<>();
+      AtomicReference<SemanticModelVersionInfoPO> persistedVersionInfoPO =
+          new AtomicReference<>(po.getSemanticModelVersionInfoPO());
+      SessionUtils.doMultipleWithCommit(
+          () ->
+              SchemaMetaService.getInstance()
+                  .lockSchemaForEntityWrite(
+                      semanticModelEntity.nameIdentifier(),
+                      po.getSchemaId(),
+                      po.getCatalogId(),
+                      po.getMetalakeId()),
+          () ->
+              SessionUtils.doWithoutCommit(
+                  SemanticModelMetaMapper.class,
+                  mapper -> {
+                    if (overwrite) {
+                      Long persistedId =

Review Comment:
   **efficiency**: The overwrite path costs 3 sequential DB round trips (SELECT id-by-name, `SELECT...FOR UPDATE`, then INSERT) where the established pattern used by `TableMetaService.insertTable` and `FilesetMetaService` (insert first via the atomic `ON DUPLICATE KEY UPDATE`, then a single read-back SELECT) costs 2, and reimplements version-resolution logic in Java that duplicates what the SQL's `ON DUPLICATE KEY UPDATE` already computes atomically.
   
   Every `overwrite=true` call to `insertSemanticModel` does one extra query versus the equivalent Table/Fileset path for no additional correctness benefit, since the upsert statement already atomically locks and updates the row via the natural key. This also duplicates the "+1" version-bump logic in two places (Java's `versionInfoForOverwrite` and the SQL's `current_version + 1`), which must be kept in lockstep — the exact kind of drift that produced the finding above on `identityForOverwrite`.



##########
core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelPO.java:
##########
@@ -0,0 +1,225 @@
+/*
+ * 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.storage.relational.po;
+
+import static org.apache.gravitino.storage.relational.utils.POConverters.DEFAULT_DELETED_AT;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.base.Preconditions;
+import java.util.Collections;
+import java.util.Map;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+import lombok.ToString;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.json.JsonUtils;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.NamespacedEntityId;
+import org.apache.gravitino.meta.SemanticModelEntity;
+import org.apache.gravitino.semantic.SemanticModelDefinition;
+import org.apache.gravitino.storage.relational.service.EntityIdService;
+
+/** The persistent object for Semantic Model identity metadata and its current version snapshot. */
+@Getter
+@EqualsAndHashCode(exclude = "semanticModelVersionInfoPO")
+@ToString
+public class SemanticModelPO {
+
+  /** The initial version allocated to a newly created Semantic Model. */
+  public static final Integer INITIAL_VERSION = 1;
+
+  private Long semanticModelId;
+  private String semanticModelName;
+  private Long metalakeId;
+  private Long catalogId;
+  private Long schemaId;
+  private String auditInfo;
+  private Integer currentVersion;
+  private Integer lastVersion;
+  private Long deletedAt;
+  private SemanticModelVersionInfoPO semanticModelVersionInfoPO;
+
+  /** Creates an empty persistent object for MyBatis. */
+  public SemanticModelPO() {}
+
+  /** A Lombok builder for {@link SemanticModelPO}. */
+  public static class SemanticModelPOBuilder {
+    // Lombok generates the builder methods.
+  }
+
+  @lombok.Builder(setterPrefix = "with")
+  private SemanticModelPO(
+      Long semanticModelId,
+      String semanticModelName,
+      Long metalakeId,
+      Long catalogId,
+      Long schemaId,
+      String auditInfo,
+      Integer currentVersion,
+      Integer lastVersion,
+      Long deletedAt,
+      SemanticModelVersionInfoPO semanticModelVersionInfoPO) {
+    Preconditions.checkArgument(semanticModelId != null, "Semantic Model id is required");
+    Preconditions.checkArgument(semanticModelName != null, "Semantic Model name is required");
+    Preconditions.checkArgument(metalakeId != null, "Metalake id is required");
+    Preconditions.checkArgument(catalogId != null, "Catalog id is required");
+    Preconditions.checkArgument(schemaId != null, "Schema id is required");
+    Preconditions.checkArgument(auditInfo != null, "Audit info is required");
+    Preconditions.checkArgument(currentVersion != null, "Current version is required");
+    Preconditions.checkArgument(lastVersion != null, "Last version is required");
+    Preconditions.checkArgument(deletedAt != null, "Deleted at is required");
+
+    this.semanticModelId = semanticModelId;
+    this.semanticModelName = semanticModelName;
+    this.metalakeId = metalakeId;
+    this.catalogId = catalogId;
+    this.schemaId = schemaId;
+    this.auditInfo = auditInfo;
+    this.currentVersion = currentVersion;
+    this.lastVersion = lastVersion;
+    this.deletedAt = deletedAt;
+    this.semanticModelVersionInfoPO = semanticModelVersionInfoPO;
+  }
+
+  /**
+   * Converts a persistent object and its current version snapshot to a Semantic Model entity.
+   *
+   * @param semanticModelPO The persistent object to convert.
+   * @param namespace The Semantic Model namespace.
+   * @return The converted Semantic Model entity.
+   */
+  public static SemanticModelEntity fromSemanticModelPO(
+      SemanticModelPO semanticModelPO, Namespace namespace) {
+    try {
+      SemanticModelVersionInfoPO versionPO = semanticModelPO.getSemanticModelVersionInfoPO();
+      SemanticModelDefinition definition =
+          SemanticModelDefinitionSerDe.deserialize(versionPO.semanticModelDefinition());
+      Map<String, String> properties =
+          versionPO.properties() == null
+              ? Collections.emptyMap()
+              : JsonUtils.anyFieldMapper()

Review Comment:
   **simplification**: Deserializing the properties column manually constructs a Jackson `MapType` via `getTypeFactory().constructMapType(Map.class, String.class, String.class)`, instead of the simpler `JsonUtils.anyFieldMapper().readValue(xxxPO.getProperties(), Map.class)` idiom used for the same properties column by every other PO in `POConverters.java` (Metalake, Catalog, Schema, Table, Fileset, Topic).
   
   Not a bug, but a heavier, non-conforming reimplementation of a one-line pattern used everywhere else in the module — a reader has to notice this is the one PO that builds its own `MapType` instead of following the established `readValue(..., Map.class)` shortcut, adding unnecessary cognitive overhead for no behavioral difference.



##########
core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelPO.java:
##########
@@ -0,0 +1,225 @@
+/*
+ * 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.storage.relational.po;
+
+import static org.apache.gravitino.storage.relational.utils.POConverters.DEFAULT_DELETED_AT;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.base.Preconditions;
+import java.util.Collections;
+import java.util.Map;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+import lombok.ToString;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.json.JsonUtils;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.NamespacedEntityId;
+import org.apache.gravitino.meta.SemanticModelEntity;
+import org.apache.gravitino.semantic.SemanticModelDefinition;
+import org.apache.gravitino.storage.relational.service.EntityIdService;
+
+/** The persistent object for Semantic Model identity metadata and its current version snapshot. */
+@Getter
+@EqualsAndHashCode(exclude = "semanticModelVersionInfoPO")
+@ToString
+public class SemanticModelPO {
+
+  /** The initial version allocated to a newly created Semantic Model. */
+  public static final Integer INITIAL_VERSION = 1;
+
+  private Long semanticModelId;
+  private String semanticModelName;
+  private Long metalakeId;
+  private Long catalogId;
+  private Long schemaId;
+  private String auditInfo;
+  private Integer currentVersion;
+  private Integer lastVersion;
+  private Long deletedAt;
+  private SemanticModelVersionInfoPO semanticModelVersionInfoPO;
+
+  /** Creates an empty persistent object for MyBatis. */
+  public SemanticModelPO() {}
+
+  /** A Lombok builder for {@link SemanticModelPO}. */
+  public static class SemanticModelPOBuilder {
+    // Lombok generates the builder methods.
+  }
+
+  @lombok.Builder(setterPrefix = "with")
+  private SemanticModelPO(
+      Long semanticModelId,
+      String semanticModelName,
+      Long metalakeId,
+      Long catalogId,
+      Long schemaId,
+      String auditInfo,
+      Integer currentVersion,
+      Integer lastVersion,
+      Long deletedAt,
+      SemanticModelVersionInfoPO semanticModelVersionInfoPO) {
+    Preconditions.checkArgument(semanticModelId != null, "Semantic Model id is required");
+    Preconditions.checkArgument(semanticModelName != null, "Semantic Model name is required");
+    Preconditions.checkArgument(metalakeId != null, "Metalake id is required");
+    Preconditions.checkArgument(catalogId != null, "Catalog id is required");
+    Preconditions.checkArgument(schemaId != null, "Schema id is required");
+    Preconditions.checkArgument(auditInfo != null, "Audit info is required");
+    Preconditions.checkArgument(currentVersion != null, "Current version is required");
+    Preconditions.checkArgument(lastVersion != null, "Last version is required");
+    Preconditions.checkArgument(deletedAt != null, "Deleted at is required");
+
+    this.semanticModelId = semanticModelId;
+    this.semanticModelName = semanticModelName;
+    this.metalakeId = metalakeId;
+    this.catalogId = catalogId;
+    this.schemaId = schemaId;
+    this.auditInfo = auditInfo;
+    this.currentVersion = currentVersion;
+    this.lastVersion = lastVersion;
+    this.deletedAt = deletedAt;
+    this.semanticModelVersionInfoPO = semanticModelVersionInfoPO;
+  }
+
+  /**
+   * Converts a persistent object and its current version snapshot to a Semantic Model entity.
+   *
+   * @param semanticModelPO The persistent object to convert.
+   * @param namespace The Semantic Model namespace.
+   * @return The converted Semantic Model entity.
+   */
+  public static SemanticModelEntity fromSemanticModelPO(

Review Comment:
   **reuse**: PO-to-entity and entity-to-PO conversion logic for Semantic Model is implemented as static methods directly on `SemanticModelPO`, instead of being added to the shared `org.apache.gravitino.storage.relational.utils.POConverters` class where every other entity's equivalent conversion logic lives (`fromModelPO`, `fromPolicyPO`, `initializePolicyPOWithVersion`, etc.).
   
   This PR forks a second, per-entity location for conversion logic that the rest of the module centralizes in `POConverters.java`. A future maintainer looking for "how does entity X convert to/from its PO" will find every other type in `POConverters` except Semantic Model, making the codebase harder to navigate and increasing the chance that a future shared fix to conversion logic (e.g. a properties-map deserialization bugfix) misses this one entity because it isn't in the usual place.



##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetaService.java:
##########
@@ -0,0 +1,226 @@
+/*
+ * 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.storage.relational.service;
+
+import static org.apache.gravitino.metrics.source.MetricsSource.GRAVITINO_RELATIONAL_STORE_METRIC_NAME;
+import static org.apache.gravitino.storage.relational.po.SemanticModelPO.fromSemanticModelPO;
+import static org.apache.gravitino.storage.relational.po.SemanticModelPO.initializeSemanticModelPO;
+
+import com.google.common.base.Preconditions;
+import java.io.IOException;
+import java.util.Locale;
+import java.util.concurrent.atomic.AtomicReference;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.meta.SemanticModelEntity;
+import org.apache.gravitino.metrics.Monitored;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelVersionInfoMapper;
+import org.apache.gravitino.storage.relational.po.SemanticModelPO;
+import org.apache.gravitino.storage.relational.po.SemanticModelVersionInfoPO;
+import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.gravitino.utils.NameIdentifierUtil;
+
+/** Provides relational create and load operations for Semantic Model metadata. */
+public class SemanticModelMetaService {
+
+  private static final SemanticModelMetaService INSTANCE = new SemanticModelMetaService();
+
+  private final BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> ops;
+
+  /** Returns the singleton Semantic Model metadata service. */
+  public static SemanticModelMetaService getInstance() {
+    return INSTANCE;
+  }
+
+  private SemanticModelMetaService() {
+    this.ops = new HierarchicalConversionPOStorageOps<>(new SemanticModelPOStorageOps());
+  }
+
+  /**
+   * Resolves a Semantic Model stable ID by schema ID and name.
+   *
+   * @param schemaId The parent schema ID.
+   * @param semanticModelName The Semantic Model name.
+   * @return The stable Semantic Model ID.
+   * @throws NoSuchEntityException If the Semantic Model does not exist.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "getSemanticModelIdBySchemaIdAndName")
+  public Long getSemanticModelIdBySchemaIdAndName(long schemaId, String semanticModelName) {
+    Long semanticModelId =
+        SessionUtils.getWithoutCommit(
+            SemanticModelMetaMapper.class,
+            mapper -> mapper.selectSemanticModelIdBySchemaIdAndName(schemaId, semanticModelName));
+    if (semanticModelId == null) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.SEMANTIC_MODEL.name().toLowerCase(Locale.ROOT),
+          semanticModelName);
+    }
+    return semanticModelId;
+  }
+
+  /**
+   * Loads the current Semantic Model by identifier.
+   *
+   * @param identifier The Semantic Model identifier.
+   * @return The current Semantic Model entity.
+   * @throws NoSuchEntityException If the Semantic Model does not exist.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "getSemanticModelByIdentifier")
+  public SemanticModelEntity getSemanticModelByIdentifier(NameIdentifier identifier) {
+    SemanticModelPO semanticModelPO = getSemanticModelPOByIdentifier(identifier);
+    return fromSemanticModelPO(semanticModelPO, identifier.namespace());
+  }
+
+  /**
+   * Inserts a Semantic Model identity and its version-one snapshot atomically.
+   *
+   * @param semanticModelEntity The Semantic Model entity.
+   * @param overwrite Whether to overwrite rows for the same stable ID or natural key.
+   * @throws IOException If relational persistence fails.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "insertSemanticModel")
+  public void insertSemanticModel(SemanticModelEntity semanticModelEntity, boolean overwrite)
+      throws IOException {
+    NameIdentifierUtil.checkSemanticModel(semanticModelEntity.nameIdentifier());
+    try {
+      SemanticModelPO po =
+          initializeSemanticModelPO(semanticModelEntity, SemanticModelPO.builder());
+      AtomicReference<SemanticModelPO> persistedPO = new AtomicReference<>();
+      AtomicReference<SemanticModelVersionInfoPO> persistedVersionInfoPO =
+          new AtomicReference<>(po.getSemanticModelVersionInfoPO());
+      SessionUtils.doMultipleWithCommit(
+          () ->
+              SchemaMetaService.getInstance()
+                  .lockSchemaForEntityWrite(
+                      semanticModelEntity.nameIdentifier(),
+                      po.getSchemaId(),
+                      po.getCatalogId(),
+                      po.getMetalakeId()),
+          () ->
+              SessionUtils.doWithoutCommit(
+                  SemanticModelMetaMapper.class,
+                  mapper -> {
+                    if (overwrite) {
+                      Long persistedId =
+                          mapper.selectSemanticModelIdBySchemaIdAndName(
+                              po.getSchemaId(), po.getSemanticModelName());
+                      SemanticModelPO existingPO =
+                          mapper.selectSemanticModelMetaByIdForUpdate(
+                              persistedId == null ? po.getSemanticModelId() : persistedId);
+                      persistedPO.set(existingPO);
+                      if (existingPO != null) {
+                        persistedVersionInfoPO.set(
+                            versionInfoForOverwrite(
+                                po.getSemanticModelVersionInfoPO(), existingPO));
+                      }
+                    }
+                    ops.insertPO(
+                        mapper,
+                        persistedPO.get() == null
+                            ? po
+                            : identityForOverwrite(po, persistedPO.get()),
+                        overwrite);
+                  }),
+          () ->
+              SessionUtils.doWithoutCommit(
+                  SemanticModelVersionInfoMapper.class,
+                  mapper -> {
+                    if (overwrite) {
+                      mapper.insertSemanticModelVersionInfoOnDuplicateKeyUpdate(
+                          persistedVersionInfoPO.get());
+                    } else {
+                      mapper.insertSemanticModelVersionInfo(po.getSemanticModelVersionInfoPO());
+                    }
+                  }));
+    } catch (RuntimeException re) {
+      ExceptionUtils.checkSQLException(
+          re, Entity.EntityType.SEMANTIC_MODEL, semanticModelEntity.nameIdentifier().toString());
+      throw re;
+    }
+  }
+
+  /** Returns the persistent-object operations used by this service. */
+  public BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> ops() {
+    return ops;
+  }
+
+  private static SemanticModelPO identityForOverwrite(
+      SemanticModelPO source, SemanticModelPO persistedPO) {
+    return SemanticModelPO.builder()
+        .withSemanticModelId(persistedPO.getSemanticModelId())
+        .withSemanticModelName(source.getSemanticModelName())
+        .withMetalakeId(source.getMetalakeId())
+        .withCatalogId(source.getCatalogId())
+        .withSchemaId(source.getSchemaId())
+        .withAuditInfo(source.getAuditInfo())
+        .withCurrentVersion(source.getCurrentVersion())

Review Comment:
   **correctness (currently masked)**: `identityForOverwrite` builds the overwritten identity row's `currentVersion`/`lastVersion` from `source` (the freshly-built `po`, always version 1) instead of from `persistedPO` (the actual locked existing row) — inconsistent with the sibling `versionInfoForOverwrite`, which correctly uses `persistedPO.getCurrentVersion() + 1`.
   
   Currently masked: `insertSemanticModelMetaOnDuplicateKeyUpdate`'s SQL (`SemanticModelMetaBaseSQLProvider.java:178-179`) hardcodes `current_version = current_version + 1` / `last_version = current_version + 1` in the `ON DUPLICATE KEY UPDATE` clause, ignoring the bound Java values entirely, so the wrong value never reaches the DB today. But if a future contributor "simplifies" that SQL to trust the bound `#{semanticModelMeta.currentVersion}` parameter instead (a natural-looking cleanup since the parameter appears to already carry the right value), every overwrite would silently reset `semantic_model_meta.current_version`/`last_version` to 1 while `semantic_model_version_info` keeps accumulating rows at version 2, 3, 4... Reads join on `smm.current_version = smvi.version`, so they'd always resolve to the version-1 snapshot, silently hiding every subsequent overwrite. No existing unit test asserts `identityForOverwrite`'s version fields directly.



-- 
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] [#12600] feat(store): Add Semantic Model create and load persistence [gravitino]

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

   @jerryshao comments resolved, please help review again, thanks!


-- 
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] [#12600] feat(store): Add Semantic Model create and load persistence [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetaService.java:
##########
@@ -0,0 +1,161 @@
+/*
+ * 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.storage.relational.service;
+
+import static org.apache.gravitino.metrics.source.MetricsSource.GRAVITINO_RELATIONAL_STORE_METRIC_NAME;
+import static org.apache.gravitino.storage.relational.po.SemanticModelPO.fromSemanticModelPO;
+import static org.apache.gravitino.storage.relational.po.SemanticModelPO.initializeSemanticModelPO;
+
+import java.io.IOException;
+import java.util.Locale;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.meta.SemanticModelEntity;
+import org.apache.gravitino.metrics.Monitored;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelVersionInfoMapper;
+import org.apache.gravitino.storage.relational.po.SemanticModelPO;
+import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.gravitino.utils.NameIdentifierUtil;
+
+/** Provides relational create and load operations for Semantic Model metadata. */
+public class SemanticModelMetaService {
+
+  private static final SemanticModelMetaService INSTANCE = new SemanticModelMetaService();
+
+  private final BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> ops;
+
+  /** Returns the singleton Semantic Model metadata service. */
+  public static SemanticModelMetaService getInstance() {
+    return INSTANCE;
+  }
+
+  private SemanticModelMetaService() {
+    this.ops = new HierarchicalConversionPOStorageOps<>(new SemanticModelPOStorageOps());
+  }
+
+  /**
+   * Resolves a Semantic Model stable ID by schema ID and name.
+   *
+   * @param schemaId The parent schema ID.
+   * @param semanticModelName The Semantic Model name.
+   * @return The stable Semantic Model ID.
+   * @throws NoSuchEntityException If the Semantic Model does not exist.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "getSemanticModelIdBySchemaIdAndName")
+  public Long getSemanticModelIdBySchemaIdAndName(long schemaId, String semanticModelName) {
+    Long semanticModelId =
+        SessionUtils.getWithoutCommit(
+            SemanticModelMetaMapper.class,
+            mapper -> mapper.selectSemanticModelIdBySchemaIdAndName(schemaId, semanticModelName));
+    if (semanticModelId == null) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.SEMANTIC_MODEL.name().toLowerCase(Locale.ROOT),
+          semanticModelName);
+    }
+    return semanticModelId;
+  }
+
+  /**
+   * Loads the current Semantic Model by identifier.
+   *
+   * @param identifier The Semantic Model identifier.
+   * @return The current Semantic Model entity.
+   * @throws NoSuchEntityException If the Semantic Model does not exist.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "getSemanticModelByIdentifier")
+  public SemanticModelEntity getSemanticModelByIdentifier(NameIdentifier identifier) {
+    SemanticModelPO semanticModelPO = getSemanticModelPOByIdentifier(identifier);
+    return fromSemanticModelPO(semanticModelPO, identifier.namespace());
+  }
+
+  /**
+   * Inserts a Semantic Model identity and its version-one snapshot atomically.
+   *
+   * @param semanticModelEntity The Semantic Model entity.
+   * @param overwrite Whether to overwrite rows for the same stable ID.
+   * @throws IOException If relational persistence fails.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "insertSemanticModel")
+  public void insertSemanticModel(SemanticModelEntity semanticModelEntity, boolean overwrite)
+      throws IOException {
+    NameIdentifierUtil.checkSemanticModel(semanticModelEntity.nameIdentifier());
+    try {
+      SemanticModelPO po =
+          initializeSemanticModelPO(semanticModelEntity, SemanticModelPO.builder());
+      SessionUtils.doMultipleWithCommit(
+          () ->
+              SchemaMetaService.getInstance()
+                  .lockSchemaForEntityWrite(
+                      semanticModelEntity.nameIdentifier(),
+                      po.getSchemaId(),
+                      po.getCatalogId(),
+                      po.getMetalakeId()),
+          () ->
+              SessionUtils.doWithoutCommit(
+                  SemanticModelMetaMapper.class, mapper -> ops.insertPO(mapper, po, overwrite)),
+          () ->
+              SessionUtils.doWithoutCommit(
+                  SemanticModelVersionInfoMapper.class,
+                  mapper -> {
+                    if (overwrite) {
+                      mapper.insertSemanticModelVersionInfoOnDuplicateKeyUpdate(

Review Comment:
   This was not implemented when the comment was posted. It is fixed in [`3be4e12521`](https://github.com/apache/gravitino/commit/3be4e1252108629d40dc090e45fff4899d2e51ac). Replace now locks the persisted Semantic Model identity, advances `current_version` and `last_version` from N to N + 1, and writes snapshot N + 1 in the same transaction. Previous snapshots remain retained. The same-ID, natural-key, and concurrent overwrite cases pass on H2, MySQL, and PostgreSQL.



##########
core/src/test/java/org/apache/gravitino/storage/relational/TestSemanticModelJDBCBackend.java:
##########
@@ -0,0 +1,264 @@
+/*
+ * 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.storage.relational;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import com.google.common.collect.ImmutableMap;
+import java.io.IOException;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.List;
+import java.util.Map;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.EntityAlreadyExistsException;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.meta.SemanticModelEntity;
+import org.apache.gravitino.semantic.AIContext;
+import org.apache.gravitino.semantic.AIContextObject;
+import org.apache.gravitino.semantic.CustomExtension;
+import org.apache.gravitino.semantic.DataType;
+import org.apache.gravitino.semantic.Dataset;
+import org.apache.gravitino.semantic.DialectExpression;
+import org.apache.gravitino.semantic.Dimension;
+import org.apache.gravitino.semantic.Expression;
+import org.apache.gravitino.semantic.Field;
+import org.apache.gravitino.semantic.Metric;
+import org.apache.gravitino.semantic.Relationship;
+import org.apache.gravitino.semantic.SemanticModelDefinition;
+import org.apache.gravitino.storage.RandomIdGenerator;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelVersionInfoMapper;
+import org.apache.gravitino.storage.relational.po.SemanticModelPO;
+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.gravitino.utils.NamespaceUtil;
+import org.apache.ibatis.session.SqlSession;
+import org.junit.jupiter.api.TestTemplate;
+
+/** Tests Semantic Model create and load persistence through {@link JDBCBackend}. */
+public class TestSemanticModelJDBCBackend extends TestJDBCBackend {
+
+  @TestTemplate
+  public void testCreateAndLoadRoundTrip() throws IOException {
+    Namespace namespace = createParents("round_trip");
+    SemanticModelEntity absent =
+        semanticModel(
+            RandomIdGenerator.INSTANCE.nextId(),
+            namespace,
+            "absent_optional_model",
+            false,
+            ImmutableMap.of("domain", "sales"));
+    SemanticModelEntity empty =
+        semanticModel(
+            RandomIdGenerator.INSTANCE.nextId(),
+            namespace,
+            "empty_optional_model",
+            true,
+            ImmutableMap.of());
+
+    backend.insert(absent, false);
+    backend.insert(empty, false);
+
+    SemanticModelEntity loadedAbsent =
+        backend.get(absent.nameIdentifier(), Entity.EntityType.SEMANTIC_MODEL);
+    SemanticModelEntity loadedEmpty =
+        backend.get(empty.nameIdentifier(), Entity.EntityType.SEMANTIC_MODEL);
+
+    assertEquals(absent, loadedAbsent);
+    assertEquals(empty, loadedEmpty);
+    assertNull(loadedAbsent.definition().relationships());
+    assertNull(loadedAbsent.definition().metrics());
+    assertEquals(0, loadedEmpty.definition().relationships().length);
+    assertEquals(0, loadedEmpty.definition().metrics().length);
+    assertTrue(loadedEmpty.properties().isEmpty());
+    assertEquals(
+        new BigDecimal("1.50"),
+        loadedAbsent.definition().aiContext().object().additionalProperties().get("threshold"));
+    assertNull(loadedAbsent.definition().aiContext().object().examples());
+    assertEquals(0, loadedAbsent.definition().aiContext().object().synonyms().length);
+  }
+
+  @TestTemplate
+  public void testDuplicateAndMissingEntities() throws IOException {
+    Namespace namespace = createParents("duplicate");
+    SemanticModelEntity original =
+        semanticModel(
+            RandomIdGenerator.INSTANCE.nextId(),
+            namespace,
+            "sales_model",
+            false,
+            ImmutableMap.of("owner", "analytics"));
+    backend.insert(original, false);
+
+    SemanticModelEntity duplicate =
+        semanticModel(
+            RandomIdGenerator.INSTANCE.nextId(),
+            namespace,
+            original.name(),
+            true,
+            ImmutableMap.of());
+    assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(duplicate, false));
+    assertEquals(
+        original, backend.get(original.nameIdentifier(), Entity.EntityType.SEMANTIC_MODEL));
+
+    NameIdentifier missingModel = NameIdentifier.of(namespace, "missing_model");
+    assertThrows(
+        NoSuchEntityException.class,
+        () -> backend.get(missingModel, Entity.EntityType.SEMANTIC_MODEL));
+
+    String suffix = Long.toUnsignedString(RandomIdGenerator.INSTANCE.nextId());
+    String metalakeName = "missing_parent_metalake_" + suffix;
+    String catalogName = "missing_parent_catalog_" + suffix;
+    createAndInsertMakeLake(metalakeName);
+    createAndInsertCatalog(metalakeName, catalogName);
+    Namespace missingParentNamespace =
+        NamespaceUtil.ofSemanticModel(metalakeName, catalogName, "missing_schema");
+    SemanticModelEntity missingParent =
+        semanticModel(
+            RandomIdGenerator.INSTANCE.nextId(),
+            missingParentNamespace,
+            "orphan_model",
+            false,
+            ImmutableMap.of());
+
+    assertThrows(NoSuchEntityException.class, () -> backend.insert(missingParent, false));
+    assertEquals(0, countRows(SemanticModelMetaMapper.TABLE_NAME, missingParent.id()));
+    assertEquals(0, countRows(SemanticModelVersionInfoMapper.TABLE_NAME, missingParent.id()));
+  }
+
+  @TestTemplate
+  public void testCreateRollsBackIdentityWhenSnapshotInsertFails() throws IOException {
+    Namespace namespace = createParents("transaction");
+    SemanticModelEntity semanticModel =
+        semanticModel(
+            RandomIdGenerator.INSTANCE.nextId(),
+            namespace,
+            "transaction_model",
+            false,
+            ImmutableMap.of("domain", "finance"));
+    SemanticModelPO po =
+        SemanticModelPO.initializeSemanticModelPO(semanticModel, SemanticModelPO.builder());
+    SessionUtils.doWithCommit(
+        SemanticModelVersionInfoMapper.class,
+        mapper -> mapper.insertSemanticModelVersionInfo(po.getSemanticModelVersionInfoPO()));
+
+    assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(semanticModel, false));
+    assertEquals(0, countRows(SemanticModelMetaMapper.TABLE_NAME, semanticModel.id()));
+    assertEquals(1, countRows(SemanticModelVersionInfoMapper.TABLE_NAME, semanticModel.id()));
+  }

Review Comment:
   Implemented in [`3be4e12521`](https://github.com/apache/gravitino/commit/3be4e1252108629d40dc090e45fff4899d2e51ac).
   
   - Added same-ID and natural-key overwrite coverage, including monotonic version advancement, retained snapshots, and orphan-snapshot prevention.
   - Covered both read routes, missing parent/model cases, and the Semantic Model branch of `RelationalEntityStoreIdResolver`.
   - Added focused SerDe coverage for fully populated definitions, both AI context forms, all `DataType` values, multiple dialects, nested additional properties, null-vs-empty arrays, and a golden JSON fixture.
   - Added duplicate-create, overwrite-race, change-log atomicity, and create-vs-schema-drop coverage.
   
   Validation passed with 24 persistence and concurrency tests across H2, MySQL, and PostgreSQL, plus 3 focused SerDe tests.



-- 
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] [#12600] feat(store): Add Semantic Model create and load persistence [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelDefinitionSerDe.java:
##########
@@ -0,0 +1,265 @@
+/*
+ * 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.storage.relational.po;
+
+import com.fasterxml.jackson.annotation.JsonAutoDetect;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.PropertyAccessor;
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.JsonToken;
+import com.fasterxml.jackson.databind.DeserializationContext;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonDeserializer;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.JsonSerializer;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.PropertyNamingStrategies;
+import com.fasterxml.jackson.databind.SerializerProvider;
+import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
+import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
+import com.fasterxml.jackson.databind.cfg.JsonNodeFeature;
+import com.fasterxml.jackson.databind.module.SimpleModule;
+import com.google.common.base.CaseFormat;
+import java.io.IOException;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.json.JsonUtils;
+import org.apache.gravitino.semantic.AIContext;
+import org.apache.gravitino.semantic.AIContextObject;
+import org.apache.gravitino.semantic.CustomExtension;
+import org.apache.gravitino.semantic.DataType;
+import org.apache.gravitino.semantic.Dataset;
+import org.apache.gravitino.semantic.DialectExpression;
+import org.apache.gravitino.semantic.Dimension;
+import org.apache.gravitino.semantic.Expression;
+import org.apache.gravitino.semantic.Field;
+import org.apache.gravitino.semantic.Metric;
+import org.apache.gravitino.semantic.Relationship;
+import org.apache.gravitino.semantic.SemanticModelDefinition;
+
+/**
+ * Serializes immutable Semantic Model API values for relational storage without depending on REST
+ * DTOs.
+ */
+final class SemanticModelDefinitionSerDe {
+
+  private static final ObjectMapper MAPPER = createMapper();
+
+  private SemanticModelDefinitionSerDe() {}
+
+  static String serialize(SemanticModelDefinition definition) throws JsonProcessingException {
+    return MAPPER.writeValueAsString(definition);
+  }
+
+  static SemanticModelDefinition deserialize(String json) throws JsonProcessingException {
+    return MAPPER.readValue(json, SemanticModelDefinition.class);
+  }
+
+  private static ObjectMapper createMapper() {
+    SimpleModule module =
+        new SimpleModule()
+            .addSerializer(AIContext.class, new AIContextSerializer())
+            .addDeserializer(AIContext.class, new AIContextDeserializer())
+            .addSerializer(DataType.class, new DataTypeSerializer())
+            .addDeserializer(DataType.class, new DataTypeDeserializer())
+            .addSerializer(NameIdentifier.class, new JsonUtils.NameIdentifierSerializer())
+            .addDeserializer(NameIdentifier.class, new JsonUtils.NameIdentifierDeserializer());
+
+    ObjectMapper mapper =
+        JsonUtils.anyFieldMapper()
+            .copy()
+            .setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE)
+            .setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE)
+            .setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE)
+            .setDefaultPropertyInclusion(
+                JsonInclude.Value.construct(
+                    JsonInclude.Include.NON_NULL, JsonInclude.Include.ALWAYS))
+            .configure(JsonNodeFeature.STRIP_TRAILING_BIGDECIMAL_ZEROES, false)
+            .enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)
+            .enable(DeserializationFeature.USE_BIG_INTEGER_FOR_INTS)
+            .registerModule(module);
+    addBuilderMixIns(
+        mapper,
+        SemanticModelDefinition.class,
+        SemanticModelDefinitionMixIn.class,
+        SemanticModelDefinition.Builder.class);
+    addBuilderMixIns(mapper, Dataset.class, DatasetMixIn.class, Dataset.Builder.class);
+    addBuilderMixIns(
+        mapper, Relationship.class, RelationshipMixIn.class, Relationship.Builder.class);
+    addBuilderMixIns(mapper, Metric.class, MetricMixIn.class, Metric.Builder.class);
+    addBuilderMixIns(mapper, Field.class, FieldMixIn.class, Field.Builder.class);
+    addBuilderMixIns(mapper, Expression.class, ExpressionMixIn.class, Expression.Builder.class);
+    addBuilderMixIns(
+        mapper,
+        DialectExpression.class,
+        DialectExpressionMixIn.class,
+        DialectExpression.Builder.class);
+    addBuilderMixIns(mapper, Dimension.class, DimensionMixIn.class, Dimension.Builder.class);
+    addBuilderMixIns(
+        mapper, CustomExtension.class, CustomExtensionMixIn.class, CustomExtension.Builder.class);
+    return mapper;
+  }
+
+  private static void addBuilderMixIns(
+      ObjectMapper mapper, Class<?> valueClass, Class<?> mixInClass, Class<?> builderClass) {
+    mapper.addMixIn(valueClass, mixInClass);
+    mapper.addMixIn(builderClass, BuilderMixIn.class);
+  }
+
+  @JsonPOJOBuilder(withPrefix = "with")
+  private abstract static class BuilderMixIn {}
+
+  @JsonDeserialize(builder = SemanticModelDefinition.Builder.class)
+  private abstract static class SemanticModelDefinitionMixIn {}
+
+  @JsonDeserialize(builder = Dataset.Builder.class)
+  private abstract static class DatasetMixIn {}
+
+  @JsonDeserialize(builder = Relationship.Builder.class)
+  private abstract static class RelationshipMixIn {}
+
+  @JsonDeserialize(builder = Metric.Builder.class)
+  private abstract static class MetricMixIn {}
+
+  @JsonDeserialize(builder = Field.Builder.class)
+  private abstract static class FieldMixIn {}
+
+  @JsonDeserialize(builder = Expression.Builder.class)
+  private abstract static class ExpressionMixIn {}
+
+  @JsonDeserialize(builder = DialectExpression.Builder.class)
+  private abstract static class DialectExpressionMixIn {}
+
+  @JsonDeserialize(builder = Dimension.Builder.class)
+  private abstract static class DimensionMixIn {}
+
+  @JsonDeserialize(builder = CustomExtension.Builder.class)
+  private abstract static class CustomExtensionMixIn {}
+
+  private static final class AIContextSerializer extends JsonSerializer<AIContext> {

Review Comment:
   Can all these serializer and deserializer be used For XXXDTOs? I think it is better to define these JSON serde there, not in the storage module.



-- 
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] [#12600] feat(store): Add Semantic Model create and load persistence [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetaService.java:
##########
@@ -0,0 +1,242 @@
+/*
+ * 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.storage.relational.service;
+
+import static org.apache.gravitino.metrics.source.MetricsSource.GRAVITINO_RELATIONAL_STORE_METRIC_NAME;
+import static org.apache.gravitino.storage.relational.po.SemanticModelPO.fromSemanticModelPO;
+import static org.apache.gravitino.storage.relational.po.SemanticModelPO.initializeSemanticModelPO;
+
+import com.google.common.base.Preconditions;
+import java.io.IOException;
+import java.util.Locale;
+import java.util.Objects;
+import java.util.concurrent.atomic.AtomicReference;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.meta.SemanticModelEntity;
+import org.apache.gravitino.metrics.Monitored;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelVersionInfoMapper;
+import org.apache.gravitino.storage.relational.po.SemanticModelPO;
+import org.apache.gravitino.storage.relational.po.SemanticModelVersionInfoPO;
+import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.gravitino.utils.NameIdentifierUtil;
+
+/** Provides relational create and load operations for Semantic Model metadata. */
+public class SemanticModelMetaService {
+
+  private static final SemanticModelMetaService INSTANCE = new SemanticModelMetaService();
+
+  private final BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> ops;
+
+  /** Returns the singleton Semantic Model metadata service. */
+  public static SemanticModelMetaService getInstance() {
+    return INSTANCE;
+  }
+
+  private SemanticModelMetaService() {
+    this.ops = new HierarchicalConversionPOStorageOps<>(new SemanticModelPOStorageOps());
+  }
+
+  /**
+   * Resolves a Semantic Model stable ID by schema ID and name.
+   *
+   * @param schemaId The parent schema ID.
+   * @param semanticModelName The Semantic Model name.
+   * @return The stable Semantic Model ID.
+   * @throws NoSuchEntityException If the Semantic Model does not exist.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "getSemanticModelIdBySchemaIdAndName")
+  public Long getSemanticModelIdBySchemaIdAndName(long schemaId, String semanticModelName) {
+    Long semanticModelId =
+        SessionUtils.getWithoutCommit(
+            SemanticModelMetaMapper.class,
+            mapper -> mapper.selectSemanticModelIdBySchemaIdAndName(schemaId, semanticModelName));
+    if (semanticModelId == null) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.SEMANTIC_MODEL.name().toLowerCase(Locale.ROOT),
+          semanticModelName);
+    }
+    return semanticModelId;
+  }
+
+  /**
+   * Loads the current Semantic Model by identifier.
+   *
+   * @param identifier The Semantic Model identifier.
+   * @return The current Semantic Model entity.
+   * @throws NoSuchEntityException If the Semantic Model does not exist.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "getSemanticModelByIdentifier")
+  public SemanticModelEntity getSemanticModelByIdentifier(NameIdentifier identifier) {
+    SemanticModelPO semanticModelPO = getSemanticModelPOByIdentifier(identifier);
+    return fromSemanticModelPO(semanticModelPO, identifier.namespace());
+  }
+
+  /**
+   * Inserts or overwrites a Semantic Model identity and its snapshot atomically.
+   *
+   * @param semanticModelEntity The Semantic Model entity.
+   * @param overwrite Whether to overwrite rows for the same stable ID or natural key.
+   * @throws IOException If relational persistence fails.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "insertSemanticModel")
+  public void insertSemanticModel(SemanticModelEntity semanticModelEntity, boolean overwrite)
+      throws IOException {
+    NameIdentifierUtil.checkSemanticModel(semanticModelEntity.nameIdentifier());
+    try {
+      SemanticModelPO po =
+          initializeSemanticModelPO(semanticModelEntity, SemanticModelPO.builder());
+      AtomicReference<SemanticModelPO> persistedPO = new AtomicReference<>(po);
+      SchemaMetaService.getInstance()
+          .doWithSchemaWriteLock(
+              semanticModelEntity.nameIdentifier(),
+              po.getSchemaId(),
+              po.getCatalogId(),
+              po.getMetalakeId(),
+              () ->
+                  SessionUtils.doWithoutCommit(
+                      SemanticModelMetaMapper.class,
+                      mapper -> {
+                        SemanticModelPO storedPO =
+                            overwrite
+                                ? mapper.selectSemanticModelMetaBySchemaIdAndNameForUpdate(
+                                    po.getSchemaId(), po.getSemanticModelName())
+                                : null;
+                        if (storedPO == null) {
+                          // Keep missing-row imports strict. A losing concurrent insert must not
+                          // overwrite a persisted identity with a different ID.
+                          ops.insertPO(mapper, po, false);
+                          return;
+                        }
+
+                        SemanticModelPO replacementPO = semanticModelForOverwrite(po, storedPO);
+                        Integer updated = mapper.updateSemanticModelMeta(replacementPO, storedPO);
+                        if (updated == null || updated != 1) {
+                          throw semanticModelWriteFailure(
+                              semanticModelEntity.nameIdentifier(), storedPO);
+                        }
+                        persistedPO.set(replacementPO);
+                      }),
+              () ->
+                  SessionUtils.doWithoutCommit(
+                      SemanticModelVersionInfoMapper.class,
+                      mapper ->
+                          mapper.insertSemanticModelVersionInfo(
+                              persistedPO.get().getSemanticModelVersionInfoPO())));
+    } catch (RuntimeException re) {
+      ExceptionUtils.checkSQLException(
+          re, Entity.EntityType.SEMANTIC_MODEL, semanticModelEntity.nameIdentifier().toString());
+      throw re;
+    }
+  }
+
+  /** Returns the persistent-object operations used by this service. */
+  public BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> ops() {
+    return ops;
+  }
+
+  private static SemanticModelPO semanticModelForOverwrite(
+      SemanticModelPO source, SemanticModelPO persistedPO) {
+    int previousVersion = Math.max(persistedPO.getCurrentVersion(), persistedPO.getLastVersion());
+    Preconditions.checkState(
+        previousVersion < Integer.MAX_VALUE,
+        "Semantic Model %s has exhausted the version range",
+        persistedPO.getSemanticModelId());
+    int nextVersion = previousVersion + 1;
+    return SemanticModelPO.builder()
+        .withSemanticModelId(persistedPO.getSemanticModelId())
+        .withSemanticModelName(source.getSemanticModelName())
+        .withMetalakeId(persistedPO.getMetalakeId())
+        .withCatalogId(persistedPO.getCatalogId())
+        .withSchemaId(persistedPO.getSchemaId())
+        .withAuditInfo(source.getAuditInfo())
+        .withCurrentVersion(nextVersion)
+        .withLastVersion(nextVersion)
+        .withDeletedAt(source.getDeletedAt())
+        .withSemanticModelVersionInfoPO(
+            versionInfoForOverwrite(
+                source.getSemanticModelVersionInfoPO(), persistedPO, nextVersion))
+        .build();
+  }
+
+  private static SemanticModelVersionInfoPO versionInfoForOverwrite(
+      SemanticModelVersionInfoPO source, SemanticModelPO persistedPO, int nextVersion) {
+    return SemanticModelVersionInfoPO.builder()
+        .withMetalakeId(persistedPO.getMetalakeId())
+        .withCatalogId(persistedPO.getCatalogId())
+        .withSchemaId(persistedPO.getSchemaId())
+        .withSemanticModelId(persistedPO.getSemanticModelId())
+        .withVersion(nextVersion)
+        .withSemanticModelName(source.semanticModelName())
+        .withSemanticModelComment(source.semanticModelComment())
+        .withSemanticModelDefinition(source.semanticModelDefinition())
+        .withProperties(source.properties())
+        .withAuditInfo(source.auditInfo())
+        .withDeletedAt(source.deletedAt())
+        .build();
+  }
+
+  private SemanticModelPO getSemanticModelPOByIdentifier(NameIdentifier identifier) {
+    NameIdentifierUtil.checkSemanticModel(identifier);
+    SemanticModelPO semanticModelPO =
+        SessionUtils.getWithoutCommit(
+            SemanticModelMetaMapper.class,
+            mapper ->
+                POStorageReadRouting.getPO(
+                    mapper, identifier, ops, Entity.EntityType.SEMANTIC_MODEL));
+    if (semanticModelPO == null) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.SEMANTIC_MODEL.name().toLowerCase(Locale.ROOT),
+          identifier.name());
+    }
+    return semanticModelPO;
+  }
+
+  private RuntimeException semanticModelWriteFailure(
+      NameIdentifier identifier, SemanticModelPO observedSemanticModelPO) {
+    return OccWriteSupport.writeFailure(
+        identifier,
+        Entity.EntityType.SEMANTIC_MODEL,
+        () ->
+            SessionUtils.getWithoutCommit(
+                SemanticModelMetaMapper.class,
+                mapper ->
+                    mapper.selectSemanticModelMetaByIdForUpdate(
+                        observedSemanticModelPO.getSemanticModelId())),

Review Comment:
   Fixed. The by-ID lock now aliases the identity columns and no longer reuses the joined snapshot result map, matching the natural-key, View, and Function lock queries. Added coverage for the by-ID mapper path.



##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -291,22 +291,23 @@ Most alters are safe:
 | drop                                               | for Group 1 the connector call fails; for a fileset the file path is gone and access fails                                                            | yes   |
 | catalog changes                                    | already handled today by a separate cross-node signal (`CatalogChangeLogListener`), not by this cache                                                 | yes   |
 
-Five cases are **not** safe — a stale read gives a wrong answer with no error. They are in the model area, functions, or the metalake on/off flag:
+Six cases are **not** safe — a stale read gives a wrong answer with no error. They are in the model area, Semantic Models, functions, or the metalake on/off flag:
 
 | Change                                                                | Why a stale read is wrong, with no error                                                                                                                                                            |
 | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
 | model version — update / add / remove URI                             | the URI points to the model files. An old URI silently loads the **wrong model files**.                                                                                                             |
 | model version — update aliases                                        | an alias silently points to the **wrong version**.                                                                                                                                                  |
 | model — latest version (after a new version is added on another node) | "get the latest version" silently returns an **old version**.                                                                                                                                       |
+| Semantic Model — overwrite definition                                | the current version selects the definition used for semantic queries. An old version silently uses the **wrong definition**.                                                                        |

Review Comment:
   Fixed. Added the missing padding space to keep the Markdown source columns aligned.



-- 
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] [#12600] feat(store): Add Semantic Model create and load persistence [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelPOStorageOps.java:
##########
@@ -0,0 +1,81 @@
+/*
+ * 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.storage.relational.service;
+
+import java.util.Locale;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;
+import org.apache.gravitino.storage.relational.po.SemanticModelPO;
+
+/** Provides relational persistent-object operations required to create and load Semantic Models. */
+public class SemanticModelPOStorageOps
+    extends BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> {
+
+  /** Creates Semantic Model persistent-object operations. */
+  public SemanticModelPOStorageOps() {}
+
+  @Override
+  public void insertPO(
+      SemanticModelMetaMapper mapper, SemanticModelPO semanticModelPO, boolean overwrite) {
+    if (overwrite) {
+      mapper.insertSemanticModelMetaOnDuplicateKeyUpdate(semanticModelPO);
+    } else {
+      mapper.insertSemanticModelMeta(semanticModelPO);
+    }
+  }
+
+  @Override
+  public SemanticModelPO getPO(
+      SemanticModelMetaMapper mapper, Long parentId, String semanticModelName) {
+    return mapper.selectSemanticModelMetaBySchemaIdAndName(parentId, semanticModelName);
+  }
+
+  @Override
+  public SemanticModelPO getPOByFullName(
+      SemanticModelMetaMapper mapper, NameIdentifier identifier) {
+    Namespace namespace = identifier.namespace();
+    SemanticModelPO po =
+        mapper.selectSemanticModelByFullQualifiedName(
+            namespace.level(0), namespace.level(1), namespace.level(2), identifier.name());
+    if (po == null) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,

Review Comment:
   `po == null` can happen when the metalake does not exist (because the SQL uses an INNER JOIN from metalake -> catalog). Throwing `NoSuchEntityException` for `catalog` in that case is misleading and breaks expected error semantics. A concrete fix is to adjust the SQL in `selectSemanticModelByFullQualifiedName` to `LEFT JOIN` the catalog table (similar to how schema is handled) so the query still returns a row when the metalake exists but the catalog does not; then you can throw `METALAKE` vs `CATALOG` based on which ID column is null. Alternatively, perform a separate existence check for metalake before running the current query.



##########
core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelDefinitionSerDe.java:
##########
@@ -0,0 +1,263 @@
+/*
+ * 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.storage.relational.po;
+
+import com.fasterxml.jackson.annotation.JsonAutoDetect;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.PropertyAccessor;
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.JsonToken;
+import com.fasterxml.jackson.databind.DeserializationContext;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonDeserializer;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.JsonSerializer;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.PropertyNamingStrategies;
+import com.fasterxml.jackson.databind.SerializerProvider;
+import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
+import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
+import com.fasterxml.jackson.databind.cfg.JsonNodeFeature;
+import com.fasterxml.jackson.databind.module.SimpleModule;
+import com.google.common.base.CaseFormat;
+import java.io.IOException;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.json.JsonUtils;
+import org.apache.gravitino.semantic.AIContext;
+import org.apache.gravitino.semantic.AIContextObject;
+import org.apache.gravitino.semantic.CustomExtension;
+import org.apache.gravitino.semantic.DataType;
+import org.apache.gravitino.semantic.Dataset;
+import org.apache.gravitino.semantic.DialectExpression;
+import org.apache.gravitino.semantic.Dimension;
+import org.apache.gravitino.semantic.Expression;
+import org.apache.gravitino.semantic.Field;
+import org.apache.gravitino.semantic.Metric;
+import org.apache.gravitino.semantic.Relationship;
+import org.apache.gravitino.semantic.SemanticModelDefinition;
+
+/**
+ * Serializes immutable Semantic Model API values for relational storage without depending on REST
+ * DTOs.
+ */
+final class SemanticModelDefinitionSerDe {
+
+  private static final ObjectMapper MAPPER = createMapper();
+
+  private SemanticModelDefinitionSerDe() {}
+
+  static String serialize(SemanticModelDefinition definition) throws JsonProcessingException {
+    return MAPPER.writeValueAsString(definition);
+  }
+
+  static SemanticModelDefinition deserialize(String json) throws JsonProcessingException {
+    return MAPPER.readValue(json, SemanticModelDefinition.class);
+  }
+
+  private static ObjectMapper createMapper() {
+    SimpleModule module =
+        new SimpleModule()
+            .addSerializer(AIContext.class, new AIContextSerializer())
+            .addDeserializer(AIContext.class, new AIContextDeserializer())
+            .addSerializer(DataType.class, new DataTypeSerializer())
+            .addDeserializer(DataType.class, new DataTypeDeserializer())
+            .addSerializer(NameIdentifier.class, new JsonUtils.NameIdentifierSerializer())
+            .addDeserializer(NameIdentifier.class, new JsonUtils.NameIdentifierDeserializer());
+
+    ObjectMapper mapper =
+        JsonUtils.anyFieldMapper()
+            .copy()
+            .setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE)
+            .setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE)
+            .setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE)
+            .setSerializationInclusion(JsonInclude.Include.NON_NULL)
+            .configure(JsonNodeFeature.STRIP_TRAILING_BIGDECIMAL_ZEROES, false)
+            .enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)
+            .enable(DeserializationFeature.USE_BIG_INTEGER_FOR_INTS)
+            .registerModule(module);
+    addBuilderMixIns(
+        mapper,
+        SemanticModelDefinition.class,
+        SemanticModelDefinitionMixIn.class,
+        SemanticModelDefinition.Builder.class);
+    addBuilderMixIns(mapper, Dataset.class, DatasetMixIn.class, Dataset.Builder.class);
+    addBuilderMixIns(
+        mapper, Relationship.class, RelationshipMixIn.class, Relationship.Builder.class);
+    addBuilderMixIns(mapper, Metric.class, MetricMixIn.class, Metric.Builder.class);
+    addBuilderMixIns(mapper, Field.class, FieldMixIn.class, Field.Builder.class);
+    addBuilderMixIns(mapper, Expression.class, ExpressionMixIn.class, Expression.Builder.class);
+    addBuilderMixIns(
+        mapper,
+        DialectExpression.class,
+        DialectExpressionMixIn.class,
+        DialectExpression.Builder.class);
+    addBuilderMixIns(mapper, Dimension.class, DimensionMixIn.class, Dimension.Builder.class);
+    addBuilderMixIns(
+        mapper, CustomExtension.class, CustomExtensionMixIn.class, CustomExtension.Builder.class);
+    return mapper;
+  }
+
+  private static void addBuilderMixIns(
+      ObjectMapper mapper, Class<?> valueClass, Class<?> mixInClass, Class<?> builderClass) {
+    mapper.addMixIn(valueClass, mixInClass);
+    mapper.addMixIn(builderClass, BuilderMixIn.class);
+  }
+
+  @JsonPOJOBuilder(withPrefix = "with")
+  private abstract static class BuilderMixIn {}
+
+  @JsonDeserialize(builder = SemanticModelDefinition.Builder.class)
+  private abstract static class SemanticModelDefinitionMixIn {}
+
+  @JsonDeserialize(builder = Dataset.Builder.class)
+  private abstract static class DatasetMixIn {}
+
+  @JsonDeserialize(builder = Relationship.Builder.class)
+  private abstract static class RelationshipMixIn {}
+
+  @JsonDeserialize(builder = Metric.Builder.class)
+  private abstract static class MetricMixIn {}
+
+  @JsonDeserialize(builder = Field.Builder.class)
+  private abstract static class FieldMixIn {}
+
+  @JsonDeserialize(builder = Expression.Builder.class)
+  private abstract static class ExpressionMixIn {}
+
+  @JsonDeserialize(builder = DialectExpression.Builder.class)
+  private abstract static class DialectExpressionMixIn {}
+
+  @JsonDeserialize(builder = Dimension.Builder.class)
+  private abstract static class DimensionMixIn {}
+
+  @JsonDeserialize(builder = CustomExtension.Builder.class)
+  private abstract static class CustomExtensionMixIn {}
+
+  private static final class AIContextSerializer extends JsonSerializer<AIContext> {
+
+    @Override
+    public void serialize(AIContext value, JsonGenerator generator, SerializerProvider serializers)
+        throws IOException {
+      if (value.isText()) {
+        generator.writeString(value.text());
+        return;
+      }
+
+      AIContextObject object = value.object();
+      if (object == null) {
+        throw JsonMappingException.from(generator, "Structured AI context must not be null");
+      }
+      generator.writeStartObject();
+      writeOptionalField(generator, "instructions", object.instructions());
+      writeOptionalField(generator, "synonyms", object.synonyms());
+      writeOptionalField(generator, "examples", object.examples());
+      for (Map.Entry<String, Object> entry : object.additionalProperties().entrySet()) {
+        generator.writeObjectField(entry.getKey(), entry.getValue());
+      }

Review Comment:
   If `additionalProperties` contains reserved keys (`instructions`, `synonyms`, `examples`), this serializer will emit duplicate JSON fields, and the deserializer will treat them as 'standard' fields (and exclude them from `additionalProperties`), making round-trips order-dependent and potentially lossy. Filter out reserved keys during serialization (or validate and fail fast) so the JSON is unambiguous and symmetric with the deserializer.



##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelPOStorageOps.java:
##########
@@ -0,0 +1,81 @@
+/*
+ * 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.storage.relational.service;
+
+import java.util.Locale;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;
+import org.apache.gravitino.storage.relational.po.SemanticModelPO;
+
+/** Provides relational persistent-object operations required to create and load Semantic Models. */
+public class SemanticModelPOStorageOps
+    extends BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> {
+
+  /** Creates Semantic Model persistent-object operations. */
+  public SemanticModelPOStorageOps() {}
+
+  @Override
+  public void insertPO(
+      SemanticModelMetaMapper mapper, SemanticModelPO semanticModelPO, boolean overwrite) {
+    if (overwrite) {
+      mapper.insertSemanticModelMetaOnDuplicateKeyUpdate(semanticModelPO);
+    } else {
+      mapper.insertSemanticModelMeta(semanticModelPO);
+    }
+  }
+
+  @Override
+  public SemanticModelPO getPO(
+      SemanticModelMetaMapper mapper, Long parentId, String semanticModelName) {
+    return mapper.selectSemanticModelMetaBySchemaIdAndName(parentId, semanticModelName);
+  }
+
+  @Override
+  public SemanticModelPO getPOByFullName(
+      SemanticModelMetaMapper mapper, NameIdentifier identifier) {
+    Namespace namespace = identifier.namespace();
+    SemanticModelPO po =
+        mapper.selectSemanticModelByFullQualifiedName(
+            namespace.level(0), namespace.level(1), namespace.level(2), identifier.name());
+    if (po == null) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.CATALOG.name().toLowerCase(Locale.ROOT),
+          namespace.level(1));

Review Comment:
   Given the conditional behavior here (`po == null` vs `schemaId == null` vs `semanticModelId == null`), add a targeted test covering the 'missing metalake' and 'missing catalog' cases so the thrown `NoSuchEntityException` type/name are asserted. This will prevent regressions when adjusting the query/join strategy to fix the metalake-vs-catalog ambiguity.



##########
core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/SemanticModelVersionInfoPostgreSQLProvider.java:
##########
@@ -0,0 +1,41 @@
+/*
+ * 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.storage.relational.mapper.provider.postgresql;
+
+import org.apache.gravitino.storage.relational.mapper.provider.base.SemanticModelVersionInfoBaseSQLProvider;
+import org.apache.gravitino.storage.relational.po.SemanticModelVersionInfoPO;
+import org.apache.ibatis.annotations.Param;
+
+/** Provides PostgreSQL SQL for creating Semantic Model version snapshots. */
+public class SemanticModelVersionInfoPostgreSQLProvider
+    extends SemanticModelVersionInfoBaseSQLProvider {
+
+  @Override
+  public String insertSemanticModelVersionInfoOnDuplicateKeyUpdate(
+      @Param("semanticModelVersionInfo") SemanticModelVersionInfoPO versionInfoPO) {
+    return insertSemanticModelVersionInfo(versionInfoPO)
+        + " ON CONFLICT (semantic_model_id, version, deleted_at) DO UPDATE SET"
+        + " semantic_model_name = #{semanticModelVersionInfo.semanticModelName},"
+        + " semantic_model_comment = #{semanticModelVersionInfo.semanticModelComment},"
+        + " semantic_model_definition = #{semanticModelVersionInfo.semanticModelDefinition},"
+        + " properties = #{semanticModelVersionInfo.properties},"
+        + " audit_info = #{semanticModelVersionInfo.auditInfo},"
+        + " deleted_at = #{semanticModelVersionInfo.deletedAt}";

Review Comment:
   The upsert updates `deleted_at` even though it's part of the conflict target; updating conflict-key columns is unnecessary and can create unexpected behavior if `deletedAt` differs from the existing row (e.g., update may violate uniqueness against other rows). Prefer omitting `deleted_at` from the `DO UPDATE SET` list and treat it as immutable for a given (semantic_model_id, version) snapshot row.



-- 
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] [#12600] feat(store): Add Semantic Model create and load persistence [gravitino]

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

   @yuqi1129 can you please also review 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] [#12600] feat(store): Add Semantic Model create and load persistence [gravitino]

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

   > This PR *is* that delegation target. Now a repeated `put(entity, true)` grows the table without bound.
   
   Garbage collection and version retention are explicitly out of scope for #12600. They are covered by the follow-up storage lifecycle PR #12603, which adds Semantic Model version-retention cleanup, legacy hard deletion, and the corresponding `JDBCBackend` routing.
   
   This PR remains limited to create/load persistence and does not introduce a public API, REST, or client surface.


-- 
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] [#12600] feat(store): Add Semantic Model create and load persistence [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelVersionInfoPO.java:
##########
@@ -0,0 +1,91 @@
+/*
+ * 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.storage.relational.po;
+
+import com.google.common.base.Preconditions;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+import lombok.ToString;
+import lombok.experimental.Accessors;
+import org.apache.commons.lang3.StringUtils;
+
+/** The persistent object for a complete Semantic Model version snapshot. */
+@EqualsAndHashCode
+@Getter
+@ToString
+@Accessors(fluent = true)
+public class SemanticModelVersionInfoPO {
+
+  private Long id;
+  private Long metalakeId;
+  private Long catalogId;
+  private Long schemaId;
+  private Long semanticModelId;
+  private Integer version;
+  private String semanticModelName;

Review Comment:
   Thanks for raising this. I standardized the Semantic Model version fields on `Integer`, matching the existing `INT` columns across MySQL, H2, and PostgreSQL. `currentVersion`, `lastVersion`, and the snapshot `version` now use the same Java type, and the narrowing conversion has been removed.



-- 
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] [#12600] feat(store): Add Semantic Model create and load persistence [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelPOStorageOps.java:
##########
@@ -0,0 +1,81 @@
+/*
+ * 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.storage.relational.service;
+
+import java.util.Locale;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;
+import org.apache.gravitino.storage.relational.po.SemanticModelPO;
+
+/** Provides relational persistent-object operations required to create and load Semantic Models. */
+public class SemanticModelPOStorageOps
+    extends BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> {
+
+  /** Creates Semantic Model persistent-object operations. */
+  public SemanticModelPOStorageOps() {}
+
+  @Override
+  public void insertPO(
+      SemanticModelMetaMapper mapper, SemanticModelPO semanticModelPO, boolean overwrite) {
+    if (overwrite) {
+      mapper.insertSemanticModelMetaOnDuplicateKeyUpdate(semanticModelPO);
+    } else {
+      mapper.insertSemanticModelMeta(semanticModelPO);
+    }
+  }
+
+  @Override
+  public SemanticModelPO getPO(
+      SemanticModelMetaMapper mapper, Long parentId, String semanticModelName) {
+    return mapper.selectSemanticModelMetaBySchemaIdAndName(parentId, semanticModelName);
+  }
+
+  @Override
+  public SemanticModelPO getPOByFullName(
+      SemanticModelMetaMapper mapper, NameIdentifier identifier) {
+    Namespace namespace = identifier.namespace();
+    SemanticModelPO po =
+        mapper.selectSemanticModelByFullQualifiedName(
+            namespace.level(0), namespace.level(1), namespace.level(2), identifier.name());
+    if (po == null) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.CATALOG.name().toLowerCase(Locale.ROOT),
+          namespace.level(1));

Review Comment:
   The expected assertions here depend on the metalake-vs-catalog classification discussed in the [related thread](https://github.com/apache/gravitino/pull/12602#discussion_r3870624155). The current full-name and cache-enabled parent-ID lookup paths both classify a missing metalake or catalog as a missing catalog. Tests expecting distinct classifications would be inconsistent with those paths, while asserting the current ambiguous result would lock it in as a Semantic Model-specific contract. I am not adding either expectation in this PR; targeted classification tests should accompany a consistent cross-entity relational lookup 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] [#12600] feat(store): Add Semantic Model create and load persistence [gravitino]

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


-- 
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] [#12600] feat(store): Add Semantic Model create and load persistence [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelPO.java:
##########
@@ -0,0 +1,225 @@
+/*
+ * 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.storage.relational.po;
+
+import static org.apache.gravitino.storage.relational.utils.POConverters.DEFAULT_DELETED_AT;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.base.Preconditions;
+import java.util.Collections;
+import java.util.Map;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+import lombok.ToString;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.json.JsonUtils;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.NamespacedEntityId;
+import org.apache.gravitino.meta.SemanticModelEntity;
+import org.apache.gravitino.semantic.SemanticModelDefinition;
+import org.apache.gravitino.storage.relational.service.EntityIdService;
+
+/** The persistent object for Semantic Model identity metadata and its current version snapshot. */
+@Getter
+@EqualsAndHashCode(exclude = "semanticModelVersionInfoPO")
+@ToString
+public class SemanticModelPO {
+
+  /** The initial version allocated to a newly created Semantic Model. */
+  public static final Integer INITIAL_VERSION = 1;
+
+  private Long semanticModelId;
+  private String semanticModelName;
+  private Long metalakeId;
+  private Long catalogId;
+  private Long schemaId;
+  private String auditInfo;
+  private Integer currentVersion;
+  private Integer lastVersion;
+  private Long deletedAt;
+  private SemanticModelVersionInfoPO semanticModelVersionInfoPO;
+
+  /** Creates an empty persistent object for MyBatis. */
+  public SemanticModelPO() {}
+
+  /** A Lombok builder for {@link SemanticModelPO}. */
+  public static class SemanticModelPOBuilder {
+    // Lombok generates the builder methods.
+  }
+
+  @lombok.Builder(setterPrefix = "with")
+  private SemanticModelPO(
+      Long semanticModelId,
+      String semanticModelName,
+      Long metalakeId,
+      Long catalogId,
+      Long schemaId,
+      String auditInfo,
+      Integer currentVersion,
+      Integer lastVersion,
+      Long deletedAt,
+      SemanticModelVersionInfoPO semanticModelVersionInfoPO) {
+    Preconditions.checkArgument(semanticModelId != null, "Semantic Model id is required");
+    Preconditions.checkArgument(semanticModelName != null, "Semantic Model name is required");
+    Preconditions.checkArgument(metalakeId != null, "Metalake id is required");
+    Preconditions.checkArgument(catalogId != null, "Catalog id is required");
+    Preconditions.checkArgument(schemaId != null, "Schema id is required");
+    Preconditions.checkArgument(auditInfo != null, "Audit info is required");
+    Preconditions.checkArgument(currentVersion != null, "Current version is required");
+    Preconditions.checkArgument(lastVersion != null, "Last version is required");
+    Preconditions.checkArgument(deletedAt != null, "Deleted at is required");
+
+    this.semanticModelId = semanticModelId;
+    this.semanticModelName = semanticModelName;
+    this.metalakeId = metalakeId;
+    this.catalogId = catalogId;
+    this.schemaId = schemaId;
+    this.auditInfo = auditInfo;
+    this.currentVersion = currentVersion;
+    this.lastVersion = lastVersion;
+    this.deletedAt = deletedAt;
+    this.semanticModelVersionInfoPO = semanticModelVersionInfoPO;
+  }
+
+  /**
+   * Converts a persistent object and its current version snapshot to a Semantic Model entity.
+   *
+   * @param semanticModelPO The persistent object to convert.
+   * @param namespace The Semantic Model namespace.
+   * @return The converted Semantic Model entity.
+   */
+  public static SemanticModelEntity fromSemanticModelPO(
+      SemanticModelPO semanticModelPO, Namespace namespace) {
+    try {
+      SemanticModelVersionInfoPO versionPO = semanticModelPO.getSemanticModelVersionInfoPO();
+      SemanticModelDefinition definition =
+          SemanticModelDefinitionSerDe.deserialize(versionPO.semanticModelDefinition());
+      Map<String, String> properties =
+          versionPO.properties() == null
+              ? Collections.emptyMap()
+              : JsonUtils.anyFieldMapper()

Review Comment:
   This is intentional and is not unique to Semantic Model; `ViewPO#fromViewPO` uses the same explicit `MapType`.
   
   `readValue(..., Map.class)` deserializes values as generic `Object`s under type erasure, while the explicit map type preserves the `Map<String, String>` contract at the JSON boundary. Both behave the same for valid string-only properties, but the typed form avoids silently carrying non-string values in a map declared as `Map<String, String>`, so I prefer to keep 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] [#12600] feat(store): Add Semantic Model create and load persistence [gravitino]

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

   Verdict: blocking issues
   
   java\n      case SEMANTIC_MODEL:\n        // TODO: Delegate to SemanticModelMetaService when relational persistence is added.\n        return 0;\n```\n\nThis PR *is* that delegation target: before it, no snapshot rows existed, so the stub was harmless. Now a repeated `put(entity, true)` — a pipeline redeploying the same definition, say — grows the table without bound. `TestSemanticModelJDBCBackend.java:369` asserts exactly this retain-everything behaviour (`List.of(1, 2, 3)`) with nothing configured to trim it.\n\nTwo established shapes to pick from: `ViewMetaService` retires the superseded snapshot inline, and `FunctionMetaService` retains snapshots but backs that with `deleteFunctionVersionsByRetentionCount` wired into `deleteOldVersionData`. This PR takes Function's retention model without Function's collector, which is the one combination that leaks. Adding `deleteSemanticModelVersionsByRetentionCount` and replacing the stub would close it.\n\nVerified by: read `JDBCBacken
 d.java:541-585` and `SemanticModelMetaService.java:146-151` in the checked-out PR tree; `grep -rn \"deleteFunctionVersionsByRetentionCount\"` confirms the Function precedent, and `TestSemanticModelJDBCBackend.java:369` confirms snapshots accumulate."
       },
       {
         "path": "core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetaService.java",
         "start_line": 139,
         "line": 143,
         "side": "RIGHT",
         "severity": "Nit",
         "body": "[Nit] A lost overwrite here throws `IllegalStateException`, which no caller can classify.\n\n`ExceptionUtils.checkSQLException` (line 153) only converts when `re.getCause() instanceof SQLException` (`ExceptionUtils.java:32-38`), so a `Preconditions.checkState` failure falls straight through the `catch` and out of `insertSemanticModel` as a raw `IllegalStateException` — not the `OptimisticLockException` that retry logic keys on, and not `NoSuchEntityException`. The sibling path throws the classified exception instead: `ViewMetaService.java:317-318` does `if (updated == 0) throw viewWriteFailure(...)`, which routes through `OccWriteSupport.writeFailure` and picks `NoSuchEntityException` or `ExceptionUtils.concurrentModification` based on a re-read.\n\nI could not construct a reachable case: the row is held by `FOR UPDATE` for the whole transaction and `nextVersion` is always above every existing snapshot version, so `updated` should be 1. That makes this defensive r
 ather than a live bug — but if the guard is worth keeping, it is worth throwing what the rest of the module throws.\n\nVerified by: read `SemanticModelMetaService.java:136-155`, `ExceptionUtils.java:32-38`, `ViewMetaService.java:314-322` and `OccWriteSupport.java:113-135` in the checked-out PR tree."
       },
       {
         "path": "core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SemanticModelMetaBaseSQLProvider.java",
         "start_line": 183,
         "line": 195,
         "side": "RIGHT",
         "severity": "Nit",
         "body": "[Nit] This upsert is now unreachable, and it is the same SQL flagged last round as a version-bump trap.\n\n`insertSemanticModelMetaOnDuplicateKeyUpdate` is only reached from `SemanticModelPOStorageOps.insertPO(..., overwrite=true)`, and the one call site passes a hard-coded `false` (`SemanticModelMetaService.java:133`). So the `last_version = current_version + 1` / `current_version = current_version + 1` pair on lines 193-194, plus the `SemanticModelMetaPostgreSQLProvider` override, now computes a version bump that nothing executes — while the Java path computes its own `nextVersion` at `SemanticModelMetaService.java:166-171`. Two copies of the same rule, one of them dead, is exactly the drift the last round's finding was about.\n\n`SemanticModelVersionInfoMapper.insertSemanticModelVersionInfoOnDuplicateKeyUpdate` and its two providers have no callers at all, and `selectSemanticModelMetaByIdForUpdate` is the third (see the separate comment about the missing by-ID 
 lock, which is the one of the three that should arguably be wired rather than deleted).\n\nVerified by: `grep -rn` over `core/src` for `insertSemanticModelMetaOnDuplicateKeyUpdate`, `insertSemanticModelVersionInfoOnDuplicateKeyUpdate` and `selectSemanticModelMetaByIdForUpdate` — the first reaches only `SemanticModelPOStorageOps.java:40`, and `SemanticModelMetaService.java:133` is the sole `insertPO` caller, passing `false`."
       }
     ]
   }
   ```
   
   ---
   _Generated by [Claude Code](https://claude.ai/code)_


-- 
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] [#12600] feat(store): Add Semantic Model create and load persistence [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelPO.java:
##########
@@ -0,0 +1,224 @@
+/*
+ * 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.storage.relational.po;
+
+import static org.apache.gravitino.storage.relational.utils.POConverters.DEFAULT_DELETED_AT;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.base.Preconditions;
+import java.util.Collections;
+import java.util.Map;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+import lombok.ToString;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.json.JsonUtils;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.NamespacedEntityId;
+import org.apache.gravitino.meta.SemanticModelEntity;
+import org.apache.gravitino.semantic.SemanticModelDefinition;
+import org.apache.gravitino.storage.relational.service.EntityIdService;
+
+/** The persistent object for Semantic Model identity metadata and its current version snapshot. */
+@Getter
+@EqualsAndHashCode(exclude = "semanticModelVersionInfoPO")
+@ToString
+public class SemanticModelPO {
+
+  /** The initial version allocated to a newly created Semantic Model. */
+  public static final Long INITIAL_VERSION = 1L;
+
+  private Long semanticModelId;
+  private String semanticModelName;
+  private Long metalakeId;
+  private Long catalogId;
+  private Long schemaId;
+  private String auditInfo;
+  private Long currentVersion;
+  private Long lastVersion;
+  private Long deletedAt;
+  private SemanticModelVersionInfoPO semanticModelVersionInfoPO;
+
+  /** Creates an empty persistent object for MyBatis. */
+  public SemanticModelPO() {}
+
+  /** A Lombok builder for {@link SemanticModelPO}. */
+  public static class SemanticModelPOBuilder {
+    // Lombok generates the builder methods.
+  }
+
+  @lombok.Builder(setterPrefix = "with")
+  private SemanticModelPO(
+      Long semanticModelId,
+      String semanticModelName,
+      Long metalakeId,
+      Long catalogId,
+      Long schemaId,
+      String auditInfo,
+      Long currentVersion,
+      Long lastVersion,
+      Long deletedAt,
+      SemanticModelVersionInfoPO semanticModelVersionInfoPO) {
+    Preconditions.checkArgument(semanticModelId != null, "Semantic Model id is required");
+    Preconditions.checkArgument(semanticModelName != null, "Semantic Model name is required");
+    Preconditions.checkArgument(metalakeId != null, "Metalake id is required");
+    Preconditions.checkArgument(catalogId != null, "Catalog id is required");
+    Preconditions.checkArgument(schemaId != null, "Schema id is required");
+    Preconditions.checkArgument(auditInfo != null, "Audit info is required");
+    Preconditions.checkArgument(currentVersion != null, "Current version is required");
+    Preconditions.checkArgument(lastVersion != null, "Last version is required");
+    Preconditions.checkArgument(deletedAt != null, "Deleted at is required");
+
+    this.semanticModelId = semanticModelId;
+    this.semanticModelName = semanticModelName;
+    this.metalakeId = metalakeId;
+    this.catalogId = catalogId;
+    this.schemaId = schemaId;
+    this.auditInfo = auditInfo;
+    this.currentVersion = currentVersion;
+    this.lastVersion = lastVersion;
+    this.deletedAt = deletedAt;
+    this.semanticModelVersionInfoPO = semanticModelVersionInfoPO;
+  }
+
+  /**
+   * Converts a persistent object and its current version snapshot to a Semantic Model entity.
+   *
+   * @param semanticModelPO The persistent object to convert.
+   * @param namespace The Semantic Model namespace.
+   * @return The converted Semantic Model entity.
+   */
+  public static SemanticModelEntity fromSemanticModelPO(
+      SemanticModelPO semanticModelPO, Namespace namespace) {
+    try {
+      SemanticModelVersionInfoPO versionPO = semanticModelPO.getSemanticModelVersionInfoPO();
+      SemanticModelDefinition definition =
+          SemanticModelDefinitionSerDe.deserialize(versionPO.semanticModelDefinition());
+      Map<String, String> properties =
+          versionPO.properties() == null
+              ? Collections.emptyMap()
+              : JsonUtils.anyFieldMapper()
+                  .readValue(
+                      versionPO.properties(),
+                      JsonUtils.anyFieldMapper()
+                          .getTypeFactory()
+                          .constructMapType(Map.class, String.class, String.class));
+
+      return SemanticModelEntity.builder()
+          .withId(semanticModelPO.getSemanticModelId())
+          .withName(versionPO.semanticModelName())
+          .withNamespace(namespace)
+          .withComment(versionPO.semanticModelComment())
+          .withDefinition(definition)
+          .withProperties(properties)
+          .withAuditInfo(
+              JsonUtils.anyFieldMapper().readValue(semanticModelPO.getAuditInfo(), AuditInfo.class))
+          .build();
+    } catch (JsonProcessingException e) {
+      throw new RuntimeException("Failed to deserialize Semantic Model JSON", e);
+    }
+  }
+
+  /**
+   * Initializes a new Semantic Model identity and version-one snapshot.
+   *
+   * @param semanticModelEntity The Semantic Model entity.
+   * @param builder The identity persistent-object builder.
+   * @return The initialized persistent object.
+   */
+  public static SemanticModelPO initializeSemanticModelPO(
+      SemanticModelEntity semanticModelEntity, SemanticModelPOBuilder builder) {
+    builder.withCurrentVersion(INITIAL_VERSION).withLastVersion(INITIAL_VERSION);
+    return buildSemanticModelPO(semanticModelEntity, builder, INITIAL_VERSION.intValue());
+  }
+
+  /**
+   * Creates a complete version snapshot for a Semantic Model entity.
+   *
+   * @param semanticModelEntity The Semantic Model entity.
+   * @param namespacedEntityId The resolved schema and ancestor IDs.
+   * @param version The version to allocate.
+   * @return The version snapshot persistent object.
+   */
+  public static SemanticModelVersionInfoPO initializeSemanticModelVersionInfoPO(
+      SemanticModelEntity semanticModelEntity,
+      NamespacedEntityId namespacedEntityId,
+      Integer version) {
+    try {
+      String definitionJson =
+          SemanticModelDefinitionSerDe.serialize(semanticModelEntity.definition());
+      String propertiesJson =
+          semanticModelEntity.properties().isEmpty()
+              ? null
+              : JsonUtils.anyFieldMapper().writeValueAsString(semanticModelEntity.properties());
+
+      return SemanticModelVersionInfoPO.builder()
+          .withSemanticModelId(semanticModelEntity.id())
+          .withMetalakeId(namespacedEntityId.namespaceIds()[0])
+          .withCatalogId(namespacedEntityId.namespaceIds()[1])
+          .withSchemaId(namespacedEntityId.entityId())
+          .withVersion(version)
+          .withSemanticModelName(semanticModelEntity.name())
+          .withSemanticModelComment(semanticModelEntity.comment())
+          .withSemanticModelDefinition(definitionJson)
+          .withProperties(propertiesJson)
+          .withAuditInfo(
+              JsonUtils.anyFieldMapper().writeValueAsString(semanticModelEntity.auditInfo()))
+          .withDeletedAt(DEFAULT_DELETED_AT)
+          .build();
+    } catch (JsonProcessingException e) {
+      throw new RuntimeException("Failed to serialize Semantic Model JSON", e);
+    }
+  }
+
+  /**
+   * Builds a Semantic Model identity persistent object and the requested complete snapshot.
+   *
+   * @param semanticModelEntity The Semantic Model entity.
+   * @param builder The identity persistent-object builder.
+   * @param version The version to allocate.
+   * @return The built persistent object.
+   */
+  public static SemanticModelPO buildSemanticModelPO(
+      SemanticModelEntity semanticModelEntity, SemanticModelPOBuilder builder, Integer version) {
+    try {
+      NamespacedEntityId namespacedEntityId =
+          EntityIdService.getEntityIds(
+              NameIdentifier.of(semanticModelEntity.namespace().levels()),
+              Entity.EntityType.SCHEMA);
+      SemanticModelVersionInfoPO versionPO =
+          initializeSemanticModelVersionInfoPO(semanticModelEntity, namespacedEntityId, version);
+      return builder
+          .withSemanticModelId(semanticModelEntity.id())
+          .withSemanticModelName(semanticModelEntity.name())
+          .withMetalakeId(namespacedEntityId.namespaceIds()[0])
+          .withCatalogId(namespacedEntityId.namespaceIds()[1])
+          .withSchemaId(namespacedEntityId.entityId())
+          .withAuditInfo(
+              JsonUtils.anyFieldMapper().writeValueAsString(semanticModelEntity.auditInfo()))

Review Comment:
   Thanks for pointing this out. `buildSemanticModelPO(...)` now sets `currentVersion` and `lastVersion` from the supplied `version` before building the PO, so callers can safely use a fresh builder without relying on hidden preconditions.



-- 
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] [#12600] feat(store): Add Semantic Model create and load persistence [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelPOStorageOps.java:
##########
@@ -0,0 +1,81 @@
+/*
+ * 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.storage.relational.service;
+
+import java.util.Locale;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;
+import org.apache.gravitino.storage.relational.po.SemanticModelPO;
+
+/** Provides relational persistent-object operations required to create and load Semantic Models. */
+public class SemanticModelPOStorageOps
+    extends BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> {
+
+  /** Creates Semantic Model persistent-object operations. */
+  public SemanticModelPOStorageOps() {}
+
+  @Override
+  public void insertPO(
+      SemanticModelMetaMapper mapper, SemanticModelPO semanticModelPO, boolean overwrite) {
+    if (overwrite) {
+      mapper.insertSemanticModelMetaOnDuplicateKeyUpdate(semanticModelPO);
+    } else {
+      mapper.insertSemanticModelMeta(semanticModelPO);
+    }
+  }
+
+  @Override
+  public SemanticModelPO getPO(
+      SemanticModelMetaMapper mapper, Long parentId, String semanticModelName) {
+    return mapper.selectSemanticModelMetaBySchemaIdAndName(parentId, semanticModelName);
+  }
+
+  @Override
+  public SemanticModelPO getPOByFullName(
+      SemanticModelMetaMapper mapper, NameIdentifier identifier) {
+    Namespace namespace = identifier.namespace();
+    SemanticModelPO po =
+        mapper.selectSemanticModelByFullQualifiedName(
+            namespace.level(0), namespace.level(1), namespace.level(2), identifier.name());
+    if (po == null) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.CATALOG.name().toLowerCase(Locale.ROOT),
+          namespace.level(1));

Review Comment:
   When the metalake does not exist, `selectSemanticModelByFullQualifiedName(...)` returns `null` (because the SQL `WHERE` filters on metalake), but the code throws `NoSuchEntityException` for a **catalog**. This misreports the missing entity. A concrete fix is to make the SQL return a row even when the catalog is missing (e.g., left-join the catalog as well, similar to schema/model) so you can distinguish: metalake missing vs catalog missing vs schema missing; alternatively, if keeping the current SQL shape, treat `po == null` as a metalake-missing case (using `namespace.level(0)` and `EntityType.METALAKE`) and add a separate check/query for catalog existence to preserve correct error classification.



##########
core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelVersionInfoPO.java:
##########
@@ -0,0 +1,91 @@
+/*
+ * 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.storage.relational.po;
+
+import com.google.common.base.Preconditions;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+import lombok.ToString;
+import lombok.experimental.Accessors;
+import org.apache.commons.lang3.StringUtils;
+
+/** The persistent object for a complete Semantic Model version snapshot. */
+@EqualsAndHashCode
+@Getter
+@ToString
+@Accessors(fluent = true)
+public class SemanticModelVersionInfoPO {
+
+  private Long id;
+  private Long metalakeId;
+  private Long catalogId;
+  private Long schemaId;
+  private Long semanticModelId;
+  private Integer version;
+  private String semanticModelName;

Review Comment:
   The snapshot PO uses `Integer version`, while the identity PO uses `Long currentVersion/lastVersion`. This type mismatch can lead to implicit casts in SQL joins/comparisons and creates an avoidable overflow boundary for long-lived entities. Consider standardizing version types across POs (and DB columns) to a single type (preferably `Long`) to keep mappings and SQL consistent.



##########
core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelPO.java:
##########
@@ -0,0 +1,224 @@
+/*
+ * 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.storage.relational.po;
+
+import static org.apache.gravitino.storage.relational.utils.POConverters.DEFAULT_DELETED_AT;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.base.Preconditions;
+import java.util.Collections;
+import java.util.Map;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+import lombok.ToString;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.json.JsonUtils;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.NamespacedEntityId;
+import org.apache.gravitino.meta.SemanticModelEntity;
+import org.apache.gravitino.semantic.SemanticModelDefinition;
+import org.apache.gravitino.storage.relational.service.EntityIdService;
+
+/** The persistent object for Semantic Model identity metadata and its current version snapshot. */
+@Getter
+@EqualsAndHashCode(exclude = "semanticModelVersionInfoPO")
+@ToString
+public class SemanticModelPO {
+
+  /** The initial version allocated to a newly created Semantic Model. */
+  public static final Long INITIAL_VERSION = 1L;
+
+  private Long semanticModelId;
+  private String semanticModelName;
+  private Long metalakeId;
+  private Long catalogId;
+  private Long schemaId;
+  private String auditInfo;
+  private Long currentVersion;
+  private Long lastVersion;
+  private Long deletedAt;
+  private SemanticModelVersionInfoPO semanticModelVersionInfoPO;
+
+  /** Creates an empty persistent object for MyBatis. */
+  public SemanticModelPO() {}
+
+  /** A Lombok builder for {@link SemanticModelPO}. */
+  public static class SemanticModelPOBuilder {
+    // Lombok generates the builder methods.
+  }
+
+  @lombok.Builder(setterPrefix = "with")
+  private SemanticModelPO(
+      Long semanticModelId,
+      String semanticModelName,
+      Long metalakeId,
+      Long catalogId,
+      Long schemaId,
+      String auditInfo,
+      Long currentVersion,
+      Long lastVersion,
+      Long deletedAt,
+      SemanticModelVersionInfoPO semanticModelVersionInfoPO) {
+    Preconditions.checkArgument(semanticModelId != null, "Semantic Model id is required");
+    Preconditions.checkArgument(semanticModelName != null, "Semantic Model name is required");
+    Preconditions.checkArgument(metalakeId != null, "Metalake id is required");
+    Preconditions.checkArgument(catalogId != null, "Catalog id is required");
+    Preconditions.checkArgument(schemaId != null, "Schema id is required");
+    Preconditions.checkArgument(auditInfo != null, "Audit info is required");
+    Preconditions.checkArgument(currentVersion != null, "Current version is required");
+    Preconditions.checkArgument(lastVersion != null, "Last version is required");
+    Preconditions.checkArgument(deletedAt != null, "Deleted at is required");
+
+    this.semanticModelId = semanticModelId;
+    this.semanticModelName = semanticModelName;
+    this.metalakeId = metalakeId;
+    this.catalogId = catalogId;
+    this.schemaId = schemaId;
+    this.auditInfo = auditInfo;
+    this.currentVersion = currentVersion;
+    this.lastVersion = lastVersion;
+    this.deletedAt = deletedAt;
+    this.semanticModelVersionInfoPO = semanticModelVersionInfoPO;
+  }
+
+  /**
+   * Converts a persistent object and its current version snapshot to a Semantic Model entity.
+   *
+   * @param semanticModelPO The persistent object to convert.
+   * @param namespace The Semantic Model namespace.
+   * @return The converted Semantic Model entity.
+   */
+  public static SemanticModelEntity fromSemanticModelPO(
+      SemanticModelPO semanticModelPO, Namespace namespace) {
+    try {
+      SemanticModelVersionInfoPO versionPO = semanticModelPO.getSemanticModelVersionInfoPO();
+      SemanticModelDefinition definition =
+          SemanticModelDefinitionSerDe.deserialize(versionPO.semanticModelDefinition());
+      Map<String, String> properties =
+          versionPO.properties() == null
+              ? Collections.emptyMap()
+              : JsonUtils.anyFieldMapper()
+                  .readValue(
+                      versionPO.properties(),
+                      JsonUtils.anyFieldMapper()
+                          .getTypeFactory()
+                          .constructMapType(Map.class, String.class, String.class));
+
+      return SemanticModelEntity.builder()
+          .withId(semanticModelPO.getSemanticModelId())
+          .withName(versionPO.semanticModelName())
+          .withNamespace(namespace)
+          .withComment(versionPO.semanticModelComment())
+          .withDefinition(definition)
+          .withProperties(properties)
+          .withAuditInfo(
+              JsonUtils.anyFieldMapper().readValue(semanticModelPO.getAuditInfo(), AuditInfo.class))
+          .build();
+    } catch (JsonProcessingException e) {
+      throw new RuntimeException("Failed to deserialize Semantic Model JSON", e);
+    }
+  }
+
+  /**
+   * Initializes a new Semantic Model identity and version-one snapshot.
+   *
+   * @param semanticModelEntity The Semantic Model entity.
+   * @param builder The identity persistent-object builder.
+   * @return The initialized persistent object.
+   */
+  public static SemanticModelPO initializeSemanticModelPO(
+      SemanticModelEntity semanticModelEntity, SemanticModelPOBuilder builder) {
+    builder.withCurrentVersion(INITIAL_VERSION).withLastVersion(INITIAL_VERSION);
+    return buildSemanticModelPO(semanticModelEntity, builder, INITIAL_VERSION.intValue());
+  }
+
+  /**
+   * Creates a complete version snapshot for a Semantic Model entity.
+   *
+   * @param semanticModelEntity The Semantic Model entity.
+   * @param namespacedEntityId The resolved schema and ancestor IDs.
+   * @param version The version to allocate.
+   * @return The version snapshot persistent object.
+   */
+  public static SemanticModelVersionInfoPO initializeSemanticModelVersionInfoPO(
+      SemanticModelEntity semanticModelEntity,
+      NamespacedEntityId namespacedEntityId,
+      Integer version) {
+    try {
+      String definitionJson =
+          SemanticModelDefinitionSerDe.serialize(semanticModelEntity.definition());
+      String propertiesJson =
+          semanticModelEntity.properties().isEmpty()
+              ? null
+              : JsonUtils.anyFieldMapper().writeValueAsString(semanticModelEntity.properties());
+
+      return SemanticModelVersionInfoPO.builder()
+          .withSemanticModelId(semanticModelEntity.id())
+          .withMetalakeId(namespacedEntityId.namespaceIds()[0])
+          .withCatalogId(namespacedEntityId.namespaceIds()[1])
+          .withSchemaId(namespacedEntityId.entityId())
+          .withVersion(version)
+          .withSemanticModelName(semanticModelEntity.name())
+          .withSemanticModelComment(semanticModelEntity.comment())
+          .withSemanticModelDefinition(definitionJson)
+          .withProperties(propertiesJson)
+          .withAuditInfo(
+              JsonUtils.anyFieldMapper().writeValueAsString(semanticModelEntity.auditInfo()))
+          .withDeletedAt(DEFAULT_DELETED_AT)
+          .build();
+    } catch (JsonProcessingException e) {
+      throw new RuntimeException("Failed to serialize Semantic Model JSON", e);
+    }
+  }
+
+  /**
+   * Builds a Semantic Model identity persistent object and the requested complete snapshot.
+   *
+   * @param semanticModelEntity The Semantic Model entity.
+   * @param builder The identity persistent-object builder.
+   * @param version The version to allocate.
+   * @return The built persistent object.
+   */
+  public static SemanticModelPO buildSemanticModelPO(
+      SemanticModelEntity semanticModelEntity, SemanticModelPOBuilder builder, Integer version) {
+    try {
+      NamespacedEntityId namespacedEntityId =
+          EntityIdService.getEntityIds(
+              NameIdentifier.of(semanticModelEntity.namespace().levels()),
+              Entity.EntityType.SCHEMA);
+      SemanticModelVersionInfoPO versionPO =
+          initializeSemanticModelVersionInfoPO(semanticModelEntity, namespacedEntityId, version);
+      return builder
+          .withSemanticModelId(semanticModelEntity.id())
+          .withSemanticModelName(semanticModelEntity.name())
+          .withMetalakeId(namespacedEntityId.namespaceIds()[0])
+          .withCatalogId(namespacedEntityId.namespaceIds()[1])
+          .withSchemaId(namespacedEntityId.entityId())
+          .withAuditInfo(
+              JsonUtils.anyFieldMapper().writeValueAsString(semanticModelEntity.auditInfo()))

Review Comment:
   `buildSemanticModelPO(...)` is public and does not set `currentVersion` / `lastVersion`, yet the PO constructor requires them (via Preconditions). This makes the method easy to misuse (callers can pass a fresh builder and get a runtime failure). To make the API harder to misuse, either: (a) set `currentVersion/lastVersion` inside this method when appropriate, (b) make this helper `private`/package-private and expose only safer factory methods (like `initializeSemanticModelPO`), or (c) document clearly in Javadoc that the caller must pre-populate those builder fields.



##########
core/src/test/java/org/apache/gravitino/storage/relational/TestSemanticModelJDBCBackend.java:
##########
@@ -0,0 +1,259 @@
+/*
+ * 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.storage.relational;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import com.google.common.collect.ImmutableMap;
+import java.io.IOException;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.List;
+import java.util.Map;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.EntityAlreadyExistsException;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.meta.SemanticModelEntity;
+import org.apache.gravitino.semantic.AIContext;
+import org.apache.gravitino.semantic.AIContextObject;
+import org.apache.gravitino.semantic.CustomExtension;
+import org.apache.gravitino.semantic.DataType;
+import org.apache.gravitino.semantic.Dataset;
+import org.apache.gravitino.semantic.DialectExpression;
+import org.apache.gravitino.semantic.Dimension;
+import org.apache.gravitino.semantic.Expression;
+import org.apache.gravitino.semantic.Field;
+import org.apache.gravitino.semantic.Metric;
+import org.apache.gravitino.semantic.Relationship;
+import org.apache.gravitino.semantic.SemanticModelDefinition;
+import org.apache.gravitino.storage.RandomIdGenerator;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelVersionInfoMapper;
+import org.apache.gravitino.storage.relational.po.SemanticModelPO;
+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.gravitino.utils.NamespaceUtil;
+import org.apache.ibatis.session.SqlSession;
+import org.junit.jupiter.api.TestTemplate;
+
+/** Tests Semantic Model create and load persistence through {@link JDBCBackend}. */
+public class TestSemanticModelJDBCBackend extends TestJDBCBackend {
+
+  @TestTemplate
+  public void testCreateAndLoadRoundTrip() throws IOException {
+    Namespace namespace = createParents("round_trip");
+    SemanticModelEntity absent =
+        semanticModel(
+            RandomIdGenerator.INSTANCE.nextId(),
+            namespace,
+            "absent_optional_model",
+            false,
+            ImmutableMap.of("domain", "sales"));
+    SemanticModelEntity empty =
+        semanticModel(
+            RandomIdGenerator.INSTANCE.nextId(),
+            namespace,
+            "empty_optional_model",
+            true,
+            ImmutableMap.of());
+
+    backend.insert(absent, false);
+    backend.insert(empty, false);
+
+    SemanticModelEntity loadedAbsent =
+        backend.get(absent.nameIdentifier(), Entity.EntityType.SEMANTIC_MODEL);
+    SemanticModelEntity loadedEmpty =
+        backend.get(empty.nameIdentifier(), Entity.EntityType.SEMANTIC_MODEL);
+
+    assertEquals(absent, loadedAbsent);
+    assertEquals(empty, loadedEmpty);
+    assertNull(loadedAbsent.definition().relationships());
+    assertNull(loadedAbsent.definition().metrics());
+    assertEquals(0, loadedEmpty.definition().relationships().length);
+    assertEquals(0, loadedEmpty.definition().metrics().length);
+    assertTrue(loadedEmpty.properties().isEmpty());
+    assertEquals(
+        new BigDecimal("1.50"),
+        loadedAbsent.definition().aiContext().object().additionalProperties().get("threshold"));
+    assertNull(loadedAbsent.definition().aiContext().object().examples());
+    assertEquals(0, loadedAbsent.definition().aiContext().object().synonyms().length);
+  }
+
+  @TestTemplate
+  public void testDuplicateAndMissingEntities() throws IOException {
+    Namespace namespace = createParents("duplicate");
+    SemanticModelEntity original =
+        semanticModel(
+            RandomIdGenerator.INSTANCE.nextId(),
+            namespace,
+            "sales_model",
+            false,
+            ImmutableMap.of("owner", "analytics"));
+    backend.insert(original, false);
+
+    SemanticModelEntity duplicate =
+        semanticModel(
+            RandomIdGenerator.INSTANCE.nextId(),
+            namespace,
+            original.name(),
+            true,
+            ImmutableMap.of());
+    assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(duplicate, false));
+    assertEquals(
+        original, backend.get(original.nameIdentifier(), Entity.EntityType.SEMANTIC_MODEL));
+
+    NameIdentifier missingModel = NameIdentifier.of(namespace, "missing_model");
+    assertThrows(
+        NoSuchEntityException.class,
+        () -> backend.get(missingModel, Entity.EntityType.SEMANTIC_MODEL));
+
+    String suffix = Long.toUnsignedString(RandomIdGenerator.INSTANCE.nextId());
+    String metalakeName = "missing_parent_metalake_" + suffix;
+    String catalogName = "missing_parent_catalog_" + suffix;
+    createAndInsertMakeLake(metalakeName);
+    createAndInsertCatalog(metalakeName, catalogName);
+    Namespace missingParentNamespace =
+        NamespaceUtil.ofSemanticModel(metalakeName, catalogName, "missing_schema");
+    SemanticModelEntity missingParent =
+        semanticModel(
+            RandomIdGenerator.INSTANCE.nextId(),
+            missingParentNamespace,
+            "orphan_model",
+            false,
+            ImmutableMap.of());
+
+    assertThrows(NoSuchEntityException.class, () -> backend.insert(missingParent, false));
+    assertEquals(0, countRows("semantic_model_meta", missingParent.id()));
+    assertEquals(0, countRows("semantic_model_version_info", missingParent.id()));
+  }
+
+  @TestTemplate
+  public void testCreateRollsBackIdentityWhenSnapshotInsertFails() throws IOException {
+    Namespace namespace = createParents("transaction");
+    SemanticModelEntity semanticModel =
+        semanticModel(
+            RandomIdGenerator.INSTANCE.nextId(),
+            namespace,
+            "transaction_model",
+            false,
+            ImmutableMap.of("domain", "finance"));
+    SemanticModelPO po =
+        SemanticModelPO.initializeSemanticModelPO(semanticModel, SemanticModelPO.builder());
+    SessionUtils.doWithCommit(
+        SemanticModelVersionInfoMapper.class,
+        mapper -> mapper.insertSemanticModelVersionInfo(po.getSemanticModelVersionInfoPO()));
+
+    assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(semanticModel, false));
+    assertEquals(0, countRows("semantic_model_meta", semanticModel.id()));
+    assertEquals(1, countRows("semantic_model_version_info", semanticModel.id()));
+  }
+
+  private Namespace createParents(String prefix) throws IOException {
+    String suffix = Long.toUnsignedString(RandomIdGenerator.INSTANCE.nextId());
+    String metalakeName = prefix + "_metalake_" + suffix;
+    String catalogName = prefix + "_catalog_" + suffix;
+    String schemaName = prefix + "_schema_" + suffix;
+    createAndInsertMakeLake(metalakeName);
+    createAndInsertCatalog(metalakeName, catalogName);
+    createAndInsertSchema(metalakeName, catalogName, schemaName);
+    return NamespaceUtil.ofSemanticModel(metalakeName, catalogName, schemaName);
+  }
+
+  private SemanticModelEntity semanticModel(
+      Long id,
+      Namespace namespace,
+      String name,
+      boolean explicitEmpty,
+      Map<String, String> properties) {
+    AIContextObject context =
+        AIContextObject.builder()
+            .withInstructions("Use certified sales definitions")
+            .withSynonyms(new String[0])
+            .withAdditionalProperties(
+                Map.of("threshold", new BigDecimal("1.50"), "nested", List.of(new BigInteger("3"))))
+            .build();
+    Field field =
+        Field.builder()
+            .withName("ordered_at")
+            .withExpression(
+                Expression.builder()
+                    .withDialects(
+                        new DialectExpression[] {
+                          DialectExpression.builder()
+                              .withDialect("ansi")
+                              .withExpression("ordered_at")
+                              .build()
+                        })
+                    .build())
+            .withDimension(Dimension.builder().withIsTime(true).build())
+            .withDatatype(DataType.DATE_TIME_TZ)
+            .build();
+    Dataset dataset =
+        Dataset.builder()
+            .withName("orders")
+            .withSource(NameIdentifier.of("sales", "mart", "orders"))
+            .withPrimaryKey(new String[0])
+            .withFields(new Field[] {field})
+            .build();
+    SemanticModelDefinition.Builder definitionBuilder =
+        SemanticModelDefinition.builder()
+            .withAIContext(AIContext.of(context))
+            .withDatasets(new Dataset[] {dataset});
+    if (explicitEmpty) {
+      definitionBuilder
+          .withRelationships(new Relationship[0])
+          .withMetrics(new Metric[0])
+          .withCustomExtensions(new CustomExtension[0]);
+    }
+
+    return SemanticModelEntity.builder()
+        .withId(id)
+        .withName(name)
+        .withNamespace(namespace)
+        .withComment(explicitEmpty ? null : "Governed sales definitions")
+        .withDefinition(definitionBuilder.build())
+        .withProperties(properties)
+        .withAuditInfo(AUDIT_INFO)
+        .build();
+  }
+
+  private int countRows(String tableName, Long semanticModelId) {
+    String sql =
+        String.format(
+            "SELECT count(*) FROM %s WHERE semantic_model_id = %d", tableName, semanticModelId);
+    try (SqlSession sqlSession =
+            SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);
+        Connection connection = sqlSession.getConnection();
+        Statement statement = connection.createStatement();
+        ResultSet resultSet = statement.executeQuery(sql)) {

Review Comment:
   This test helper builds SQL via string formatting and executes it with a plain `Statement`. Even in tests, prefer parameter binding (e.g., `PreparedStatement`) for correctness and to avoid accidental SQL issues if the helper is reused/extended. If you keep `tableName` dynamic, consider constraining it to a fixed allowlist (the specific tables used in this test) to prevent accidental injection via future refactors.



-- 
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] [#12600] feat(store): Add Semantic Model create and load persistence [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelPOStorageOps.java:
##########
@@ -0,0 +1,81 @@
+/*
+ * 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.storage.relational.service;
+
+import java.util.Locale;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;
+import org.apache.gravitino.storage.relational.po.SemanticModelPO;
+
+/** Provides relational persistent-object operations required to create and load Semantic Models. */
+public class SemanticModelPOStorageOps
+    extends BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> {
+
+  /** Creates Semantic Model persistent-object operations. */
+  public SemanticModelPOStorageOps() {}
+
+  @Override
+  public void insertPO(
+      SemanticModelMetaMapper mapper, SemanticModelPO semanticModelPO, boolean overwrite) {
+    if (overwrite) {
+      mapper.insertSemanticModelMetaOnDuplicateKeyUpdate(semanticModelPO);
+    } else {
+      mapper.insertSemanticModelMeta(semanticModelPO);
+    }
+  }
+
+  @Override
+  public SemanticModelPO getPO(
+      SemanticModelMetaMapper mapper, Long parentId, String semanticModelName) {
+    return mapper.selectSemanticModelMetaBySchemaIdAndName(parentId, semanticModelName);
+  }
+
+  @Override
+  public SemanticModelPO getPOByFullName(
+      SemanticModelMetaMapper mapper, NameIdentifier identifier) {
+    Namespace namespace = identifier.namespace();
+    SemanticModelPO po =
+        mapper.selectSemanticModelByFullQualifiedName(
+            namespace.level(0), namespace.level(1), namespace.level(2), identifier.name());
+    if (po == null) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.CATALOG.name().toLowerCase(Locale.ROOT),
+          namespace.level(1));

Review Comment:
   Thanks for pointing this out. The full-name query does collapse a missing metalake and a missing catalog into the same `null` result. This is consistent with the existing relational lookup paths for schemas, tables, and views; the cache-enabled path also reports this case as a missing catalog via `CatalogMetaService#getCatalogIdByMetalakeAndCatalogName`.
   
   Changing only the Semantic Model path would make the exception classification depend on `gravitino.cache.enabled`. I propose keeping the existing behavior in this PR and handling metalake-vs-catalog classification, if desired, as a cross-entity relational-store 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] [#12600] feat(store): Add Semantic Model create and load persistence [gravitino]

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


##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -291,22 +291,23 @@ Most alters are safe:
 | drop                                               | for Group 1 the connector call fails; for a fileset the file path is gone and access fails                                                            | yes   |
 | catalog changes                                    | already handled today by a separate cross-node signal (`CatalogChangeLogListener`), not by this cache                                                 | yes   |
 
-Five cases are **not** safe — a stale read gives a wrong answer with no error. They are in the model area, functions, or the metalake on/off flag:
+Six cases are **not** safe — a stale read gives a wrong answer with no error. They are in the model area, Semantic Models, functions, or the metalake on/off flag:
 
 | Change                                                                | Why a stale read is wrong, with no error                                                                                                                                                            |
 | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
 | model version — update / add / remove URI                             | the URI points to the model files. An old URI silently loads the **wrong model files**.                                                                                                             |
 | model version — update aliases                                        | an alias silently points to the **wrong version**.                                                                                                                                                  |
 | model — latest version (after a new version is added on another node) | "get the latest version" silently returns an **old version**.                                                                                                                                       |
+| Semantic Model — overwrite definition                                | the current version selects the definition used for semantic queries. An old version silently uses the **wrong definition**.                                                                        |

Review Comment:
   This new table row's first cell is one space shorter than the surrounding rows. Please add one padding space so the Markdown source columns stay aligned.



##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetaService.java:
##########
@@ -0,0 +1,242 @@
+/*
+ * 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.storage.relational.service;
+
+import static org.apache.gravitino.metrics.source.MetricsSource.GRAVITINO_RELATIONAL_STORE_METRIC_NAME;
+import static org.apache.gravitino.storage.relational.po.SemanticModelPO.fromSemanticModelPO;
+import static org.apache.gravitino.storage.relational.po.SemanticModelPO.initializeSemanticModelPO;
+
+import com.google.common.base.Preconditions;
+import java.io.IOException;
+import java.util.Locale;
+import java.util.Objects;
+import java.util.concurrent.atomic.AtomicReference;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.meta.SemanticModelEntity;
+import org.apache.gravitino.metrics.Monitored;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelVersionInfoMapper;
+import org.apache.gravitino.storage.relational.po.SemanticModelPO;
+import org.apache.gravitino.storage.relational.po.SemanticModelVersionInfoPO;
+import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.gravitino.utils.NameIdentifierUtil;
+
+/** Provides relational create and load operations for Semantic Model metadata. */
+public class SemanticModelMetaService {
+
+  private static final SemanticModelMetaService INSTANCE = new SemanticModelMetaService();
+
+  private final BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> ops;
+
+  /** Returns the singleton Semantic Model metadata service. */
+  public static SemanticModelMetaService getInstance() {
+    return INSTANCE;
+  }
+
+  private SemanticModelMetaService() {
+    this.ops = new HierarchicalConversionPOStorageOps<>(new SemanticModelPOStorageOps());
+  }
+
+  /**
+   * Resolves a Semantic Model stable ID by schema ID and name.
+   *
+   * @param schemaId The parent schema ID.
+   * @param semanticModelName The Semantic Model name.
+   * @return The stable Semantic Model ID.
+   * @throws NoSuchEntityException If the Semantic Model does not exist.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "getSemanticModelIdBySchemaIdAndName")
+  public Long getSemanticModelIdBySchemaIdAndName(long schemaId, String semanticModelName) {
+    Long semanticModelId =
+        SessionUtils.getWithoutCommit(
+            SemanticModelMetaMapper.class,
+            mapper -> mapper.selectSemanticModelIdBySchemaIdAndName(schemaId, semanticModelName));
+    if (semanticModelId == null) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.SEMANTIC_MODEL.name().toLowerCase(Locale.ROOT),
+          semanticModelName);
+    }
+    return semanticModelId;
+  }
+
+  /**
+   * Loads the current Semantic Model by identifier.
+   *
+   * @param identifier The Semantic Model identifier.
+   * @return The current Semantic Model entity.
+   * @throws NoSuchEntityException If the Semantic Model does not exist.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "getSemanticModelByIdentifier")
+  public SemanticModelEntity getSemanticModelByIdentifier(NameIdentifier identifier) {
+    SemanticModelPO semanticModelPO = getSemanticModelPOByIdentifier(identifier);
+    return fromSemanticModelPO(semanticModelPO, identifier.namespace());
+  }
+
+  /**
+   * Inserts or overwrites a Semantic Model identity and its snapshot atomically.
+   *
+   * @param semanticModelEntity The Semantic Model entity.
+   * @param overwrite Whether to overwrite rows for the same stable ID or natural key.
+   * @throws IOException If relational persistence fails.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "insertSemanticModel")
+  public void insertSemanticModel(SemanticModelEntity semanticModelEntity, boolean overwrite)
+      throws IOException {
+    NameIdentifierUtil.checkSemanticModel(semanticModelEntity.nameIdentifier());
+    try {
+      SemanticModelPO po =
+          initializeSemanticModelPO(semanticModelEntity, SemanticModelPO.builder());
+      AtomicReference<SemanticModelPO> persistedPO = new AtomicReference<>(po);
+      SchemaMetaService.getInstance()

Review Comment:
   One rollout dependency to track: this enables Semantic Model writes, while the current schema non-cascade emptiness check and schema/catalog/metalake cascade deletion do not include Semantic Models. Creating one and then dropping its schema can leave an active identity and snapshot that normal name-based reads cannot reach. I see that #12603 covers lifecycle cleanup; please ensure it lands before this create path is exposed or released, and include a parent-drop regression test there.



-- 
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] [#12600] feat(store): Add Semantic Model create and load persistence [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetaService.java:
##########
@@ -0,0 +1,242 @@
+/*
+ * 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.storage.relational.service;
+
+import static org.apache.gravitino.metrics.source.MetricsSource.GRAVITINO_RELATIONAL_STORE_METRIC_NAME;
+import static org.apache.gravitino.storage.relational.po.SemanticModelPO.fromSemanticModelPO;
+import static org.apache.gravitino.storage.relational.po.SemanticModelPO.initializeSemanticModelPO;
+
+import com.google.common.base.Preconditions;
+import java.io.IOException;
+import java.util.Locale;
+import java.util.Objects;
+import java.util.concurrent.atomic.AtomicReference;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.meta.SemanticModelEntity;
+import org.apache.gravitino.metrics.Monitored;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelVersionInfoMapper;
+import org.apache.gravitino.storage.relational.po.SemanticModelPO;
+import org.apache.gravitino.storage.relational.po.SemanticModelVersionInfoPO;
+import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.gravitino.utils.NameIdentifierUtil;
+
+/** Provides relational create and load operations for Semantic Model metadata. */
+public class SemanticModelMetaService {
+
+  private static final SemanticModelMetaService INSTANCE = new SemanticModelMetaService();
+
+  private final BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> ops;
+
+  /** Returns the singleton Semantic Model metadata service. */
+  public static SemanticModelMetaService getInstance() {
+    return INSTANCE;
+  }
+
+  private SemanticModelMetaService() {
+    this.ops = new HierarchicalConversionPOStorageOps<>(new SemanticModelPOStorageOps());
+  }
+
+  /**
+   * Resolves a Semantic Model stable ID by schema ID and name.
+   *
+   * @param schemaId The parent schema ID.
+   * @param semanticModelName The Semantic Model name.
+   * @return The stable Semantic Model ID.
+   * @throws NoSuchEntityException If the Semantic Model does not exist.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "getSemanticModelIdBySchemaIdAndName")
+  public Long getSemanticModelIdBySchemaIdAndName(long schemaId, String semanticModelName) {
+    Long semanticModelId =
+        SessionUtils.getWithoutCommit(
+            SemanticModelMetaMapper.class,
+            mapper -> mapper.selectSemanticModelIdBySchemaIdAndName(schemaId, semanticModelName));
+    if (semanticModelId == null) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.SEMANTIC_MODEL.name().toLowerCase(Locale.ROOT),
+          semanticModelName);
+    }
+    return semanticModelId;
+  }
+
+  /**
+   * Loads the current Semantic Model by identifier.
+   *
+   * @param identifier The Semantic Model identifier.
+   * @return The current Semantic Model entity.
+   * @throws NoSuchEntityException If the Semantic Model does not exist.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "getSemanticModelByIdentifier")
+  public SemanticModelEntity getSemanticModelByIdentifier(NameIdentifier identifier) {
+    SemanticModelPO semanticModelPO = getSemanticModelPOByIdentifier(identifier);
+    return fromSemanticModelPO(semanticModelPO, identifier.namespace());
+  }
+
+  /**
+   * Inserts or overwrites a Semantic Model identity and its snapshot atomically.
+   *
+   * @param semanticModelEntity The Semantic Model entity.
+   * @param overwrite Whether to overwrite rows for the same stable ID or natural key.
+   * @throws IOException If relational persistence fails.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "insertSemanticModel")
+  public void insertSemanticModel(SemanticModelEntity semanticModelEntity, boolean overwrite)
+      throws IOException {
+    NameIdentifierUtil.checkSemanticModel(semanticModelEntity.nameIdentifier());
+    try {
+      SemanticModelPO po =
+          initializeSemanticModelPO(semanticModelEntity, SemanticModelPO.builder());
+      AtomicReference<SemanticModelPO> persistedPO = new AtomicReference<>(po);
+      SchemaMetaService.getInstance()

Review Comment:
   This is outside the scope of this PR and will be addressed in #12603, including parent-drop regression tests.



-- 
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] [#12600] feat(store): Add Semantic Model create and load persistence [gravitino]

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

   > A lost overwrite here throws `IllegalStateException`, which no caller can classify.
   
   Fixed. The zero-row overwrite path now uses `OccWriteSupport.writeFailure`, which re-reads the persisted identity and reports `NoSuchEntityException` or `OptimisticLockException` consistently with the View and Function OCC paths.
   
   > This upsert is now unreachable, and it is the same SQL flagged last round as a version-bump trap.
   
   Fixed. `SemanticModelPOStorageOps` now rejects overwrite requests and only performs strict inserts, matching the View and Function paths. The unused identity and version-snapshot upsert mapper/provider methods have been removed. `selectSemanticModelMetaByIdForUpdate` is retained and is now used to classify overwrite failures.


-- 
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] [#12600] feat(store): Add Semantic Model create and load persistence [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelPO.java:
##########
@@ -0,0 +1,225 @@
+/*
+ * 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.storage.relational.po;
+
+import static org.apache.gravitino.storage.relational.utils.POConverters.DEFAULT_DELETED_AT;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.base.Preconditions;
+import java.util.Collections;
+import java.util.Map;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+import lombok.ToString;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.json.JsonUtils;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.NamespacedEntityId;
+import org.apache.gravitino.meta.SemanticModelEntity;
+import org.apache.gravitino.semantic.SemanticModelDefinition;
+import org.apache.gravitino.storage.relational.service.EntityIdService;
+
+/** The persistent object for Semantic Model identity metadata and its current version snapshot. */
+@Getter
+@EqualsAndHashCode(exclude = "semanticModelVersionInfoPO")
+@ToString
+public class SemanticModelPO {
+
+  /** The initial version allocated to a newly created Semantic Model. */
+  public static final Integer INITIAL_VERSION = 1;
+
+  private Long semanticModelId;
+  private String semanticModelName;
+  private Long metalakeId;
+  private Long catalogId;
+  private Long schemaId;
+  private String auditInfo;
+  private Integer currentVersion;
+  private Integer lastVersion;
+  private Long deletedAt;
+  private SemanticModelVersionInfoPO semanticModelVersionInfoPO;
+
+  /** Creates an empty persistent object for MyBatis. */
+  public SemanticModelPO() {}
+
+  /** A Lombok builder for {@link SemanticModelPO}. */
+  public static class SemanticModelPOBuilder {
+    // Lombok generates the builder methods.
+  }
+
+  @lombok.Builder(setterPrefix = "with")
+  private SemanticModelPO(
+      Long semanticModelId,
+      String semanticModelName,
+      Long metalakeId,
+      Long catalogId,
+      Long schemaId,
+      String auditInfo,
+      Integer currentVersion,
+      Integer lastVersion,
+      Long deletedAt,
+      SemanticModelVersionInfoPO semanticModelVersionInfoPO) {
+    Preconditions.checkArgument(semanticModelId != null, "Semantic Model id is required");
+    Preconditions.checkArgument(semanticModelName != null, "Semantic Model name is required");
+    Preconditions.checkArgument(metalakeId != null, "Metalake id is required");
+    Preconditions.checkArgument(catalogId != null, "Catalog id is required");
+    Preconditions.checkArgument(schemaId != null, "Schema id is required");
+    Preconditions.checkArgument(auditInfo != null, "Audit info is required");
+    Preconditions.checkArgument(currentVersion != null, "Current version is required");
+    Preconditions.checkArgument(lastVersion != null, "Last version is required");
+    Preconditions.checkArgument(deletedAt != null, "Deleted at is required");
+
+    this.semanticModelId = semanticModelId;
+    this.semanticModelName = semanticModelName;
+    this.metalakeId = metalakeId;
+    this.catalogId = catalogId;
+    this.schemaId = schemaId;
+    this.auditInfo = auditInfo;
+    this.currentVersion = currentVersion;
+    this.lastVersion = lastVersion;
+    this.deletedAt = deletedAt;
+    this.semanticModelVersionInfoPO = semanticModelVersionInfoPO;
+  }
+
+  /**
+   * Converts a persistent object and its current version snapshot to a Semantic Model entity.
+   *
+   * @param semanticModelPO The persistent object to convert.
+   * @param namespace The Semantic Model namespace.
+   * @return The converted Semantic Model entity.
+   */
+  public static SemanticModelEntity fromSemanticModelPO(

Review Comment:
   I checked the analogous versioned entities more closely. `ViewPO` and `FunctionPO` keep their `from`, `initialize`, and version-snapshot conversion methods on the PO itself, and `JobPO` follows the same co-located pattern. `POConverters` is therefore not the universal convention and is already a large utility class.
   
   Semantic Model follows the View/Function pattern because its identity and version snapshot are built together. The shared JSON representation is already reused through `SemanticModelDefinitionDTO`, so I propose keeping these conversions on `SemanticModelPO`.



-- 
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] [#12600] feat(store): Add Semantic Model create and load persistence [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetaService.java:
##########
@@ -0,0 +1,226 @@
+/*
+ * 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.storage.relational.service;
+
+import static org.apache.gravitino.metrics.source.MetricsSource.GRAVITINO_RELATIONAL_STORE_METRIC_NAME;
+import static org.apache.gravitino.storage.relational.po.SemanticModelPO.fromSemanticModelPO;
+import static org.apache.gravitino.storage.relational.po.SemanticModelPO.initializeSemanticModelPO;
+
+import com.google.common.base.Preconditions;
+import java.io.IOException;
+import java.util.Locale;
+import java.util.concurrent.atomic.AtomicReference;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.meta.SemanticModelEntity;
+import org.apache.gravitino.metrics.Monitored;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelVersionInfoMapper;
+import org.apache.gravitino.storage.relational.po.SemanticModelPO;
+import org.apache.gravitino.storage.relational.po.SemanticModelVersionInfoPO;
+import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.gravitino.utils.NameIdentifierUtil;
+
+/** Provides relational create and load operations for Semantic Model metadata. */
+public class SemanticModelMetaService {
+
+  private static final SemanticModelMetaService INSTANCE = new SemanticModelMetaService();
+
+  private final BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> ops;
+
+  /** Returns the singleton Semantic Model metadata service. */
+  public static SemanticModelMetaService getInstance() {
+    return INSTANCE;
+  }
+
+  private SemanticModelMetaService() {
+    this.ops = new HierarchicalConversionPOStorageOps<>(new SemanticModelPOStorageOps());
+  }
+
+  /**
+   * Resolves a Semantic Model stable ID by schema ID and name.
+   *
+   * @param schemaId The parent schema ID.
+   * @param semanticModelName The Semantic Model name.
+   * @return The stable Semantic Model ID.
+   * @throws NoSuchEntityException If the Semantic Model does not exist.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "getSemanticModelIdBySchemaIdAndName")
+  public Long getSemanticModelIdBySchemaIdAndName(long schemaId, String semanticModelName) {
+    Long semanticModelId =
+        SessionUtils.getWithoutCommit(
+            SemanticModelMetaMapper.class,
+            mapper -> mapper.selectSemanticModelIdBySchemaIdAndName(schemaId, semanticModelName));
+    if (semanticModelId == null) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.SEMANTIC_MODEL.name().toLowerCase(Locale.ROOT),
+          semanticModelName);
+    }
+    return semanticModelId;
+  }
+
+  /**
+   * Loads the current Semantic Model by identifier.
+   *
+   * @param identifier The Semantic Model identifier.
+   * @return The current Semantic Model entity.
+   * @throws NoSuchEntityException If the Semantic Model does not exist.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "getSemanticModelByIdentifier")
+  public SemanticModelEntity getSemanticModelByIdentifier(NameIdentifier identifier) {
+    SemanticModelPO semanticModelPO = getSemanticModelPOByIdentifier(identifier);
+    return fromSemanticModelPO(semanticModelPO, identifier.namespace());
+  }
+
+  /**
+   * Inserts a Semantic Model identity and its version-one snapshot atomically.
+   *
+   * @param semanticModelEntity The Semantic Model entity.
+   * @param overwrite Whether to overwrite rows for the same stable ID or natural key.
+   * @throws IOException If relational persistence fails.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "insertSemanticModel")
+  public void insertSemanticModel(SemanticModelEntity semanticModelEntity, boolean overwrite)
+      throws IOException {
+    NameIdentifierUtil.checkSemanticModel(semanticModelEntity.nameIdentifier());
+    try {
+      SemanticModelPO po =
+          initializeSemanticModelPO(semanticModelEntity, SemanticModelPO.builder());
+      AtomicReference<SemanticModelPO> persistedPO = new AtomicReference<>();
+      AtomicReference<SemanticModelVersionInfoPO> persistedVersionInfoPO =
+          new AtomicReference<>(po.getSemanticModelVersionInfoPO());
+      SessionUtils.doMultipleWithCommit(
+          () ->
+              SchemaMetaService.getInstance()
+                  .lockSchemaForEntityWrite(
+                      semanticModelEntity.nameIdentifier(),
+                      po.getSchemaId(),
+                      po.getCatalogId(),
+                      po.getMetalakeId()),
+          () ->
+              SessionUtils.doWithoutCommit(
+                  SemanticModelMetaMapper.class,
+                  mapper -> {
+                    if (overwrite) {

Review Comment:
   Fixed. The missing-row path now uses a strict insert, so a concurrent natural-key collision fails instead of upserting with a different ID. Existing rows are locked by natural key and updated using the persisted ID and next version, keeping the identity and snapshot consistent.



##########
core/src/main/java/org/apache/gravitino/cache/BaseEntityCache.java:
##########
@@ -58,6 +58,7 @@ public abstract class BaseEntityCache implements EntityCache {
           Entity.EntityType.CATALOG,
           Entity.EntityType.SCHEMA,
           Entity.EntityType.TABLE,
+          Entity.EntityType.SEMANTIC_MODEL,

Review Comment:
   Fixed. Removed `SEMANTIC_MODEL` from `CACHEABLE_TYPES` and updated the cache documentation and tests. Local-cache deployments now read Semantic Models from the store, avoiding stale definitions during the cross-node invalidation window.



##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetaService.java:
##########
@@ -0,0 +1,226 @@
+/*
+ * 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.storage.relational.service;
+
+import static org.apache.gravitino.metrics.source.MetricsSource.GRAVITINO_RELATIONAL_STORE_METRIC_NAME;
+import static org.apache.gravitino.storage.relational.po.SemanticModelPO.fromSemanticModelPO;
+import static org.apache.gravitino.storage.relational.po.SemanticModelPO.initializeSemanticModelPO;
+
+import com.google.common.base.Preconditions;
+import java.io.IOException;
+import java.util.Locale;
+import java.util.concurrent.atomic.AtomicReference;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.meta.SemanticModelEntity;
+import org.apache.gravitino.metrics.Monitored;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelVersionInfoMapper;
+import org.apache.gravitino.storage.relational.po.SemanticModelPO;
+import org.apache.gravitino.storage.relational.po.SemanticModelVersionInfoPO;
+import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.gravitino.utils.NameIdentifierUtil;
+
+/** Provides relational create and load operations for Semantic Model metadata. */
+public class SemanticModelMetaService {
+
+  private static final SemanticModelMetaService INSTANCE = new SemanticModelMetaService();
+
+  private final BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> ops;
+
+  /** Returns the singleton Semantic Model metadata service. */
+  public static SemanticModelMetaService getInstance() {
+    return INSTANCE;
+  }
+
+  private SemanticModelMetaService() {
+    this.ops = new HierarchicalConversionPOStorageOps<>(new SemanticModelPOStorageOps());
+  }
+
+  /**
+   * Resolves a Semantic Model stable ID by schema ID and name.
+   *
+   * @param schemaId The parent schema ID.
+   * @param semanticModelName The Semantic Model name.
+   * @return The stable Semantic Model ID.
+   * @throws NoSuchEntityException If the Semantic Model does not exist.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "getSemanticModelIdBySchemaIdAndName")
+  public Long getSemanticModelIdBySchemaIdAndName(long schemaId, String semanticModelName) {
+    Long semanticModelId =
+        SessionUtils.getWithoutCommit(
+            SemanticModelMetaMapper.class,
+            mapper -> mapper.selectSemanticModelIdBySchemaIdAndName(schemaId, semanticModelName));
+    if (semanticModelId == null) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.SEMANTIC_MODEL.name().toLowerCase(Locale.ROOT),
+          semanticModelName);
+    }
+    return semanticModelId;
+  }
+
+  /**
+   * Loads the current Semantic Model by identifier.
+   *
+   * @param identifier The Semantic Model identifier.
+   * @return The current Semantic Model entity.
+   * @throws NoSuchEntityException If the Semantic Model does not exist.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "getSemanticModelByIdentifier")
+  public SemanticModelEntity getSemanticModelByIdentifier(NameIdentifier identifier) {
+    SemanticModelPO semanticModelPO = getSemanticModelPOByIdentifier(identifier);
+    return fromSemanticModelPO(semanticModelPO, identifier.namespace());
+  }
+
+  /**
+   * Inserts a Semantic Model identity and its version-one snapshot atomically.
+   *
+   * @param semanticModelEntity The Semantic Model entity.
+   * @param overwrite Whether to overwrite rows for the same stable ID or natural key.
+   * @throws IOException If relational persistence fails.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "insertSemanticModel")
+  public void insertSemanticModel(SemanticModelEntity semanticModelEntity, boolean overwrite)
+      throws IOException {
+    NameIdentifierUtil.checkSemanticModel(semanticModelEntity.nameIdentifier());
+    try {
+      SemanticModelPO po =
+          initializeSemanticModelPO(semanticModelEntity, SemanticModelPO.builder());
+      AtomicReference<SemanticModelPO> persistedPO = new AtomicReference<>();
+      AtomicReference<SemanticModelVersionInfoPO> persistedVersionInfoPO =
+          new AtomicReference<>(po.getSemanticModelVersionInfoPO());
+      SessionUtils.doMultipleWithCommit(
+          () ->
+              SchemaMetaService.getInstance()
+                  .lockSchemaForEntityWrite(
+                      semanticModelEntity.nameIdentifier(),
+                      po.getSchemaId(),
+                      po.getCatalogId(),
+                      po.getMetalakeId()),
+          () ->
+              SessionUtils.doWithoutCommit(
+                  SemanticModelMetaMapper.class,
+                  mapper -> {
+                    if (overwrite) {
+                      Long persistedId =
+                          mapper.selectSemanticModelIdBySchemaIdAndName(
+                              po.getSchemaId(), po.getSemanticModelName());
+                      SemanticModelPO existingPO =
+                          mapper.selectSemanticModelMetaByIdForUpdate(
+                              persistedId == null ? po.getSemanticModelId() : persistedId);
+                      persistedPO.set(existingPO);
+                      if (existingPO != null) {
+                        persistedVersionInfoPO.set(
+                            versionInfoForOverwrite(
+                                po.getSemanticModelVersionInfoPO(), existingPO));
+                      }
+                    }
+                    ops.insertPO(
+                        mapper,
+                        persistedPO.get() == null
+                            ? po
+                            : identityForOverwrite(po, persistedPO.get()),
+                        overwrite);
+                  }),
+          () ->
+              SessionUtils.doWithoutCommit(
+                  SemanticModelVersionInfoMapper.class,
+                  mapper -> {
+                    if (overwrite) {
+                      mapper.insertSemanticModelVersionInfoOnDuplicateKeyUpdate(
+                          persistedVersionInfoPO.get());
+                    } else {
+                      mapper.insertSemanticModelVersionInfo(po.getSemanticModelVersionInfoPO());
+                    }
+                  }));
+    } catch (RuntimeException re) {
+      ExceptionUtils.checkSQLException(
+          re, Entity.EntityType.SEMANTIC_MODEL, semanticModelEntity.nameIdentifier().toString());
+      throw re;
+    }
+  }
+
+  /** Returns the persistent-object operations used by this service. */
+  public BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> ops() {
+    return ops;
+  }
+
+  private static SemanticModelPO identityForOverwrite(
+      SemanticModelPO source, SemanticModelPO persistedPO) {
+    return SemanticModelPO.builder()
+        .withSemanticModelId(persistedPO.getSemanticModelId())
+        .withSemanticModelName(source.getSemanticModelName())
+        .withMetalakeId(source.getMetalakeId())
+        .withCatalogId(source.getCatalogId())
+        .withSchemaId(source.getSchemaId())
+        .withAuditInfo(source.getAuditInfo())
+        .withCurrentVersion(source.getCurrentVersion())

Review Comment:
   Fixed. Overwrites now derive one `nextVersion` from the persisted current and last versions and use it for both the identity row and version snapshot.



##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetaService.java:
##########
@@ -0,0 +1,226 @@
+/*
+ * 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.storage.relational.service;
+
+import static org.apache.gravitino.metrics.source.MetricsSource.GRAVITINO_RELATIONAL_STORE_METRIC_NAME;
+import static org.apache.gravitino.storage.relational.po.SemanticModelPO.fromSemanticModelPO;
+import static org.apache.gravitino.storage.relational.po.SemanticModelPO.initializeSemanticModelPO;
+
+import com.google.common.base.Preconditions;
+import java.io.IOException;
+import java.util.Locale;
+import java.util.concurrent.atomic.AtomicReference;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.meta.SemanticModelEntity;
+import org.apache.gravitino.metrics.Monitored;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelVersionInfoMapper;
+import org.apache.gravitino.storage.relational.po.SemanticModelPO;
+import org.apache.gravitino.storage.relational.po.SemanticModelVersionInfoPO;
+import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.gravitino.utils.NameIdentifierUtil;
+
+/** Provides relational create and load operations for Semantic Model metadata. */
+public class SemanticModelMetaService {
+
+  private static final SemanticModelMetaService INSTANCE = new SemanticModelMetaService();
+
+  private final BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> ops;
+
+  /** Returns the singleton Semantic Model metadata service. */
+  public static SemanticModelMetaService getInstance() {
+    return INSTANCE;
+  }
+
+  private SemanticModelMetaService() {
+    this.ops = new HierarchicalConversionPOStorageOps<>(new SemanticModelPOStorageOps());
+  }
+
+  /**
+   * Resolves a Semantic Model stable ID by schema ID and name.
+   *
+   * @param schemaId The parent schema ID.
+   * @param semanticModelName The Semantic Model name.
+   * @return The stable Semantic Model ID.
+   * @throws NoSuchEntityException If the Semantic Model does not exist.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "getSemanticModelIdBySchemaIdAndName")
+  public Long getSemanticModelIdBySchemaIdAndName(long schemaId, String semanticModelName) {
+    Long semanticModelId =
+        SessionUtils.getWithoutCommit(
+            SemanticModelMetaMapper.class,
+            mapper -> mapper.selectSemanticModelIdBySchemaIdAndName(schemaId, semanticModelName));
+    if (semanticModelId == null) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.SEMANTIC_MODEL.name().toLowerCase(Locale.ROOT),
+          semanticModelName);
+    }
+    return semanticModelId;
+  }
+
+  /**
+   * Loads the current Semantic Model by identifier.
+   *
+   * @param identifier The Semantic Model identifier.
+   * @return The current Semantic Model entity.
+   * @throws NoSuchEntityException If the Semantic Model does not exist.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "getSemanticModelByIdentifier")
+  public SemanticModelEntity getSemanticModelByIdentifier(NameIdentifier identifier) {
+    SemanticModelPO semanticModelPO = getSemanticModelPOByIdentifier(identifier);
+    return fromSemanticModelPO(semanticModelPO, identifier.namespace());
+  }
+
+  /**
+   * Inserts a Semantic Model identity and its version-one snapshot atomically.
+   *
+   * @param semanticModelEntity The Semantic Model entity.
+   * @param overwrite Whether to overwrite rows for the same stable ID or natural key.
+   * @throws IOException If relational persistence fails.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "insertSemanticModel")
+  public void insertSemanticModel(SemanticModelEntity semanticModelEntity, boolean overwrite)
+      throws IOException {
+    NameIdentifierUtil.checkSemanticModel(semanticModelEntity.nameIdentifier());
+    try {
+      SemanticModelPO po =
+          initializeSemanticModelPO(semanticModelEntity, SemanticModelPO.builder());
+      AtomicReference<SemanticModelPO> persistedPO = new AtomicReference<>();
+      AtomicReference<SemanticModelVersionInfoPO> persistedVersionInfoPO =
+          new AtomicReference<>(po.getSemanticModelVersionInfoPO());
+      SessionUtils.doMultipleWithCommit(
+          () ->
+              SchemaMetaService.getInstance()
+                  .lockSchemaForEntityWrite(
+                      semanticModelEntity.nameIdentifier(),
+                      po.getSchemaId(),
+                      po.getCatalogId(),
+                      po.getMetalakeId()),
+          () ->
+              SessionUtils.doWithoutCommit(
+                  SemanticModelMetaMapper.class,
+                  mapper -> {
+                    if (overwrite) {
+                      Long persistedId =

Review Comment:
   Fixed. Removed the separate ID lookup and duplicated upsert version bump. The overwrite path now uses one natural-key locking read followed by a version-checked update, sharing the same `nextVersion` with the snapshot insert.



##########
core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelDefinitionSerDe.java:
##########
@@ -0,0 +1,265 @@
+/*
+ * 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.storage.relational.po;
+
+import com.fasterxml.jackson.annotation.JsonAutoDetect;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.PropertyAccessor;
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.JsonToken;
+import com.fasterxml.jackson.databind.DeserializationContext;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonDeserializer;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.JsonSerializer;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.PropertyNamingStrategies;
+import com.fasterxml.jackson.databind.SerializerProvider;
+import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
+import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
+import com.fasterxml.jackson.databind.cfg.JsonNodeFeature;
+import com.fasterxml.jackson.databind.module.SimpleModule;
+import com.google.common.base.CaseFormat;
+import java.io.IOException;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.json.JsonUtils;
+import org.apache.gravitino.semantic.AIContext;
+import org.apache.gravitino.semantic.AIContextObject;
+import org.apache.gravitino.semantic.CustomExtension;
+import org.apache.gravitino.semantic.DataType;
+import org.apache.gravitino.semantic.Dataset;
+import org.apache.gravitino.semantic.DialectExpression;
+import org.apache.gravitino.semantic.Dimension;
+import org.apache.gravitino.semantic.Expression;
+import org.apache.gravitino.semantic.Field;
+import org.apache.gravitino.semantic.Metric;
+import org.apache.gravitino.semantic.Relationship;
+import org.apache.gravitino.semantic.SemanticModelDefinition;
+
+/**
+ * Serializes immutable Semantic Model API values for relational storage without depending on REST
+ * DTOs.
+ */
+final class SemanticModelDefinitionSerDe {
+
+  private static final ObjectMapper MAPPER = createMapper();
+
+  private SemanticModelDefinitionSerDe() {}
+
+  static String serialize(SemanticModelDefinition definition) throws JsonProcessingException {
+    return MAPPER.writeValueAsString(definition);
+  }
+
+  static SemanticModelDefinition deserialize(String json) throws JsonProcessingException {
+    return MAPPER.readValue(json, SemanticModelDefinition.class);
+  }
+
+  private static ObjectMapper createMapper() {
+    SimpleModule module =
+        new SimpleModule()
+            .addSerializer(AIContext.class, new AIContextSerializer())
+            .addDeserializer(AIContext.class, new AIContextDeserializer())
+            .addSerializer(DataType.class, new DataTypeSerializer())
+            .addDeserializer(DataType.class, new DataTypeDeserializer())
+            .addSerializer(NameIdentifier.class, new JsonUtils.NameIdentifierSerializer())
+            .addDeserializer(NameIdentifier.class, new JsonUtils.NameIdentifierDeserializer());
+
+    ObjectMapper mapper =
+        JsonUtils.anyFieldMapper()
+            .copy()
+            .setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE)
+            .setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE)
+            .setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE)
+            .setDefaultPropertyInclusion(
+                JsonInclude.Value.construct(
+                    JsonInclude.Include.NON_NULL, JsonInclude.Include.ALWAYS))
+            .configure(JsonNodeFeature.STRIP_TRAILING_BIGDECIMAL_ZEROES, false)
+            .enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)
+            .enable(DeserializationFeature.USE_BIG_INTEGER_FOR_INTS)
+            .registerModule(module);
+    addBuilderMixIns(
+        mapper,
+        SemanticModelDefinition.class,
+        SemanticModelDefinitionMixIn.class,
+        SemanticModelDefinition.Builder.class);
+    addBuilderMixIns(mapper, Dataset.class, DatasetMixIn.class, Dataset.Builder.class);
+    addBuilderMixIns(
+        mapper, Relationship.class, RelationshipMixIn.class, Relationship.Builder.class);
+    addBuilderMixIns(mapper, Metric.class, MetricMixIn.class, Metric.Builder.class);
+    addBuilderMixIns(mapper, Field.class, FieldMixIn.class, Field.Builder.class);
+    addBuilderMixIns(mapper, Expression.class, ExpressionMixIn.class, Expression.Builder.class);
+    addBuilderMixIns(
+        mapper,
+        DialectExpression.class,
+        DialectExpressionMixIn.class,
+        DialectExpression.Builder.class);
+    addBuilderMixIns(mapper, Dimension.class, DimensionMixIn.class, Dimension.Builder.class);
+    addBuilderMixIns(
+        mapper, CustomExtension.class, CustomExtensionMixIn.class, CustomExtension.Builder.class);
+    return mapper;
+  }
+
+  private static void addBuilderMixIns(
+      ObjectMapper mapper, Class<?> valueClass, Class<?> mixInClass, Class<?> builderClass) {
+    mapper.addMixIn(valueClass, mixInClass);
+    mapper.addMixIn(builderClass, BuilderMixIn.class);
+  }
+
+  @JsonPOJOBuilder(withPrefix = "with")
+  private abstract static class BuilderMixIn {}
+
+  @JsonDeserialize(builder = SemanticModelDefinition.Builder.class)
+  private abstract static class SemanticModelDefinitionMixIn {}
+
+  @JsonDeserialize(builder = Dataset.Builder.class)
+  private abstract static class DatasetMixIn {}
+
+  @JsonDeserialize(builder = Relationship.Builder.class)
+  private abstract static class RelationshipMixIn {}
+
+  @JsonDeserialize(builder = Metric.Builder.class)
+  private abstract static class MetricMixIn {}
+
+  @JsonDeserialize(builder = Field.Builder.class)
+  private abstract static class FieldMixIn {}
+
+  @JsonDeserialize(builder = Expression.Builder.class)
+  private abstract static class ExpressionMixIn {}
+
+  @JsonDeserialize(builder = DialectExpression.Builder.class)
+  private abstract static class DialectExpressionMixIn {}
+
+  @JsonDeserialize(builder = Dimension.Builder.class)
+  private abstract static class DimensionMixIn {}
+
+  @JsonDeserialize(builder = CustomExtension.Builder.class)
+  private abstract static class CustomExtensionMixIn {}
+
+  private static final class AIContextSerializer extends JsonSerializer<AIContext> {

Review Comment:
   Fixed. Removed `SemanticModelDefinitionSerDe` and now serialize and deserialize through `SemanticModelDefinitionDTO` in `SemanticModelPO`.



-- 
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] [#12600] feat(store): Add Semantic Model create and load persistence [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/SemanticModelVersionInfoPostgreSQLProvider.java:
##########
@@ -0,0 +1,41 @@
+/*
+ * 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.storage.relational.mapper.provider.postgresql;
+
+import org.apache.gravitino.storage.relational.mapper.provider.base.SemanticModelVersionInfoBaseSQLProvider;
+import org.apache.gravitino.storage.relational.po.SemanticModelVersionInfoPO;
+import org.apache.ibatis.annotations.Param;
+
+/** Provides PostgreSQL SQL for creating Semantic Model version snapshots. */
+public class SemanticModelVersionInfoPostgreSQLProvider
+    extends SemanticModelVersionInfoBaseSQLProvider {
+
+  @Override
+  public String insertSemanticModelVersionInfoOnDuplicateKeyUpdate(
+      @Param("semanticModelVersionInfo") SemanticModelVersionInfoPO versionInfoPO) {
+    return insertSemanticModelVersionInfo(versionInfoPO)
+        + " ON CONFLICT (semantic_model_id, version, deleted_at) DO UPDATE SET"
+        + " semantic_model_name = #{semanticModelVersionInfo.semanticModelName},"
+        + " semantic_model_comment = #{semanticModelVersionInfo.semanticModelComment},"
+        + " semantic_model_definition = #{semanticModelVersionInfo.semanticModelDefinition},"
+        + " properties = #{semanticModelVersionInfo.properties},"
+        + " audit_info = #{semanticModelVersionInfo.auditInfo},"
+        + " deleted_at = #{semanticModelVersionInfo.deletedAt}";

Review Comment:
   A row reaches `DO UPDATE` only when its existing `(semantic_model_id, version, deleted_at)` values match the incoming conflict key. Therefore, the assigned `deleted_at` value is necessarily equal to the existing value; if it differs, this conflict target is not matched and the update is not executed. This also follows the existing PostgreSQL version-provider pattern used by tables, views, functions, policies, and filesets. The assignment is redundant but cannot cause the described uniqueness violation, so I am keeping it for consistency.



-- 
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] [#12600] feat(store): Add Semantic Model create and load persistence [gravitino]

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

   <!-- coverage-report -->
   ### Code Coverage Report
   |Overall Project|68.18% **`+0.28%`**|:green_circle:|
   |:-|:-|:-:|
   |Files changed|82.96%|:green_circle:|
   <br>
   
   |Module|Coverage||
   |:-|:-|:-:|
   |aliyun|19.74%|:red_circle:|
   |api|52.94%|: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.02%|: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|59.35%|:green_circle:|
   |catalog-lakehouse-hudi|79.1%|:green_circle:|
   |catalog-lakehouse-iceberg|85.93%|:green_circle:|
   |catalog-lakehouse-paimon|84.26%|:green_circle:|
   |catalog-model|77.99%|:green_circle:|
   |cli|44.48%|:green_circle:|
   |client-java|78.07%|:green_circle:|
   |common|52.29%|:green_circle:|
   |core|83.4% **`-0.03%`**|: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.38%|:green_circle:|
   |idp-basic|85.98%|:green_circle:|
   |integration-test-common|0.0%|:red_circle:|
   |jobs|62.92%|:green_circle:|
   |lance-common|32.81%|:red_circle:|
   |lance-rest-server|64.78%|:green_circle:|
   |lineage|53.02%|:green_circle:|
   |optimizer|83.24%|:green_circle:|
   |optimizer-api|21.95%|:red_circle:|
   |server|87.51%|:green_circle:|
   |server-common|79.59%|:green_circle:|
   |spark|28.57%|:red_circle:|
   |spark-common|48.92%|:green_circle:|
   |tencent|69.84%|:green_circle:|
   |trino-connector|47.41%|:green_circle:|
   
   <details>
   <summary>Files</summary>
   
   |Module|File|Coverage||
   |:-|:-|:-|:-:|
   |core|[Entity.java](https://github.com/mchades/gravitino/blob/52dab59c39bc5579a293618cf0b46c54fe7d8726/core/src/main/java/org/apache/gravitino/Entity.java)|100.0%|:green_circle:|
   ||[DefaultMapperPackageProvider.java](https://github.com/mchades/gravitino/blob/52dab59c39bc5579a293618cf0b46c54fe7d8726/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/DefaultMapperPackageProvider.java)|100.0%|:green_circle:|
   ||[SchemaMetaService.java](https://github.com/mchades/gravitino/blob/52dab59c39bc5579a293618cf0b46c54fe7d8726/core/src/main/java/org/apache/gravitino/storage/relational/service/SchemaMetaService.java)|97.59%|:green_circle:|
   ||[SemanticModelEntity.java](https://github.com/mchades/gravitino/blob/52dab59c39bc5579a293618cf0b46c54fe7d8726/core/src/main/java/org/apache/gravitino/meta/SemanticModelEntity.java)|97.14%|:green_circle:|
   ||[BaseEntityCache.java](https://github.com/mchades/gravitino/blob/52dab59c39bc5579a293618cf0b46c54fe7d8726/core/src/main/java/org/apache/gravitino/cache/BaseEntityCache.java)|92.31%|:green_circle:|
   ||[SemanticModelPO.java](https://github.com/mchades/gravitino/blob/52dab59c39bc5579a293618cf0b46c54fe7d8726/core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelPO.java)|92.0%|:green_circle:|
   ||[SemanticModelDefinitionSerDe.java](https://github.com/mchades/gravitino/blob/52dab59c39bc5579a293618cf0b46c54fe7d8726/core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelDefinitionSerDe.java)|89.16%|:green_circle:|
   ||[NamespaceUtil.java](https://github.com/mchades/gravitino/blob/52dab59c39bc5579a293618cf0b46c54fe7d8726/core/src/main/java/org/apache/gravitino/utils/NamespaceUtil.java)|88.41%|:green_circle:|
   ||[SemanticModelMetaService.java](https://github.com/mchades/gravitino/blob/52dab59c39bc5579a293618cf0b46c54fe7d8726/core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetaService.java)|87.1%|:green_circle:|
   ||[JDBCBackend.java](https://github.com/mchades/gravitino/blob/52dab59c39bc5579a293618cf0b46c54fe7d8726/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java)|84.48%|:green_circle:|
   ||[SemanticModelVersionInfoSQLProviderFactory.java](https://github.com/mchades/gravitino/blob/52dab59c39bc5579a293618cf0b46c54fe7d8726/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelVersionInfoSQLProviderFactory.java)|83.33%|:green_circle:|
   ||[RelationalEntityStoreIdResolver.java](https://github.com/mchades/gravitino/blob/52dab59c39bc5579a293618cf0b46c54fe7d8726/core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStoreIdResolver.java)|78.9%|:green_circle:|
   ||[SemanticModelVersionInfoPO.java](https://github.com/mchades/gravitino/blob/52dab59c39bc5579a293618cf0b46c54fe7d8726/core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelVersionInfoPO.java)|75.61%|:green_circle:|
   ||[NameIdentifierUtil.java](https://github.com/mchades/gravitino/blob/52dab59c39bc5579a293618cf0b46c54fe7d8726/core/src/main/java/org/apache/gravitino/utils/NameIdentifierUtil.java)|74.06%|:green_circle:|
   ||[SemanticModelMetaSQLProviderFactory.java](https://github.com/mchades/gravitino/blob/52dab59c39bc5579a293618cf0b46c54fe7d8726/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelMetaSQLProviderFactory.java)|68.75%|:green_circle:|
   ||[SemanticModelVersionInfoBaseSQLProvider.java](https://github.com/mchades/gravitino/blob/52dab59c39bc5579a293618cf0b46c54fe7d8726/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SemanticModelVersionInfoBaseSQLProvider.java)|66.67%|:green_circle:|
   ||[MetadataObjectUtil.java](https://github.com/mchades/gravitino/blob/52dab59c39bc5579a293618cf0b46c54fe7d8726/core/src/main/java/org/apache/gravitino/utils/MetadataObjectUtil.java)|58.33%|:red_circle:|
   ||[SemanticModelMetaPostgreSQLProvider.java](https://github.com/mchades/gravitino/blob/52dab59c39bc5579a293618cf0b46c54fe7d8726/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/SemanticModelMetaPostgreSQLProvider.java)|50.0%|:red_circle:|
   ||[SemanticModelVersionInfoPostgreSQLProvider.java](https://github.com/mchades/gravitino/blob/52dab59c39bc5579a293618cf0b46c54fe7d8726/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/SemanticModelVersionInfoPostgreSQLProvider.java)|50.0%|:red_circle:|
   ||[SemanticModelMetaBaseSQLProvider.java](https://github.com/mchades/gravitino/blob/52dab59c39bc5579a293618cf0b46c54fe7d8726/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SemanticModelMetaBaseSQLProvider.java)|42.86%|:red_circle:|
   ||[SemanticModelPOStorageOps.java](https://github.com/mchades/gravitino/blob/52dab59c39bc5579a293618cf0b46c54fe7d8726/core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelPOStorageOps.java)|27.27%|:red_circle:|
   ||[SemanticModelMetaMapper.java](https://github.com/mchades/gravitino/blob/52dab59c39bc5579a293618cf0b46c54fe7d8726/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelMetaMapper.java)|0.0%|:red_circle:|
   ||[SemanticModelVersionInfoMapper.java](https://github.com/mchades/gravitino/blob/52dab59c39bc5579a293618cf0b46c54fe7d8726/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelVersionInfoMapper.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] [#12600] feat(store): Add Semantic Model create and load persistence [gravitino]

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

   @jerryshao @yuqi1129 All comments resolved, please help to review again, thanks!


-- 
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] [#12600] feat(store): Add Semantic Model create and load persistence [gravitino]

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


##########
core/src/test/java/org/apache/gravitino/storage/relational/TestSemanticModelJDBCBackend.java:
##########
@@ -0,0 +1,259 @@
+/*
+ * 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.storage.relational;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import com.google.common.collect.ImmutableMap;
+import java.io.IOException;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.List;
+import java.util.Map;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.EntityAlreadyExistsException;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.meta.SemanticModelEntity;
+import org.apache.gravitino.semantic.AIContext;
+import org.apache.gravitino.semantic.AIContextObject;
+import org.apache.gravitino.semantic.CustomExtension;
+import org.apache.gravitino.semantic.DataType;
+import org.apache.gravitino.semantic.Dataset;
+import org.apache.gravitino.semantic.DialectExpression;
+import org.apache.gravitino.semantic.Dimension;
+import org.apache.gravitino.semantic.Expression;
+import org.apache.gravitino.semantic.Field;
+import org.apache.gravitino.semantic.Metric;
+import org.apache.gravitino.semantic.Relationship;
+import org.apache.gravitino.semantic.SemanticModelDefinition;
+import org.apache.gravitino.storage.RandomIdGenerator;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelVersionInfoMapper;
+import org.apache.gravitino.storage.relational.po.SemanticModelPO;
+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.gravitino.utils.NamespaceUtil;
+import org.apache.ibatis.session.SqlSession;
+import org.junit.jupiter.api.TestTemplate;
+
+/** Tests Semantic Model create and load persistence through {@link JDBCBackend}. */
+public class TestSemanticModelJDBCBackend extends TestJDBCBackend {
+
+  @TestTemplate
+  public void testCreateAndLoadRoundTrip() throws IOException {
+    Namespace namespace = createParents("round_trip");
+    SemanticModelEntity absent =
+        semanticModel(
+            RandomIdGenerator.INSTANCE.nextId(),
+            namespace,
+            "absent_optional_model",
+            false,
+            ImmutableMap.of("domain", "sales"));
+    SemanticModelEntity empty =
+        semanticModel(
+            RandomIdGenerator.INSTANCE.nextId(),
+            namespace,
+            "empty_optional_model",
+            true,
+            ImmutableMap.of());
+
+    backend.insert(absent, false);
+    backend.insert(empty, false);
+
+    SemanticModelEntity loadedAbsent =
+        backend.get(absent.nameIdentifier(), Entity.EntityType.SEMANTIC_MODEL);
+    SemanticModelEntity loadedEmpty =
+        backend.get(empty.nameIdentifier(), Entity.EntityType.SEMANTIC_MODEL);
+
+    assertEquals(absent, loadedAbsent);
+    assertEquals(empty, loadedEmpty);
+    assertNull(loadedAbsent.definition().relationships());
+    assertNull(loadedAbsent.definition().metrics());
+    assertEquals(0, loadedEmpty.definition().relationships().length);
+    assertEquals(0, loadedEmpty.definition().metrics().length);
+    assertTrue(loadedEmpty.properties().isEmpty());
+    assertEquals(
+        new BigDecimal("1.50"),
+        loadedAbsent.definition().aiContext().object().additionalProperties().get("threshold"));
+    assertNull(loadedAbsent.definition().aiContext().object().examples());
+    assertEquals(0, loadedAbsent.definition().aiContext().object().synonyms().length);
+  }
+
+  @TestTemplate
+  public void testDuplicateAndMissingEntities() throws IOException {
+    Namespace namespace = createParents("duplicate");
+    SemanticModelEntity original =
+        semanticModel(
+            RandomIdGenerator.INSTANCE.nextId(),
+            namespace,
+            "sales_model",
+            false,
+            ImmutableMap.of("owner", "analytics"));
+    backend.insert(original, false);
+
+    SemanticModelEntity duplicate =
+        semanticModel(
+            RandomIdGenerator.INSTANCE.nextId(),
+            namespace,
+            original.name(),
+            true,
+            ImmutableMap.of());
+    assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(duplicate, false));
+    assertEquals(
+        original, backend.get(original.nameIdentifier(), Entity.EntityType.SEMANTIC_MODEL));
+
+    NameIdentifier missingModel = NameIdentifier.of(namespace, "missing_model");
+    assertThrows(
+        NoSuchEntityException.class,
+        () -> backend.get(missingModel, Entity.EntityType.SEMANTIC_MODEL));
+
+    String suffix = Long.toUnsignedString(RandomIdGenerator.INSTANCE.nextId());
+    String metalakeName = "missing_parent_metalake_" + suffix;
+    String catalogName = "missing_parent_catalog_" + suffix;
+    createAndInsertMakeLake(metalakeName);
+    createAndInsertCatalog(metalakeName, catalogName);
+    Namespace missingParentNamespace =
+        NamespaceUtil.ofSemanticModel(metalakeName, catalogName, "missing_schema");
+    SemanticModelEntity missingParent =
+        semanticModel(
+            RandomIdGenerator.INSTANCE.nextId(),
+            missingParentNamespace,
+            "orphan_model",
+            false,
+            ImmutableMap.of());
+
+    assertThrows(NoSuchEntityException.class, () -> backend.insert(missingParent, false));
+    assertEquals(0, countRows("semantic_model_meta", missingParent.id()));
+    assertEquals(0, countRows("semantic_model_version_info", missingParent.id()));
+  }
+
+  @TestTemplate
+  public void testCreateRollsBackIdentityWhenSnapshotInsertFails() throws IOException {
+    Namespace namespace = createParents("transaction");
+    SemanticModelEntity semanticModel =
+        semanticModel(
+            RandomIdGenerator.INSTANCE.nextId(),
+            namespace,
+            "transaction_model",
+            false,
+            ImmutableMap.of("domain", "finance"));
+    SemanticModelPO po =
+        SemanticModelPO.initializeSemanticModelPO(semanticModel, SemanticModelPO.builder());
+    SessionUtils.doWithCommit(
+        SemanticModelVersionInfoMapper.class,
+        mapper -> mapper.insertSemanticModelVersionInfo(po.getSemanticModelVersionInfoPO()));
+
+    assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(semanticModel, false));
+    assertEquals(0, countRows("semantic_model_meta", semanticModel.id()));
+    assertEquals(1, countRows("semantic_model_version_info", semanticModel.id()));
+  }
+
+  private Namespace createParents(String prefix) throws IOException {
+    String suffix = Long.toUnsignedString(RandomIdGenerator.INSTANCE.nextId());
+    String metalakeName = prefix + "_metalake_" + suffix;
+    String catalogName = prefix + "_catalog_" + suffix;
+    String schemaName = prefix + "_schema_" + suffix;
+    createAndInsertMakeLake(metalakeName);
+    createAndInsertCatalog(metalakeName, catalogName);
+    createAndInsertSchema(metalakeName, catalogName, schemaName);
+    return NamespaceUtil.ofSemanticModel(metalakeName, catalogName, schemaName);
+  }
+
+  private SemanticModelEntity semanticModel(
+      Long id,
+      Namespace namespace,
+      String name,
+      boolean explicitEmpty,
+      Map<String, String> properties) {
+    AIContextObject context =
+        AIContextObject.builder()
+            .withInstructions("Use certified sales definitions")
+            .withSynonyms(new String[0])
+            .withAdditionalProperties(
+                Map.of("threshold", new BigDecimal("1.50"), "nested", List.of(new BigInteger("3"))))
+            .build();
+    Field field =
+        Field.builder()
+            .withName("ordered_at")
+            .withExpression(
+                Expression.builder()
+                    .withDialects(
+                        new DialectExpression[] {
+                          DialectExpression.builder()
+                              .withDialect("ansi")
+                              .withExpression("ordered_at")
+                              .build()
+                        })
+                    .build())
+            .withDimension(Dimension.builder().withIsTime(true).build())
+            .withDatatype(DataType.DATE_TIME_TZ)
+            .build();
+    Dataset dataset =
+        Dataset.builder()
+            .withName("orders")
+            .withSource(NameIdentifier.of("sales", "mart", "orders"))
+            .withPrimaryKey(new String[0])
+            .withFields(new Field[] {field})
+            .build();
+    SemanticModelDefinition.Builder definitionBuilder =
+        SemanticModelDefinition.builder()
+            .withAIContext(AIContext.of(context))
+            .withDatasets(new Dataset[] {dataset});
+    if (explicitEmpty) {
+      definitionBuilder
+          .withRelationships(new Relationship[0])
+          .withMetrics(new Metric[0])
+          .withCustomExtensions(new CustomExtension[0]);
+    }
+
+    return SemanticModelEntity.builder()
+        .withId(id)
+        .withName(name)
+        .withNamespace(namespace)
+        .withComment(explicitEmpty ? null : "Governed sales definitions")
+        .withDefinition(definitionBuilder.build())
+        .withProperties(properties)
+        .withAuditInfo(AUDIT_INFO)
+        .build();
+  }
+
+  private int countRows(String tableName, Long semanticModelId) {
+    String sql =
+        String.format(
+            "SELECT count(*) FROM %s WHERE semantic_model_id = %d", tableName, semanticModelId);
+    try (SqlSession sqlSession =
+            SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);
+        Connection connection = sqlSession.getConnection();
+        Statement statement = connection.createStatement();
+        ResultSet resultSet = statement.executeQuery(sql)) {

Review Comment:
   Thanks for pointing this out. The helper now binds `semanticModelId` with a `PreparedStatement`, uses the mapper table-name constants, and rejects any table outside the two Semantic Model tables used by this test.



-- 
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] [#12600] feat(store): Add Semantic Model create and load persistence [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelPOStorageOps.java:
##########
@@ -0,0 +1,81 @@
+/*
+ * 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.storage.relational.service;
+
+import java.util.Locale;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;
+import org.apache.gravitino.storage.relational.po.SemanticModelPO;
+
+/** Provides relational persistent-object operations required to create and load Semantic Models. */
+public class SemanticModelPOStorageOps
+    extends BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> {
+
+  /** Creates Semantic Model persistent-object operations. */
+  public SemanticModelPOStorageOps() {}
+
+  @Override
+  public void insertPO(
+      SemanticModelMetaMapper mapper, SemanticModelPO semanticModelPO, boolean overwrite) {
+    if (overwrite) {
+      mapper.insertSemanticModelMetaOnDuplicateKeyUpdate(semanticModelPO);
+    } else {
+      mapper.insertSemanticModelMeta(semanticModelPO);
+    }
+  }
+
+  @Override
+  public SemanticModelPO getPO(
+      SemanticModelMetaMapper mapper, Long parentId, String semanticModelName) {
+    return mapper.selectSemanticModelMetaBySchemaIdAndName(parentId, semanticModelName);
+  }
+
+  @Override
+  public SemanticModelPO getPOByFullName(
+      SemanticModelMetaMapper mapper, NameIdentifier identifier) {
+    Namespace namespace = identifier.namespace();
+    SemanticModelPO po =
+        mapper.selectSemanticModelByFullQualifiedName(
+            namespace.level(0), namespace.level(1), namespace.level(2), identifier.name());
+    if (po == null) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,

Review Comment:
   This is the same concern discussed in the [earlier thread](https://github.com/apache/gravitino/pull/12602#discussion_r3861564625). The current behavior matches the existing Schema, Table, and View full-name lookups, as well as the cache-enabled parent-ID resolution path. Changing only the Semantic Model query would make the exception classification depend on the entity type and `gravitino.cache.enabled`. I am keeping the existing behavior in this PR; distinguishing missing metalakes from missing catalogs should be handled consistently across the relational lookup paths.



-- 
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] [#12600] feat(store): Add Semantic Model create and load persistence [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetaService.java:
##########
@@ -0,0 +1,161 @@
+/*
+ * 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.storage.relational.service;
+
+import static org.apache.gravitino.metrics.source.MetricsSource.GRAVITINO_RELATIONAL_STORE_METRIC_NAME;
+import static org.apache.gravitino.storage.relational.po.SemanticModelPO.fromSemanticModelPO;
+import static org.apache.gravitino.storage.relational.po.SemanticModelPO.initializeSemanticModelPO;
+
+import java.io.IOException;
+import java.util.Locale;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.meta.SemanticModelEntity;
+import org.apache.gravitino.metrics.Monitored;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelVersionInfoMapper;
+import org.apache.gravitino.storage.relational.po.SemanticModelPO;
+import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.gravitino.utils.NameIdentifierUtil;
+
+/** Provides relational create and load operations for Semantic Model metadata. */
+public class SemanticModelMetaService {
+
+  private static final SemanticModelMetaService INSTANCE = new SemanticModelMetaService();
+
+  private final BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> ops;
+
+  /** Returns the singleton Semantic Model metadata service. */
+  public static SemanticModelMetaService getInstance() {
+    return INSTANCE;
+  }
+
+  private SemanticModelMetaService() {
+    this.ops = new HierarchicalConversionPOStorageOps<>(new SemanticModelPOStorageOps());
+  }
+
+  /**
+   * Resolves a Semantic Model stable ID by schema ID and name.
+   *
+   * @param schemaId The parent schema ID.
+   * @param semanticModelName The Semantic Model name.
+   * @return The stable Semantic Model ID.
+   * @throws NoSuchEntityException If the Semantic Model does not exist.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "getSemanticModelIdBySchemaIdAndName")
+  public Long getSemanticModelIdBySchemaIdAndName(long schemaId, String semanticModelName) {
+    Long semanticModelId =
+        SessionUtils.getWithoutCommit(
+            SemanticModelMetaMapper.class,
+            mapper -> mapper.selectSemanticModelIdBySchemaIdAndName(schemaId, semanticModelName));
+    if (semanticModelId == null) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.SEMANTIC_MODEL.name().toLowerCase(Locale.ROOT),
+          semanticModelName);
+    }
+    return semanticModelId;
+  }
+
+  /**
+   * Loads the current Semantic Model by identifier.
+   *
+   * @param identifier The Semantic Model identifier.
+   * @return The current Semantic Model entity.
+   * @throws NoSuchEntityException If the Semantic Model does not exist.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "getSemanticModelByIdentifier")
+  public SemanticModelEntity getSemanticModelByIdentifier(NameIdentifier identifier) {
+    SemanticModelPO semanticModelPO = getSemanticModelPOByIdentifier(identifier);
+    return fromSemanticModelPO(semanticModelPO, identifier.namespace());
+  }
+
+  /**
+   * Inserts a Semantic Model identity and its version-one snapshot atomically.
+   *
+   * @param semanticModelEntity The Semantic Model entity.
+   * @param overwrite Whether to overwrite rows for the same stable ID.
+   * @throws IOException If relational persistence fails.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "insertSemanticModel")
+  public void insertSemanticModel(SemanticModelEntity semanticModelEntity, boolean overwrite)
+      throws IOException {
+    NameIdentifierUtil.checkSemanticModel(semanticModelEntity.nameIdentifier());
+    try {
+      SemanticModelPO po =
+          initializeSemanticModelPO(semanticModelEntity, SemanticModelPO.builder());
+      SessionUtils.doMultipleWithCommit(
+          () ->
+              SchemaMetaService.getInstance()
+                  .lockSchemaForEntityWrite(
+                      semanticModelEntity.nameIdentifier(),
+                      po.getSchemaId(),
+                      po.getCatalogId(),
+                      po.getMetalakeId()),
+          () ->
+              SessionUtils.doWithoutCommit(
+                  SemanticModelMetaMapper.class, mapper -> ops.insertPO(mapper, po, overwrite)),
+          () ->
+              SessionUtils.doWithoutCommit(
+                  SemanticModelVersionInfoMapper.class,
+                  mapper -> {
+                    if (overwrite) {
+                      mapper.insertSemanticModelVersionInfoOnDuplicateKeyUpdate(

Review Comment:
   Have you increased the version for `SemanticModelVersion` when using replace syntax?



-- 
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] [#12600] feat(store): Add Semantic Model create and load persistence [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelDefinitionSerDe.java:
##########
@@ -0,0 +1,263 @@
+/*
+ * 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.storage.relational.po;
+
+import com.fasterxml.jackson.annotation.JsonAutoDetect;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.PropertyAccessor;
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.JsonToken;
+import com.fasterxml.jackson.databind.DeserializationContext;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonDeserializer;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.JsonSerializer;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.PropertyNamingStrategies;
+import com.fasterxml.jackson.databind.SerializerProvider;
+import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
+import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
+import com.fasterxml.jackson.databind.cfg.JsonNodeFeature;
+import com.fasterxml.jackson.databind.module.SimpleModule;
+import com.google.common.base.CaseFormat;
+import java.io.IOException;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.json.JsonUtils;
+import org.apache.gravitino.semantic.AIContext;
+import org.apache.gravitino.semantic.AIContextObject;
+import org.apache.gravitino.semantic.CustomExtension;
+import org.apache.gravitino.semantic.DataType;
+import org.apache.gravitino.semantic.Dataset;
+import org.apache.gravitino.semantic.DialectExpression;
+import org.apache.gravitino.semantic.Dimension;
+import org.apache.gravitino.semantic.Expression;
+import org.apache.gravitino.semantic.Field;
+import org.apache.gravitino.semantic.Metric;
+import org.apache.gravitino.semantic.Relationship;
+import org.apache.gravitino.semantic.SemanticModelDefinition;
+
+/**
+ * Serializes immutable Semantic Model API values for relational storage without depending on REST
+ * DTOs.
+ */
+final class SemanticModelDefinitionSerDe {
+
+  private static final ObjectMapper MAPPER = createMapper();
+
+  private SemanticModelDefinitionSerDe() {}
+
+  static String serialize(SemanticModelDefinition definition) throws JsonProcessingException {
+    return MAPPER.writeValueAsString(definition);
+  }
+
+  static SemanticModelDefinition deserialize(String json) throws JsonProcessingException {
+    return MAPPER.readValue(json, SemanticModelDefinition.class);
+  }
+
+  private static ObjectMapper createMapper() {
+    SimpleModule module =
+        new SimpleModule()
+            .addSerializer(AIContext.class, new AIContextSerializer())
+            .addDeserializer(AIContext.class, new AIContextDeserializer())
+            .addSerializer(DataType.class, new DataTypeSerializer())
+            .addDeserializer(DataType.class, new DataTypeDeserializer())
+            .addSerializer(NameIdentifier.class, new JsonUtils.NameIdentifierSerializer())
+            .addDeserializer(NameIdentifier.class, new JsonUtils.NameIdentifierDeserializer());
+
+    ObjectMapper mapper =
+        JsonUtils.anyFieldMapper()
+            .copy()
+            .setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE)
+            .setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE)
+            .setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE)
+            .setSerializationInclusion(JsonInclude.Include.NON_NULL)
+            .configure(JsonNodeFeature.STRIP_TRAILING_BIGDECIMAL_ZEROES, false)
+            .enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)
+            .enable(DeserializationFeature.USE_BIG_INTEGER_FOR_INTS)
+            .registerModule(module);
+    addBuilderMixIns(
+        mapper,
+        SemanticModelDefinition.class,
+        SemanticModelDefinitionMixIn.class,
+        SemanticModelDefinition.Builder.class);
+    addBuilderMixIns(mapper, Dataset.class, DatasetMixIn.class, Dataset.Builder.class);
+    addBuilderMixIns(
+        mapper, Relationship.class, RelationshipMixIn.class, Relationship.Builder.class);
+    addBuilderMixIns(mapper, Metric.class, MetricMixIn.class, Metric.Builder.class);
+    addBuilderMixIns(mapper, Field.class, FieldMixIn.class, Field.Builder.class);
+    addBuilderMixIns(mapper, Expression.class, ExpressionMixIn.class, Expression.Builder.class);
+    addBuilderMixIns(
+        mapper,
+        DialectExpression.class,
+        DialectExpressionMixIn.class,
+        DialectExpression.Builder.class);
+    addBuilderMixIns(mapper, Dimension.class, DimensionMixIn.class, Dimension.Builder.class);
+    addBuilderMixIns(
+        mapper, CustomExtension.class, CustomExtensionMixIn.class, CustomExtension.Builder.class);
+    return mapper;
+  }
+
+  private static void addBuilderMixIns(
+      ObjectMapper mapper, Class<?> valueClass, Class<?> mixInClass, Class<?> builderClass) {
+    mapper.addMixIn(valueClass, mixInClass);
+    mapper.addMixIn(builderClass, BuilderMixIn.class);
+  }
+
+  @JsonPOJOBuilder(withPrefix = "with")
+  private abstract static class BuilderMixIn {}
+
+  @JsonDeserialize(builder = SemanticModelDefinition.Builder.class)
+  private abstract static class SemanticModelDefinitionMixIn {}
+
+  @JsonDeserialize(builder = Dataset.Builder.class)
+  private abstract static class DatasetMixIn {}
+
+  @JsonDeserialize(builder = Relationship.Builder.class)
+  private abstract static class RelationshipMixIn {}
+
+  @JsonDeserialize(builder = Metric.Builder.class)
+  private abstract static class MetricMixIn {}
+
+  @JsonDeserialize(builder = Field.Builder.class)
+  private abstract static class FieldMixIn {}
+
+  @JsonDeserialize(builder = Expression.Builder.class)
+  private abstract static class ExpressionMixIn {}
+
+  @JsonDeserialize(builder = DialectExpression.Builder.class)
+  private abstract static class DialectExpressionMixIn {}
+
+  @JsonDeserialize(builder = Dimension.Builder.class)
+  private abstract static class DimensionMixIn {}
+
+  @JsonDeserialize(builder = CustomExtension.Builder.class)
+  private abstract static class CustomExtensionMixIn {}
+
+  private static final class AIContextSerializer extends JsonSerializer<AIContext> {
+
+    @Override
+    public void serialize(AIContext value, JsonGenerator generator, SerializerProvider serializers)
+        throws IOException {
+      if (value.isText()) {
+        generator.writeString(value.text());
+        return;
+      }
+
+      AIContextObject object = value.object();
+      if (object == null) {
+        throw JsonMappingException.from(generator, "Structured AI context must not be null");
+      }
+      generator.writeStartObject();
+      writeOptionalField(generator, "instructions", object.instructions());
+      writeOptionalField(generator, "synonyms", object.synonyms());
+      writeOptionalField(generator, "examples", object.examples());
+      for (Map.Entry<String, Object> entry : object.additionalProperties().entrySet()) {
+        generator.writeObjectField(entry.getKey(), entry.getValue());
+      }

Review Comment:
   `AIContextObject` already enforces this invariant before serialization. Its private constructor copies `additionalProperties` through `immutableAdditionalProperties(...)`, which rejects `instructions`, `synonyms`, and `examples`; the resulting map is also immutable. `TestSemanticModelSupportingTypes` covers this rejection explicitly. Therefore, the serializer cannot receive a valid `AIContextObject` containing these reserved additional-property keys, so it cannot emit duplicate reserved fields.



-- 
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] [#12600] feat(store): Add Semantic Model create and load persistence [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetaService.java:
##########
@@ -0,0 +1,242 @@
+/*
+ * 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.storage.relational.service;
+
+import static org.apache.gravitino.metrics.source.MetricsSource.GRAVITINO_RELATIONAL_STORE_METRIC_NAME;
+import static org.apache.gravitino.storage.relational.po.SemanticModelPO.fromSemanticModelPO;
+import static org.apache.gravitino.storage.relational.po.SemanticModelPO.initializeSemanticModelPO;
+
+import com.google.common.base.Preconditions;
+import java.io.IOException;
+import java.util.Locale;
+import java.util.Objects;
+import java.util.concurrent.atomic.AtomicReference;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.meta.SemanticModelEntity;
+import org.apache.gravitino.metrics.Monitored;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelVersionInfoMapper;
+import org.apache.gravitino.storage.relational.po.SemanticModelPO;
+import org.apache.gravitino.storage.relational.po.SemanticModelVersionInfoPO;
+import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.gravitino.utils.NameIdentifierUtil;
+
+/** Provides relational create and load operations for Semantic Model metadata. */
+public class SemanticModelMetaService {
+
+  private static final SemanticModelMetaService INSTANCE = new SemanticModelMetaService();
+
+  private final BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> ops;
+
+  /** Returns the singleton Semantic Model metadata service. */
+  public static SemanticModelMetaService getInstance() {
+    return INSTANCE;
+  }
+
+  private SemanticModelMetaService() {
+    this.ops = new HierarchicalConversionPOStorageOps<>(new SemanticModelPOStorageOps());
+  }
+
+  /**
+   * Resolves a Semantic Model stable ID by schema ID and name.
+   *
+   * @param schemaId The parent schema ID.
+   * @param semanticModelName The Semantic Model name.
+   * @return The stable Semantic Model ID.
+   * @throws NoSuchEntityException If the Semantic Model does not exist.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "getSemanticModelIdBySchemaIdAndName")
+  public Long getSemanticModelIdBySchemaIdAndName(long schemaId, String semanticModelName) {
+    Long semanticModelId =
+        SessionUtils.getWithoutCommit(
+            SemanticModelMetaMapper.class,
+            mapper -> mapper.selectSemanticModelIdBySchemaIdAndName(schemaId, semanticModelName));
+    if (semanticModelId == null) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.SEMANTIC_MODEL.name().toLowerCase(Locale.ROOT),
+          semanticModelName);
+    }
+    return semanticModelId;
+  }
+
+  /**
+   * Loads the current Semantic Model by identifier.
+   *
+   * @param identifier The Semantic Model identifier.
+   * @return The current Semantic Model entity.
+   * @throws NoSuchEntityException If the Semantic Model does not exist.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "getSemanticModelByIdentifier")
+  public SemanticModelEntity getSemanticModelByIdentifier(NameIdentifier identifier) {
+    SemanticModelPO semanticModelPO = getSemanticModelPOByIdentifier(identifier);
+    return fromSemanticModelPO(semanticModelPO, identifier.namespace());
+  }
+
+  /**
+   * Inserts or overwrites a Semantic Model identity and its snapshot atomically.
+   *
+   * @param semanticModelEntity The Semantic Model entity.
+   * @param overwrite Whether to overwrite rows for the same stable ID or natural key.
+   * @throws IOException If relational persistence fails.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "insertSemanticModel")
+  public void insertSemanticModel(SemanticModelEntity semanticModelEntity, boolean overwrite)
+      throws IOException {
+    NameIdentifierUtil.checkSemanticModel(semanticModelEntity.nameIdentifier());
+    try {
+      SemanticModelPO po =
+          initializeSemanticModelPO(semanticModelEntity, SemanticModelPO.builder());
+      AtomicReference<SemanticModelPO> persistedPO = new AtomicReference<>(po);
+      SchemaMetaService.getInstance()
+          .doWithSchemaWriteLock(
+              semanticModelEntity.nameIdentifier(),
+              po.getSchemaId(),
+              po.getCatalogId(),
+              po.getMetalakeId(),
+              () ->
+                  SessionUtils.doWithoutCommit(
+                      SemanticModelMetaMapper.class,
+                      mapper -> {
+                        SemanticModelPO storedPO =
+                            overwrite
+                                ? mapper.selectSemanticModelMetaBySchemaIdAndNameForUpdate(
+                                    po.getSchemaId(), po.getSemanticModelName())
+                                : null;
+                        if (storedPO == null) {
+                          // Keep missing-row imports strict. A losing concurrent insert must not
+                          // overwrite a persisted identity with a different ID.
+                          ops.insertPO(mapper, po, false);
+                          return;
+                        }
+
+                        SemanticModelPO replacementPO = semanticModelForOverwrite(po, storedPO);
+                        Integer updated = mapper.updateSemanticModelMeta(replacementPO, storedPO);
+                        if (updated == null || updated != 1) {
+                          throw semanticModelWriteFailure(
+                              semanticModelEntity.nameIdentifier(), storedPO);
+                        }
+                        persistedPO.set(replacementPO);
+                      }),
+              () ->
+                  SessionUtils.doWithoutCommit(
+                      SemanticModelVersionInfoMapper.class,
+                      mapper ->
+                          mapper.insertSemanticModelVersionInfo(
+                              persistedPO.get().getSemanticModelVersionInfoPO())));
+    } catch (RuntimeException re) {
+      ExceptionUtils.checkSQLException(
+          re, Entity.EntityType.SEMANTIC_MODEL, semanticModelEntity.nameIdentifier().toString());
+      throw re;
+    }
+  }
+
+  /** Returns the persistent-object operations used by this service. */
+  public BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> ops() {
+    return ops;
+  }
+
+  private static SemanticModelPO semanticModelForOverwrite(
+      SemanticModelPO source, SemanticModelPO persistedPO) {
+    int previousVersion = Math.max(persistedPO.getCurrentVersion(), persistedPO.getLastVersion());
+    Preconditions.checkState(
+        previousVersion < Integer.MAX_VALUE,
+        "Semantic Model %s has exhausted the version range",
+        persistedPO.getSemanticModelId());
+    int nextVersion = previousVersion + 1;
+    return SemanticModelPO.builder()
+        .withSemanticModelId(persistedPO.getSemanticModelId())
+        .withSemanticModelName(source.getSemanticModelName())
+        .withMetalakeId(persistedPO.getMetalakeId())
+        .withCatalogId(persistedPO.getCatalogId())
+        .withSchemaId(persistedPO.getSchemaId())
+        .withAuditInfo(source.getAuditInfo())
+        .withCurrentVersion(nextVersion)
+        .withLastVersion(nextVersion)
+        .withDeletedAt(source.getDeletedAt())
+        .withSemanticModelVersionInfoPO(
+            versionInfoForOverwrite(
+                source.getSemanticModelVersionInfoPO(), persistedPO, nextVersion))
+        .build();
+  }
+
+  private static SemanticModelVersionInfoPO versionInfoForOverwrite(
+      SemanticModelVersionInfoPO source, SemanticModelPO persistedPO, int nextVersion) {
+    return SemanticModelVersionInfoPO.builder()
+        .withMetalakeId(persistedPO.getMetalakeId())
+        .withCatalogId(persistedPO.getCatalogId())
+        .withSchemaId(persistedPO.getSchemaId())
+        .withSemanticModelId(persistedPO.getSemanticModelId())
+        .withVersion(nextVersion)
+        .withSemanticModelName(source.semanticModelName())
+        .withSemanticModelComment(source.semanticModelComment())
+        .withSemanticModelDefinition(source.semanticModelDefinition())
+        .withProperties(source.properties())
+        .withAuditInfo(source.auditInfo())
+        .withDeletedAt(source.deletedAt())
+        .build();
+  }
+
+  private SemanticModelPO getSemanticModelPOByIdentifier(NameIdentifier identifier) {
+    NameIdentifierUtil.checkSemanticModel(identifier);
+    SemanticModelPO semanticModelPO =
+        SessionUtils.getWithoutCommit(
+            SemanticModelMetaMapper.class,
+            mapper ->
+                POStorageReadRouting.getPO(
+                    mapper, identifier, ops, Entity.EntityType.SEMANTIC_MODEL));
+    if (semanticModelPO == null) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.SEMANTIC_MODEL.name().toLowerCase(Locale.ROOT),
+          identifier.name());
+    }
+    return semanticModelPO;
+  }
+
+  private RuntimeException semanticModelWriteFailure(
+      NameIdentifier identifier, SemanticModelPO observedSemanticModelPO) {
+    return OccWriteSupport.writeFailure(
+        identifier,
+        Entity.EntityType.SEMANTIC_MODEL,
+        () ->
+            SessionUtils.getWithoutCommit(
+                SemanticModelMetaMapper.class,
+                mapper ->
+                    mapper.selectSemanticModelMetaByIdForUpdate(
+                        observedSemanticModelPO.getSemanticModelId())),

Review Comment:
   [Nit] This wires `selectSemanticModelMetaByIdForUpdate` for the first time, and it is the one lock-select here that reuses the joined snapshot result map.
   
   `SemanticModelMetaMapper.java:112-118` puts `@ResultMap("semanticModelPOResultMap")` on it, but the statement's SQL (`SemanticModelMetaBaseSQLProvider.java:101-107`) selects only the nine identity columns. That result map declares a nested association (mapper `:82-90`, resolving to `mapToSemanticModelVersionInfoPO` at `:43-58`) mapped from `id`, `version_metalake_id` ... `version_deleted_at` — none of which this statement returns — so the PO handed to the predicate below comes back with a null `semanticModelVersionInfoPO`. Harmless as used, since the predicate reads only name/schema/catalog/metalake, but nothing in the test suite executes this statement, so neither that null association nor MyBatis's handling of the missing association columns has ever actually run against a database.
   
   The two siblings this service is modelled on sidestep the question by aliasing in SQL and declaring no result map: `ViewMetaMapper.java:129-130` with `ViewMetaBaseSQLProvider.java:162-170`, and `FunctionMetaMapper.java:160-163` with `FunctionMetaBaseSQLProvider.java:188-197`. So does the natural-key lock added by this PR (`SemanticModelMetaBaseSQLProvider.java:72-84`). Aliasing the columns and dropping `@ResultMap` would make the by-ID lock consistent with all three, and would matter if this lookup is later promoted into the overwrite resolution itself via `OccWriteSupport.findAndLockForOverwrite`.
   
   Verified by: read `SemanticModelMetaMapper.java:43-118`, `SemanticModelMetaBaseSQLProvider.java:72-107`, `ViewMetaMapper.java:117-130`, `ViewMetaBaseSQLProvider.java:162-170`, `FunctionMetaMapper.java:150-163` and `FunctionMetaBaseSQLProvider.java:188-197` in the checked-out tree at 17729aa; `grep -rn "selectSemanticModelMetaByIdForUpdate" --include=*.java core/src` returns the mapper, provider, factory and `SemanticModelMetaService.java:231` as the only caller, with no test reference.



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