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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to