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

[PR] [#12342] improvement(core): add OCC for namespace hierarchy [gravitino]

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

   ### What changes were proposed in this pull request?
   
   Add optimistic concurrency control to the complete alter and delete operations for metalakes, catalogs, and schemas.
   
   - Increment the entity version on every alter and update rows by id plus the expected current version.
   - Delete the root entity by id plus the expected current version before any cascade cleanup.
   - For hierarchical schemas, CAS-delete the requested schema first and then authoritatively delete its descendants.
   - Report stale alter or delete operations with `OptimisticLockException`.
   
   This PR depends on #12349.
   
   ### Why are the changes needed?
   
   Concurrent metadata changes must not silently overwrite newer state or run relationship and descendant cleanup after the root entity CAS fails.
   
   Fix: #12342
   
   ### Does this PR introduce _any_ user-facing change?
   
   Concurrent alter and delete conflicts for metalakes, catalogs, and schemas are reported as HTTP 409 through the shared conflict contract from #12349.
   
   ### How was this patch tested?
   
   Added version increment, stale alter, stale delete, and typed conflict tests. Ran:
   
   `./gradlew :core:test --tests 'org.apache.gravitino.storage.relational.utils.TestPOConverters' --tests 'org.apache.gravitino.storage.relational.service.TestMetalakeMetaService' --tests 'org.apache.gravitino.storage.relational.service.TestCatalogMetaService' --tests 'org.apache.gravitino.storage.relational.service.TestSchemaMetaService' -PskipITs -PskipDockerTests=true`
   


-- 
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] [#12342] improvement(core): add OCC for namespace hierarchy [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SchemaMetaService.java:
##########
@@ -227,20 +234,23 @@ public <E extends Entity & HasIdentifier> SchemaEntity updateSchema(
         NameIdentifierUtil.ofSchema(metalakeName, catalogName, oldSchemaEntity.name()).toString();
     boolean isRenamed = !Objects.equals(oldSchemaEntity.name(), newEntity.name());
 
-    AtomicInteger updateResult = new AtomicInteger(0);
     try {
       SessionUtils.doMultipleWithCommit(
-          () ->
-              updateResult.set(
-                  SessionUtils.getWithoutCommit(
-                      SchemaMetaMapper.class,
-                      mapper ->
-                          ops.updatePO(
-                              mapper,
-                              POConverters.updateSchemaPOWithVersion(oldSchemaPO, newEntity),
-                              oldSchemaPO))),
           () -> {
-            if (isRenamed && updateResult.get() > 0) {
+            int updated =
+                SessionUtils.getWithoutCommit(
+                    SchemaMetaMapper.class,
+                    mapper ->
+                        ops.updatePO(
+                            mapper,
+                            POConverters.updateSchemaPOWithVersion(oldSchemaPO, newEntity),
+                            oldSchemaPO));

Review Comment:
   This one and L477, L496, and CatalogMetaService:253/429 are the same problem.
   
   
   The observation is accurate: these fences validate the immediate parent row by id + name, and an ancestor rename does not change that row. 
   
   This is intentional. In Gravitino, entity identity is the ID, and rename preserves identity — the request resolved metalakeId/catalogId, and after the rename those ids still denote the same entity, so the write lands on exactly the entity the caller resolved, just reachable under a new name. Nothing is orphaned and no update is lost. The anomaly this PR is closing is the different one where the parent is deleted (or replaced by a same-named entity with a new id) and a child write would survive it — that case is fenced by the id + existence check.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org

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


Re: [PR] [#12342] improvement(core): add OCC for namespace hierarchy [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/service/MetalakeMetaService.java:
##########
@@ -206,30 +210,32 @@ public <E extends Entity & HasIdentifier> BaseMetalake updateMetalake(
       throw re;
     }
 
-    if (updateResult.get() > 0) {
-      return newMetalakeEntity;
-    } else {
-      throw new IOException("Failed to update the entity: " + ident);
-    }
+    return newMetalakeEntity;
   }
 
   @Monitored(
       metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
       baseMetricName = "deleteMetalake")
   public boolean deleteMetalake(NameIdentifier ident, boolean cascade) {
     NameIdentifierUtil.checkMetalake(ident);
-    Long metalakeId = getMetalakeIdByName(ident.name());
+    MetalakePO metalakePO =
+        SessionUtils.getWithoutCommit(
+            MetalakeMetaMapper.class, mapper -> mapper.selectMetalakeMetaByName(ident.name()));
+    if (metalakePO == null) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.METALAKE.name().toLowerCase(),
+          ident.toString());
+    }
+    Long metalakeId = metalakePO.getMetalakeId();
+    Long currentVersion = metalakePO.getCurrentVersion();
     if (metalakeId != null) {
       if (cascade) {
         SessionUtils.doMultipleWithCommit(
-            () ->
-                SessionUtils.doWithoutCommit(
-                    MetalakeMetaMapper.class,
-                    mapper -> mapper.softDeleteMetalakeMetaByMetalakeId(metalakeId)),
-            () ->
-                SessionUtils.doWithoutCommit(
-                    CatalogMetaMapper.class,
-                    mapper -> mapper.softDeleteCatalogMetasByMetalakeId(metalakeId)),
+            () -> {
+              deleteMetalakeWithVersion(ident, metalakeId, currentVersion);
+              deleteCatalogsWithVersions(ident, metalakeId);

Review Comment:
   Good catch. The metalake cascade now locks the active catalog parent rows first, collects the active SchemaPO snapshot, CAS-deletes schemas by schema_id and current_version, and validates the affected-row count. A concurrent schema alter after the snapshot now raises OptimisticLockException and rolls back the metalake/catalog deletion. Locking the catalog rows also prevents a concurrent schema create from being missed under MySQL REPEATABLE READ. I added a deterministic interleaving test that commits a schema alter between the snapshot and batch delete and verifies the full cascade rolls back. Fixed in 31a90c8840.



##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SchemaMetaService.java:
##########
@@ -492,13 +471,78 @@ private List<SchemaPO> listSchemaPOs(Namespace namespace) {
         mapper -> POStorageReadRouting.listPOs(mapper, namespace, ops, Entity.EntityType.SCHEMA));
   }
 
+  private void fenceCatalogForSchemaCreate(CatalogPO catalogPO) {
+    int fenced =
+        SessionUtils.getWithoutCommit(
+            CatalogMetaMapper.class,
+            mapper ->
+                mapper.fenceCatalogMeta(catalogPO.getCatalogId(), catalogPO.getCurrentVersion()));

Review Comment:
   Good catch. I replaced the parent version fence with SELECT ... FOR UPDATE plus identity revalidation in the same transaction. The lock serializes schema creation with catalog rename/delete, but it does not advance the catalog version. As a result, concurrent same-name creates both reach the insert sequentially and the loser is reported as EntityAlreadyExistsException, while unrelated sibling creates both succeed. I added true concurrent tests for both cases and applied the same strategy to catalog creation under a metalake. Fixed in 31a90c8840.



-- 
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] [#12342] improvement(core): add OCC for namespace hierarchy [gravitino]

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

   Per review feedback that this PR is too large, it has been split into three smaller PRs, in dependency order:
   
   - #12454 — metalake OCC plus the shared conflict helpers (issue #12451)
   - #12455 — catalog OCC (issue #12452, draft until #12454 merges)
   - #12456 — schema OCC and the child-entity row locks (issue #12453, draft until #12455 merges)
   
   The three branches stacked together produce a tree identical to this PR's head (`git diff` between them is empty), so nothing is dropped. Each branch is independently green on `:core:test` with H2.
   
   Keeping this PR open for the discussion context; it will be closed once the three land.


-- 
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] [#12342] improvement(core): add OCC for namespace hierarchy [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SchemaMetaService.java:
##########
@@ -492,13 +470,151 @@ private List<SchemaPO> listSchemaPOs(Namespace namespace) {
         mapper -> POStorageReadRouting.listPOs(mapper, namespace, ops, Entity.EntityType.SCHEMA));
   }
 
+  private void lockCatalogForSchemaCreate(
+      CatalogPO observedCatalogPO, boolean createsImplicitAncestors) {
+    CatalogPO currentCatalogPO =
+        SessionUtils.getWithoutCommit(
+            CatalogMetaMapper.class,
+            mapper ->
+                createsImplicitAncestors
+                    ? mapper.selectCatalogMetaByIdForUpdate(observedCatalogPO.getCatalogId())
+                    : mapper.selectCatalogMetaByIdForShare(observedCatalogPO.getCatalogId()));
+    if (currentCatalogPO == null
+        || !Objects.equals(currentCatalogPO.getCatalogName(), observedCatalogPO.getCatalogName())
+        || !Objects.equals(currentCatalogPO.getMetalakeId(), observedCatalogPO.getMetalakeId())) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.CATALOG.name().toLowerCase(),
+          observedCatalogPO.getCatalogName());
+    }
+  }
+
+  private void lockCatalogForSchemaDelete(NameIdentifier identifier, SchemaPO observedSchemaPO) {
+    CatalogPO currentCatalogPO =
+        SessionUtils.getWithoutCommit(
+            CatalogMetaMapper.class,
+            mapper -> mapper.selectCatalogMetaByIdForUpdate(observedSchemaPO.getCatalogId()));

Review Comment:
   This delete fence detects a catalog rename/delete, but not a metalake rename: the catalog name and `metalakeId` remain unchanged after the metalake name changes. A delete that resolved the schema under the old path can therefore proceed after the rename and remove the schema from the new path. Lock and validate the metalake name before taking this catalog lock, preserving root-to-leaf lock order.



##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SchemaMetaService.java:
##########
@@ -227,20 +234,23 @@ public <E extends Entity & HasIdentifier> SchemaEntity updateSchema(
         NameIdentifierUtil.ofSchema(metalakeName, catalogName, oldSchemaEntity.name()).toString();
     boolean isRenamed = !Objects.equals(oldSchemaEntity.name(), newEntity.name());
 
-    AtomicInteger updateResult = new AtomicInteger(0);
     try {
       SessionUtils.doMultipleWithCommit(
-          () ->
-              updateResult.set(
-                  SessionUtils.getWithoutCommit(
-                      SchemaMetaMapper.class,
-                      mapper ->
-                          ops.updatePO(
-                              mapper,
-                              POConverters.updateSchemaPOWithVersion(oldSchemaPO, newEntity),
-                              oldSchemaPO))),
           () -> {
-            if (isRenamed && updateResult.get() > 0) {
+            int updated =
+                SessionUtils.getWithoutCommit(
+                    SchemaMetaMapper.class,
+                    mapper ->
+                        ops.updatePO(
+                            mapper,
+                            POConverters.updateSchemaPOWithVersion(oldSchemaPO, newEntity),
+                            oldSchemaPO));

Review Comment:
   The schema CAS can still commit after either ancestor is renamed. The schema was loaded through the old fully qualified name, but the update locks/checks only the schema row; catalog or metalake renames do not change its IDs or version. Consequently a request for the old path can mutate the schema now reachable only through the new path. Acquire and validate shared ancestor locks in metalake-to-catalog order before this CAS.



##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SchemaMetaService.java:
##########
@@ -492,13 +470,151 @@ private List<SchemaPO> listSchemaPOs(Namespace namespace) {
         mapper -> POStorageReadRouting.listPOs(mapper, namespace, ops, Entity.EntityType.SCHEMA));
   }
 
+  private void lockCatalogForSchemaCreate(
+      CatalogPO observedCatalogPO, boolean createsImplicitAncestors) {
+    CatalogPO currentCatalogPO =
+        SessionUtils.getWithoutCommit(
+            CatalogMetaMapper.class,

Review Comment:
   The create fence does not cover a concurrent metalake rename. `catalogPO` is resolved using the old metalake name before the transaction, but this lock only revalidates the catalog row; a metalake rename leaves that row and its `metalakeId` unchanged, so the insert can succeed under the renamed metalake even though the requested fully qualified parent no longer exists. Lock and validate the metalake row by ID/name before locking the catalog (root-to-leaf order), and add a cross-transaction rename/create regression test.



##########
core/src/main/java/org/apache/gravitino/storage/relational/service/CatalogMetaService.java:
##########
@@ -226,41 +240,37 @@ public <E extends Entity & HasIdentifier> CatalogEntity updateCatalog(
     String oldFullName =
         NameIdentifierUtil.ofCatalog(metalakeName, oldCatalogEntity.name()).toString();
 
-    AtomicInteger updateResult = new AtomicInteger(0);
     try {
       SessionUtils.doMultipleWithCommit(
-          () ->
-              updateResult.set(
-                  SessionUtils.getWithoutCommit(
-                      CatalogMetaMapper.class,
-                      mapper ->
-                          mapper.updateCatalogMeta(
-                              POConverters.updateCatalogPOWithVersion(
-                                  oldCatalogPO, newEntity, oldCatalogPO.getMetalakeId()),
-                              oldCatalogPO))),
           () -> {
-            if (updateResult.get() > 0) {
+            int updated =
+                SessionUtils.getWithoutCommit(
+                    CatalogMetaMapper.class,
+                    mapper ->
+                        mapper.updateCatalogMeta(
+                            POConverters.updateCatalogPOWithVersion(
+                                oldCatalogPO, newEntity, oldCatalogPO.getMetalakeId()),
+                            oldCatalogPO));

Review Comment:
   This CAS does not fence a concurrent metalake rename. After `oldCatalogPO` is read through the old metalake name, the metalake can be renamed on another server without changing the catalog row or version, allowing this update to mutate the catalog now under the new path. Take and validate a shared metalake lock before updating the catalog so stale fully qualified identifiers report missing instead of succeeding.



##########
core/src/main/java/org/apache/gravitino/storage/relational/service/CatalogMetaService.java:
##########
@@ -415,6 +420,72 @@ public boolean deleteCatalog(NameIdentifier identifier, boolean cascade) {
     return true;
   }
 
+  private void deleteCatalogWithVersion(NameIdentifier identifier, CatalogPO observedCatalogPO) {
+    int deleted =
+        SessionUtils.getWithoutCommit(
+            CatalogMetaMapper.class,
+            mapper ->
+                mapper.softDeleteCatalogMetasByCatalogId(
+                    observedCatalogPO.getCatalogId(), observedCatalogPO.getCurrentVersion()));

Review Comment:
   A catalog delete loaded through the old metalake name can still succeed after that metalake is renamed, because this CAS checks only the catalog row and its version. The catalog's `metalakeId` is stable across the rename, so the request deletes the catalog from the new path rather than producing the documented missing/idempotent result. Acquire and validate the metalake row before the catalog CAS, using root-to-leaf lock order.



-- 
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] [#12342] improvement(core): add OCC for namespace hierarchy [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SchemaMetaService.java:
##########
@@ -492,13 +470,151 @@ private List<SchemaPO> listSchemaPOs(Namespace namespace) {
         mapper -> POStorageReadRouting.listPOs(mapper, namespace, ops, Entity.EntityType.SCHEMA));
   }
 
+  private void lockCatalogForSchemaCreate(
+      CatalogPO observedCatalogPO, boolean createsImplicitAncestors) {
+    CatalogPO currentCatalogPO =
+        SessionUtils.getWithoutCommit(
+            CatalogMetaMapper.class,
+            mapper ->
+                createsImplicitAncestors
+                    ? mapper.selectCatalogMetaByIdForUpdate(observedCatalogPO.getCatalogId())

Review Comment:
   You are right. When a create needs to make implicit ancestors, we take an exclusive lock on the catalog row, so all other schema creates under the same catalog have to wait, even if they use a different path.
   
   We need the exclusive lock here because two concurrent creates can both see that an ancestor is missing and both insert it. Under MySQL REPEATABLE READ, a shared lock is not enough to stop this.
   
   So this is an accepted tradeoff: correctness first, less concurrency for hierarchical creates. I will add this to the PR description.
   
   If it becomes a problem later, we can make the lock smaller: only lock the ancestor rows we really need to create, and use the unique constraint plus a retry instead of locking the whole catalog row. I can do that in a follow-up issue.



-- 
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] [#12342] improvement(core): add OCC for namespace hierarchy [gravitino]

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

   @roryqi @jerryshao 
   Do you have time to take a look again?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org

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


Re: [PR] [#12342] improvement(core): add OCC for namespace hierarchy [gravitino]

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

   > > @roryqi
   > > Thanks for the suggestion. I understand it as extracting a common OCC SQL template for update/fence/soft-delete operations, with each provider supplying the table name, ID column, and MyBatis parameter names. After reviewing these statements, I think a generic SQL template would have limited benefit here. Besides the table and ID column, the MyBatis parameter paths, batch collection names, entity-specific SET clauses, and database-specific deleted_at expressions also differ. Passing these as string parameters would hide the final SQL, reduce readability, and move some errors to runtime. I would prefer to keep the entity-specific SQL explicit.
   > > I agree that exact duplication should be removed. A narrower approach would be to reuse DatabaseTimeSQL for database-time expressions and let PostgreSQL providers inherit SQL that is identical to the base provider, keeping overrides only where the SQL dialect actually differs. If more entities later converge on an identical OCC SQL shape, we can revisit a narrowly scoped helper. Would this narrower cleanup address your concern, or do you have a specific interface/template design in mind?
   > 
   > I prefer think further. We can give more constraints about table create SQL standard. Some common column must has the fixed name. Some services must have some specific interfaces.
   > 
   > For example, we have delete_at column in every table, we have a delete interface. Every storage service should implement it.
   > 
   > I think this is possible. We would better have a framework to handle this issue. We should think more about how to iterate our storage framework. Now, we are using AI to generate the code. It seems not bring much burden. But it is still hard for people to review code and maintain our code base.
   
   @roryqi
   
   Thanks for the suggestion. I understand it as extracting a common OCC SQL template for update/fence/soft-delete operations, with each provider supplying the table name, ID column, and MyBatis parameter names. After reviewing these statements, I think a generic SQL template would have limited benefit here. Besides the table and ID column, the MyBatis parameter paths, batch collection names, entity-specific SET clauses, and database-specific deleted_at expressions also differ. Passing these as string parameters would hide the final SQL, reduce readability, and move some errors to runtime. I would prefer to keep the entity-specific SQL explicit.
   
   I agree that exact duplication should be removed. A narrower approach would be to reuse DatabaseTimeSQL for database-time expressions and let PostgreSQL providers inherit SQL that is identical to the base provider, keeping overrides only where the SQL dialect actually differs. If more entities later converge on an identical OCC SQL shape, we can revisit a narrowly scoped helper. Would this narrower cleanup address your concern, or do you have a specific interface/template design in mind?
   
   I prefer think further. We can give more constraints about table create SQL standard. Some common column must has the fixed name. Some services must have some specific interfaces.
   
   For example, we have delete_at column in every table, we have a delete interface. Every storage service should implement it.
   
   I think this is possible. We would better have a framework to handle this issue.  We should think more about how to iterate our storage framework. Now, we are using AI to generate the code. It seems not bring much burden.
   But it is still hard for people to review code and maintain our code base.
   
   I suggest we use another PR to discuss the problem and leave your ideas in as much detail as possible. AI hinted to me that 
   - It's not so proper to do it in this PR
   - The final return is unclear.
   
   If you insist on this point, please just create an issue that is targeted at this problem. I think we can do a pure refactor without 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] [#12342] improvement(core): add OCC for namespace hierarchy [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/service/CatalogMetaService.java:
##########
@@ -415,6 +420,72 @@ public boolean deleteCatalog(NameIdentifier identifier, boolean cascade) {
     return true;
   }
 
+  private void deleteCatalogWithVersion(NameIdentifier identifier, CatalogPO observedCatalogPO) {
+    int deleted =
+        SessionUtils.getWithoutCommit(
+            CatalogMetaMapper.class,
+            mapper ->
+                mapper.softDeleteCatalogMetasByCatalogId(
+                    observedCatalogPO.getCatalogId(), observedCatalogPO.getCurrentVersion()));
+    if (deleted == 0) {
+      throw catalogWriteFailure(identifier, observedCatalogPO);
+    }
+  }
+
+  private void lockMetalakeForCatalogCreate(MetalakePO observedMetalakePO) {
+    MetalakePO currentMetalakePO =
+        SessionUtils.getWithoutCommit(
+            MetalakeMetaMapper.class,
+            mapper -> mapper.selectMetalakeMetaByIdForShare(observedMetalakePO.getMetalakeId()));
+    if (currentMetalakePO == null
+        || !Objects.equals(
+            currentMetalakePO.getMetalakeName(), observedMetalakePO.getMetalakeName())) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.METALAKE.name().toLowerCase(),
+          observedMetalakePO.getMetalakeName());
+    }
+  }
+
+  private RuntimeException catalogWriteFailure(
+      NameIdentifier identifier, CatalogPO observedCatalogPO) {
+    CatalogPO currentCatalogPO =
+        SessionUtils.getWithoutCommit(
+            CatalogMetaMapper.class,
+            mapper -> mapper.selectCatalogMetaByIdForUpdate(observedCatalogPO.getCatalogId()));
+    if (currentCatalogPO == null
+        || !Objects.equals(currentCatalogPO.getCatalogName(), observedCatalogPO.getCatalogName())
+        || !Objects.equals(currentCatalogPO.getMetalakeId(), observedCatalogPO.getMetalakeId())) {
+      return new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.CATALOG.name().toLowerCase(),
+          identifier.name());
+    }
+    return optimisticLockException(identifier);
+  }
+
+  private void deleteSchemasWithVersions(NameIdentifier catalogIdentifier, Long catalogId) {
+    List<SchemaPO> schemaPOs =
+        SessionUtils.getWithoutCommit(
+            SchemaMetaMapper.class, mapper -> mapper.listSchemaPOsByCatalogId(catalogId));
+    if (schemaPOs.isEmpty()) {
+      return;
+    }
+    int deleted =
+        SessionUtils.getWithoutCommit(
+            SchemaMetaMapper.class, mapper -> mapper.softDeleteSchemaMetasWithVersion(schemaPOs));
+    if (deleted != schemaPOs.size()) {
+      throw new OptimisticLockException(

Review Comment:
   It is better to call a helper method if defined, rather than calling a class constructuor.



-- 
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] [#12342] improvement(core): add OCC for namespace hierarchy [gravitino]

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

   > I really would suggest you split PRs into small one, so that we can have a better review.
   
   I will adopt it for the remaining few PRs. This one is small initially, and getting larger and larger after several round of reviews.


-- 
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] [#12342] improvement(core): add OCC for namespace hierarchy [gravitino]

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

   @roryqi 
   
   Thanks for the suggestion. I understand it as extracting a common OCC SQL template for update/fence/soft-delete operations, with each provider supplying the table name, ID column, and MyBatis parameter names. After reviewing these statements, I think a generic SQL template would have limited benefit here. Besides the table and ID column, the MyBatis parameter paths, batch collection names, entity-specific SET clauses, and database-specific deleted_at expressions also differ. Passing these as string parameters would hide the final SQL, reduce readability, and move some errors to runtime. I would prefer to keep the entity-specific SQL explicit.
     
   I agree that exact duplication should be removed. A narrower approach would be to reuse DatabaseTimeSQL for database-time expressions and let PostgreSQL providers inherit SQL that is identical to the base provider, keeping overrides only where the SQL dialect actually differs. If more entities later converge on an identical OCC SQL shape, we can revisit a narrowly scoped helper. Would this narrower cleanup address your concern, or do you have a specific interface/template design in mind?


-- 
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] [#12342] improvement(core): add OCC for namespace hierarchy [gravitino]

Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 closed pull request #12350: [#12342] improvement(core): add OCC for namespace hierarchy
URL: https://github.com/apache/gravitino/pull/12350


-- 
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] [#12342] improvement(core): add OCC for namespace hierarchy [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/service/MetalakeMetaService.java:
##########
@@ -420,6 +423,75 @@ public boolean deleteMetalake(NameIdentifier ident, boolean cascade) {
     return true;
   }
 
+  void deleteMetalakeWithVersion(NameIdentifier identifier, Long metalakeId, Long currentVersion) {
+    int deleted =
+        SessionUtils.getWithoutCommit(
+            MetalakeMetaMapper.class,
+            mapper -> mapper.softDeleteMetalakeMetaByMetalakeId(metalakeId, currentVersion));
+    if (deleted == 0) {
+      throw metalakeWriteFailure(identifier, metalakeId, identifier.name());
+    }
+  }
+
+  private RuntimeException metalakeWriteFailure(
+      NameIdentifier identifier, Long metalakeId, String observedName) {
+    MetalakePO currentMetalakePO =
+        SessionUtils.getWithoutCommit(
+            MetalakeMetaMapper.class, mapper -> mapper.selectMetalakeMetaByIdForUpdate(metalakeId));
+    if (currentMetalakePO == null
+        || !Objects.equals(currentMetalakePO.getMetalakeName(), observedName)) {
+      return new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.METALAKE.name().toLowerCase(),
+          identifier.name());
+    }
+    return optimisticLockException(identifier);
+  }
+
+  private void deleteCatalogsWithVersions(NameIdentifier metalakeIdentifier, Long metalakeId) {
+    List<CatalogPO> catalogPOs =
+        SessionUtils.getWithoutCommit(
+            CatalogMetaMapper.class,
+            mapper -> mapper.listCatalogPOsByMetalakeIdForUpdate(metalakeId));
+    if (catalogPOs.isEmpty()) {
+      return;
+    }
+    int deleted =
+        SessionUtils.getWithoutCommit(
+            CatalogMetaMapper.class,
+            mapper -> mapper.softDeleteCatalogMetasWithVersion(catalogPOs));
+    if (deleted != catalogPOs.size()) {
+      throw new OptimisticLockException(
+          "A catalog under metalake %s was modified concurrently; retry the operation",
+          metalakeIdentifier);
+    }
+  }
+
+  List<SchemaPO> listSchemaPOsForCascade(Long metalakeId) {
+    return SessionUtils.getWithoutCommit(
+        SchemaMetaMapper.class, mapper -> mapper.listSchemaPOsByMetalakeId(metalakeId));
+  }
+
+  private void deleteSchemasWithVersions(
+      NameIdentifier metalakeIdentifier, List<SchemaPO> schemaPOs) {
+    if (schemaPOs.isEmpty()) {
+      return;
+    }
+    int deleted =
+        SessionUtils.getWithoutCommit(
+            SchemaMetaMapper.class, mapper -> mapper.softDeleteSchemaMetasWithVersion(schemaPOs));
+    if (deleted != schemaPOs.size()) {
+      throw new OptimisticLockException(
+          "A schema under metalake %s was modified concurrently; retry the operation",
+          metalakeIdentifier);
+    }
+  }
+
+  private OptimisticLockException optimisticLockException(NameIdentifier identifier) {
+    return new OptimisticLockException(
+        "The metalake %s was modified concurrently; retry the operation", identifier);
+  }

Review Comment:
   Strictly, it's not duplicated code and is only used for the `metalake`. Anyway, we need to refine 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] [#12342] improvement(core): add OCC for namespace hierarchy [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SchemaMetaService.java:
##########
@@ -492,13 +470,151 @@ private List<SchemaPO> listSchemaPOs(Namespace namespace) {
         mapper -> POStorageReadRouting.listPOs(mapper, namespace, ops, Entity.EntityType.SCHEMA));
   }
 
+  private void lockCatalogForSchemaCreate(
+      CatalogPO observedCatalogPO, boolean createsImplicitAncestors) {
+    CatalogPO currentCatalogPO =
+        SessionUtils.getWithoutCommit(
+            CatalogMetaMapper.class,
+            mapper ->
+                createsImplicitAncestors
+                    ? mapper.selectCatalogMetaByIdForUpdate(observedCatalogPO.getCatalogId())

Review Comment:
   You are right. When a create needs to make implicit ancestors, we take
   an exclusive lock on the catalog row, so all other schema creates under
   the same catalog have to wait, even if they use a different path.
   
   We need the exclusive lock here because two concurrent creates can both
   see that an ancestor is missing and both insert it. Under MySQL
   REPEATABLE READ, a shared lock is not enough to stop this.
   
   So this is an accepted tradeoff: correctness first, less concurrency for
   hierarchical creates. I will add this to the PR description.
   
   If it becomes a problem later, we can make the lock smaller: only lock
   the ancestor rows we really need to create, and use the unique
   constraint plus a retry instead of locking the whole catalog row. I can
   do that in a follow-up issue.
   



##########
core/src/main/java/org/apache/gravitino/metalake/MetalakeManager.java:
##########
@@ -358,7 +358,9 @@ public boolean dropMetalake(NameIdentifier ident, boolean force)
             }
 
             return store.delete(ident, EntityType.METALAKE, true);
-          } catch (NoSuchMetalakeException e) {
+          } catch (NoSuchMetalakeException | NoSuchEntityException e) {

Review Comment:
   This is intentional, not a gap. There are two reasons.
   
   First, `catalogCache` is not an entity cache. It caches `CatalogWrapper`
   objects, which hold the live catalog instance and its class loader. A
   metalake has nothing like this, and `MetalakeManager` has no cache field
   at all. The "preload all metalakes" comment in the constructor talks
   about the entity cache in the store, not a cache in the manager.
   
   Second, the entity cache in the store is already invalidated for us.
   `RelationalEntityStore.delete()` calls `cache.invalidate(ident, entityType)`
   in a `finally` block, so it runs both when the delete succeeds and when
   the entity is already gone. So there is no stale entry left for this
   branch to clean up.
   
   Also, in this method the `NoSuchMetalakeException` / `NoSuchEntityException`
   mostly comes from `metalakeInUse()` and `store.list()`, which run before
   we reach the delete.
   



-- 
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] [#12342] improvement(core): add OCC for namespace hierarchy [gravitino]

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

   Close it temporarily.


-- 
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] [#12342] improvement(core): add OCC for namespace hierarchy [gravitino]

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

   > @roryqi
   > 
   > Thanks for the suggestion. I understand it as extracting a common OCC SQL template for update/fence/soft-delete operations, with each provider supplying the table name, ID column, and MyBatis parameter names. After reviewing these statements, I think a generic SQL template would have limited benefit here. Besides the table and ID column, the MyBatis parameter paths, batch collection names, entity-specific SET clauses, and database-specific deleted_at expressions also differ. Passing these as string parameters would hide the final SQL, reduce readability, and move some errors to runtime. I would prefer to keep the entity-specific SQL explicit.
   > 
   > I agree that exact duplication should be removed. A narrower approach would be to reuse DatabaseTimeSQL for database-time expressions and let PostgreSQL providers inherit SQL that is identical to the base provider, keeping overrides only where the SQL dialect actually differs. If more entities later converge on an identical OCC SQL shape, we can revisit a narrowly scoped helper. Would this narrower cleanup address your concern, or do you have a specific interface/template design in mind?
   
   I prefer think further. We can give more constraints about table create SQL standard. Some common column must has the fixed name. Some services must have some specific interfaces.
   
   For example, we have delete_at column in every table, we have a delete interface. Every storage service should implement it.
   
   I think this is possible. We would better have a framework to handle this issue.  We should think more about how to iterate our storage framework. Now, we are using AI to generate the code. It seems not bring much burden.
   But it is still hard for people to review code and maintain our code base.


-- 
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] [#12342] improvement(core): add OCC for namespace hierarchy [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SchemaMetaService.java:
##########
@@ -492,13 +470,151 @@ private List<SchemaPO> listSchemaPOs(Namespace namespace) {
         mapper -> POStorageReadRouting.listPOs(mapper, namespace, ops, Entity.EntityType.SCHEMA));
   }
 
+  private void lockCatalogForSchemaCreate(
+      CatalogPO observedCatalogPO, boolean createsImplicitAncestors) {
+    CatalogPO currentCatalogPO =
+        SessionUtils.getWithoutCommit(
+            CatalogMetaMapper.class,
+            mapper ->
+                createsImplicitAncestors
+                    ? mapper.selectCatalogMetaByIdForUpdate(observedCatalogPO.getCatalogId())
+                    : mapper.selectCatalogMetaByIdForShare(observedCatalogPO.getCatalogId()));
+    if (currentCatalogPO == null
+        || !Objects.equals(currentCatalogPO.getCatalogName(), observedCatalogPO.getCatalogName())
+        || !Objects.equals(currentCatalogPO.getMetalakeId(), observedCatalogPO.getMetalakeId())) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.CATALOG.name().toLowerCase(),
+          observedCatalogPO.getCatalogName());
+    }
+  }
+
+  private void lockCatalogForSchemaDelete(NameIdentifier identifier, SchemaPO observedSchemaPO) {
+    CatalogPO currentCatalogPO =
+        SessionUtils.getWithoutCommit(
+            CatalogMetaMapper.class,
+            mapper -> mapper.selectCatalogMetaByIdForUpdate(observedSchemaPO.getCatalogId()));
+    if (currentCatalogPO == null
+        || !Objects.equals(currentCatalogPO.getCatalogName(), identifier.namespace().level(1))
+        || !Objects.equals(currentCatalogPO.getMetalakeId(), observedSchemaPO.getMetalakeId())) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.CATALOG.name().toLowerCase(),
+          identifier.namespace().level(1));
+    }
+  }
+
+  void lockSchemaForEntityWrite(
+      NameIdentifier entityIdentifier,
+      Long observedSchemaId,
+      Long observedCatalogId,
+      Long observedMetalakeId) {

Review Comment:
   Thanks for catching this. This is a valid cross-instance race, but it predates this PR: the existing TreeLock only serializes schema and child operations within one process, and the relational storage layer has never had a complete schema fence for child update and version-write paths.
   
   A complete fix requires auditing table, view, fileset, topic, function, model, and model-version writes; locking both schemas for table moves; failing zero-row child updates inside the transaction; and adding deterministic concurrency coverage for H2, MySQL, and PostgreSQL. That is a substantial change beyond #12342, which is scoped to OCC for the metalake/catalog/schema namespace hierarchy.
   
   I filed #12406 to track the complete schema-to-child write protocol and will address it in a follow-up PR instead of expanding this already large 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] [#12342] improvement(core): add OCC for namespace hierarchy [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/catalog/ManagedSchemaOperations.java:
##########
@@ -116,9 +117,11 @@ public Schema createSchema(NameIdentifier ident, String comment, Map<String, Str
                     .build())
             .build();
     try {
-      store().put(schemaEntity, true /* overwrite */);
+      store().put(schemaEntity, false /* overwrite */);

Review Comment:
   What is the purpose of changing this to `false`?



-- 
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] [#12342] improvement(core): add OCC for namespace hierarchy [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/utils/POConverters.java:
##########
@@ -138,7 +138,7 @@ public static MetalakePO updateMetalakePOWithVersion(
       MetalakePO oldMetalakePO, BaseMetalake newMetalake) {
     Long lastVersion = oldMetalakePO.getLastVersion();
     // Will set the version to the last version + 1 when having some fields need be multiple version

Review Comment:
   The comment describing version behavior is unclear/grammatically incorrect and no longer matches the implementation (the code now always increments the version). Please reword it to reflect OCC semantics so future readers don’t misinterpret `lastVersion` vs `currentVersion`.



##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SchemaMetaService.java:
##########
@@ -230,15 +231,19 @@ public <E extends Entity & HasIdentifier> SchemaEntity updateSchema(
     AtomicInteger updateResult = new AtomicInteger(0);
     try {
       SessionUtils.doMultipleWithCommit(
-          () ->
-              updateResult.set(
-                  SessionUtils.getWithoutCommit(
-                      SchemaMetaMapper.class,
-                      mapper ->
-                          ops.updatePO(
-                              mapper,
-                              POConverters.updateSchemaPOWithVersion(oldSchemaPO, newEntity),
-                              oldSchemaPO))),
+          () -> {
+            updateResult.set(
+                SessionUtils.getWithoutCommit(
+                    SchemaMetaMapper.class,
+                    mapper ->
+                        ops.updatePO(
+                            mapper,
+                            POConverters.updateSchemaPOWithVersion(oldSchemaPO, newEntity),
+                            oldSchemaPO)));
+            if (updateResult.get() == 0) {
+              throw optimisticLockException(identifier);
+            }

Review Comment:
   `updateSchema` now throws `OptimisticLockException` when the version-CAS update affects 0 rows, but there is no test asserting the service-level conflict behavior for schemas. Please add a regression test that introduces a competing update (or delete) and verifies `OptimisticLockException` is thrown so the OCC contract is covered at the service layer.



##########
core/src/main/java/org/apache/gravitino/storage/relational/service/CatalogMetaService.java:
##########
@@ -229,15 +230,19 @@ public <E extends Entity & HasIdentifier> CatalogEntity updateCatalog(
     AtomicInteger updateResult = new AtomicInteger(0);
     try {
       SessionUtils.doMultipleWithCommit(
-          () ->
-              updateResult.set(
-                  SessionUtils.getWithoutCommit(
-                      CatalogMetaMapper.class,
-                      mapper ->
-                          mapper.updateCatalogMeta(
-                              POConverters.updateCatalogPOWithVersion(
-                                  oldCatalogPO, newEntity, oldCatalogPO.getMetalakeId()),
-                              oldCatalogPO))),
+          () -> {
+            updateResult.set(
+                SessionUtils.getWithoutCommit(
+                    CatalogMetaMapper.class,
+                    mapper ->
+                        mapper.updateCatalogMeta(
+                            POConverters.updateCatalogPOWithVersion(
+                                oldCatalogPO, newEntity, oldCatalogPO.getMetalakeId()),
+                            oldCatalogPO)));
+            if (updateResult.get() == 0) {
+              throw optimisticLockException(identifier);
+            }
+          },

Review Comment:
   `updateCatalog` now throws `OptimisticLockException` when the version-CAS update affects 0 rows, but there is no test asserting the service-level conflict behavior for catalogs (similar to `TestMetalakeMetaService.testAlterReportsOptimisticLockConflict`). Adding a regression test that forces a competing update and then asserts `OptimisticLockException` would ensure the new OCC contract is enforced end-to-end.



##########
core/src/main/java/org/apache/gravitino/storage/relational/service/MetalakeMetaService.java:
##########
@@ -420,6 +425,22 @@ public boolean deleteMetalake(NameIdentifier ident, boolean cascade) {
     return true;
   }
 
+  private void deleteMetalakeWithVersion(
+      NameIdentifier identifier, Long metalakeId, Long currentVersion) {
+    int deleted =
+        SessionUtils.getWithoutCommit(
+            MetalakeMetaMapper.class,
+            mapper -> mapper.softDeleteMetalakeMetaByMetalakeId(metalakeId, currentVersion));
+    if (deleted == 0) {
+      throw optimisticLockException(identifier);

Review Comment:
   `deleteMetalakeWithVersion` now throws `OptimisticLockException` when the version-CAS delete affects 0 rows, but the test suite only covers the alter conflict for metalakes. Please add a regression test that forces a stale delete (e.g., competing update increments the version, then delete with the old version) and asserts `OptimisticLockException`, to cover the new OCC delete behavior.



-- 
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] [#12342] improvement(core): add OCC for namespace hierarchy [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/utils/POConverters.java:
##########
@@ -138,7 +138,7 @@ public static MetalakePO updateMetalakePOWithVersion(
       MetalakePO oldMetalakePO, BaseMetalake newMetalake) {
     Long lastVersion = oldMetalakePO.getLastVersion();
     // Will set the version to the last version + 1 when having some fields need be multiple version

Review Comment:
   Updated the version comments to describe the OCC token explicitly. The converters now advance from currentVersion, and parent fences keep current_version and last_version aligned.



##########
core/src/main/java/org/apache/gravitino/storage/relational/service/MetalakeMetaService.java:
##########
@@ -420,6 +425,22 @@ public boolean deleteMetalake(NameIdentifier ident, boolean cascade) {
     return true;
   }
 
+  private void deleteMetalakeWithVersion(
+      NameIdentifier identifier, Long metalakeId, Long currentVersion) {
+    int deleted =
+        SessionUtils.getWithoutCommit(
+            MetalakeMetaMapper.class,
+            mapper -> mapper.softDeleteMetalakeMetaByMetalakeId(metalakeId, currentVersion));
+    if (deleted == 0) {
+      throw optimisticLockException(identifier);

Review Comment:
   Added TestMetalakeMetaService.testDeleteReportsOptimisticLockConflict. It advances the row with a competing update, invokes the service conditional-delete path with the stale version, and verifies OptimisticLockException plus row preservation.



##########
core/src/main/java/org/apache/gravitino/storage/relational/service/CatalogMetaService.java:
##########
@@ -229,15 +230,19 @@ public <E extends Entity & HasIdentifier> CatalogEntity updateCatalog(
     AtomicInteger updateResult = new AtomicInteger(0);
     try {
       SessionUtils.doMultipleWithCommit(
-          () ->
-              updateResult.set(
-                  SessionUtils.getWithoutCommit(
-                      CatalogMetaMapper.class,
-                      mapper ->
-                          mapper.updateCatalogMeta(
-                              POConverters.updateCatalogPOWithVersion(
-                                  oldCatalogPO, newEntity, oldCatalogPO.getMetalakeId()),
-                              oldCatalogPO))),
+          () -> {
+            updateResult.set(
+                SessionUtils.getWithoutCommit(
+                    CatalogMetaMapper.class,
+                    mapper ->
+                        mapper.updateCatalogMeta(
+                            POConverters.updateCatalogPOWithVersion(
+                                oldCatalogPO, newEntity, oldCatalogPO.getMetalakeId()),
+                            oldCatalogPO)));
+            if (updateResult.get() == 0) {
+              throw optimisticLockException(identifier);
+            }
+          },

Review Comment:
   Added TestCatalogMetaService.testAlterReportsOptimisticLockConflict, which forces a competing committed update and verifies the catalog service reports OptimisticLockException.



##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SchemaMetaService.java:
##########
@@ -230,15 +231,19 @@ public <E extends Entity & HasIdentifier> SchemaEntity updateSchema(
     AtomicInteger updateResult = new AtomicInteger(0);
     try {
       SessionUtils.doMultipleWithCommit(
-          () ->
-              updateResult.set(
-                  SessionUtils.getWithoutCommit(
-                      SchemaMetaMapper.class,
-                      mapper ->
-                          ops.updatePO(
-                              mapper,
-                              POConverters.updateSchemaPOWithVersion(oldSchemaPO, newEntity),
-                              oldSchemaPO))),
+          () -> {
+            updateResult.set(
+                SessionUtils.getWithoutCommit(
+                    SchemaMetaMapper.class,
+                    mapper ->
+                        ops.updatePO(
+                            mapper,
+                            POConverters.updateSchemaPOWithVersion(oldSchemaPO, newEntity),
+                            oldSchemaPO)));
+            if (updateResult.get() == 0) {
+              throw optimisticLockException(identifier);
+            }

Review Comment:
   Added TestSchemaMetaService.testAlterReportsOptimisticLockConflict, which commits a competing mapper update during the service updater and verifies that the service throws OptimisticLockException.



-- 
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] [#12342] improvement(core): add OCC for namespace hierarchy [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/metalake/MetalakeManager.java:
##########
@@ -358,7 +358,9 @@ public boolean dropMetalake(NameIdentifier ident, boolean force)
             }
 
             return store.delete(ident, EntityType.METALAKE, true);
-          } catch (NoSuchMetalakeException e) {
+          } catch (NoSuchMetalakeException | NoSuchEntityException e) {

Review Comment:
   `CatalogManager.dropCatalog`'s equivalent new catch block also invalidates `catalogCache` before returning `false` (to discard the now-stale cache entry). This branch doesn't do the same for whatever metalake-level cache exists — is that intentional (metalakes aren't cached the same way) or a gap?



##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SchemaMetaService.java:
##########
@@ -492,13 +470,151 @@ private List<SchemaPO> listSchemaPOs(Namespace namespace) {
         mapper -> POStorageReadRouting.listPOs(mapper, namespace, ops, Entity.EntityType.SCHEMA));
   }
 
+  private void lockCatalogForSchemaCreate(
+      CatalogPO observedCatalogPO, boolean createsImplicitAncestors) {
+    CatalogPO currentCatalogPO =
+        SessionUtils.getWithoutCommit(
+            CatalogMetaMapper.class,
+            mapper ->
+                createsImplicitAncestors
+                    ? mapper.selectCatalogMetaByIdForUpdate(observedCatalogPO.getCatalogId())

Review Comment:
   Worth flagging as a design tradeoff: any hierarchical schema create (one that materializes implicit ancestors) takes an *exclusive* lock on the whole catalog row, which will block **all** other schema creates under that catalog — not just ones touching the same ancestor path — for the duration of the transaction. That's the right call for correctness, but it means catalogs with heavy concurrent hierarchical schema creation will serialize on this lock. Worth calling out explicitly in the PR description as an accepted throughput tradeoff.



-- 
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] [#12342] improvement(core): add OCC for namespace hierarchy [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SchemaMetaService.java:
##########
@@ -227,20 +234,23 @@ public <E extends Entity & HasIdentifier> SchemaEntity updateSchema(
         NameIdentifierUtil.ofSchema(metalakeName, catalogName, oldSchemaEntity.name()).toString();
     boolean isRenamed = !Objects.equals(oldSchemaEntity.name(), newEntity.name());
 
-    AtomicInteger updateResult = new AtomicInteger(0);
     try {
       SessionUtils.doMultipleWithCommit(
-          () ->
-              updateResult.set(
-                  SessionUtils.getWithoutCommit(
-                      SchemaMetaMapper.class,
-                      mapper ->
-                          ops.updatePO(
-                              mapper,
-                              POConverters.updateSchemaPOWithVersion(oldSchemaPO, newEntity),
-                              oldSchemaPO))),
           () -> {
-            if (isRenamed && updateResult.get() > 0) {
+            int updated =
+                SessionUtils.getWithoutCommit(
+                    SchemaMetaMapper.class,
+                    mapper ->
+                        ops.updatePO(
+                            mapper,
+                            POConverters.updateSchemaPOWithVersion(oldSchemaPO, newEntity),
+                            oldSchemaPO));

Review Comment:
   The observation is accurate — this CAS locks and validates the schema row only, so neither a catalog nor a metalake rename is fenced here. This is intentional.
   
   Rename in Gravitino is identity-preserving: it changes only the name column of the renamed row, and the ids this request already resolved (`metalakeId`/`catalogId`/`schemaId`) keep denoting the same entities. So the write lands on exactly the entity the caller resolved, just one that is now reachable under a different path — nothing is orphaned and no update is lost. The anomaly this PR closes is the other one: the parent is *deleted*, or replaced by a same-named entity with a fresh id, and a stale child write survives it. That case is caught by the id + existence checks these fences already do.
   
   Making a stale fully qualified path fail would require shared locks on the whole ancestor chain, root-to-leaf, on every write in the hierarchy — a metalake row read on every catalog/schema/table/model write. That is a much larger change than this PR, and it buys strictness rather than integrity, so I'd rather track it separately if we decide we want strict path semantics.
   



##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SchemaMetaService.java:
##########
@@ -492,13 +470,151 @@ private List<SchemaPO> listSchemaPOs(Namespace namespace) {
         mapper -> POStorageReadRouting.listPOs(mapper, namespace, ops, Entity.EntityType.SCHEMA));
   }
 
+  private void lockCatalogForSchemaCreate(
+      CatalogPO observedCatalogPO, boolean createsImplicitAncestors) {
+    CatalogPO currentCatalogPO =
+        SessionUtils.getWithoutCommit(
+            CatalogMetaMapper.class,

Review Comment:
   Correct — the create fence revalidates the catalog row, and a metalake rename leaves that row and its `metalakeId` untouched. This is intentional.
   
   Rename in Gravitino is identity-preserving: it changes only the name column of the renamed row, and the ids this request already resolved (`metalakeId`/`catalogId`/`schemaId`) keep denoting the same entities. So the write lands on exactly the entity the caller resolved, just one that is now reachable under a different path — nothing is orphaned and no update is lost. The anomaly this PR closes is the other one: the parent is *deleted*, or replaced by a same-named entity with a fresh id, and a stale child write survives it. That case is caught by the id + existence checks these fences already do.
   
   Making a stale fully qualified path fail would require shared locks on the whole ancestor chain, root-to-leaf, on every write in the hierarchy — a metalake row read on every catalog/schema/table/model write. That is a much larger change than this PR, and it buys strictness rather than integrity, so I'd rather track it separately if we decide we want strict path semantics.
   



##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SchemaMetaService.java:
##########
@@ -492,13 +470,151 @@ private List<SchemaPO> listSchemaPOs(Namespace namespace) {
         mapper -> POStorageReadRouting.listPOs(mapper, namespace, ops, Entity.EntityType.SCHEMA));
   }
 
+  private void lockCatalogForSchemaCreate(
+      CatalogPO observedCatalogPO, boolean createsImplicitAncestors) {
+    CatalogPO currentCatalogPO =
+        SessionUtils.getWithoutCommit(
+            CatalogMetaMapper.class,
+            mapper ->
+                createsImplicitAncestors
+                    ? mapper.selectCatalogMetaByIdForUpdate(observedCatalogPO.getCatalogId())
+                    : mapper.selectCatalogMetaByIdForShare(observedCatalogPO.getCatalogId()));
+    if (currentCatalogPO == null
+        || !Objects.equals(currentCatalogPO.getCatalogName(), observedCatalogPO.getCatalogName())
+        || !Objects.equals(currentCatalogPO.getMetalakeId(), observedCatalogPO.getMetalakeId())) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.CATALOG.name().toLowerCase(),
+          observedCatalogPO.getCatalogName());
+    }
+  }
+
+  private void lockCatalogForSchemaDelete(NameIdentifier identifier, SchemaPO observedSchemaPO) {
+    CatalogPO currentCatalogPO =
+        SessionUtils.getWithoutCommit(
+            CatalogMetaMapper.class,
+            mapper -> mapper.selectCatalogMetaByIdForUpdate(observedSchemaPO.getCatalogId()));

Review Comment:
   Correct — the delete fence takes the catalog row and validates its name and `metalakeId`, neither of which changes when the metalake is renamed. This is intentional.
   
   Rename in Gravitino is identity-preserving: it changes only the name column of the renamed row, and the ids this request already resolved (`metalakeId`/`catalogId`/`schemaId`) keep denoting the same entities. So the write lands on exactly the entity the caller resolved, just one that is now reachable under a different path — nothing is orphaned and no update is lost. The anomaly this PR closes is the other one: the parent is *deleted*, or replaced by a same-named entity with a fresh id, and a stale child write survives it. That case is caught by the id + existence checks these fences already do.
   
   Making a stale fully qualified path fail would require shared locks on the whole ancestor chain, root-to-leaf, on every write in the hierarchy — a metalake row read on every catalog/schema/table/model write. That is a much larger change than this PR, and it buys strictness rather than integrity, so I'd rather track it separately if we decide we want strict path semantics.
   



##########
core/src/main/java/org/apache/gravitino/storage/relational/service/CatalogMetaService.java:
##########
@@ -226,41 +240,37 @@ public <E extends Entity & HasIdentifier> CatalogEntity updateCatalog(
     String oldFullName =
         NameIdentifierUtil.ofCatalog(metalakeName, oldCatalogEntity.name()).toString();
 
-    AtomicInteger updateResult = new AtomicInteger(0);
     try {
       SessionUtils.doMultipleWithCommit(
-          () ->
-              updateResult.set(
-                  SessionUtils.getWithoutCommit(
-                      CatalogMetaMapper.class,
-                      mapper ->
-                          mapper.updateCatalogMeta(
-                              POConverters.updateCatalogPOWithVersion(
-                                  oldCatalogPO, newEntity, oldCatalogPO.getMetalakeId()),
-                              oldCatalogPO))),
           () -> {
-            if (updateResult.get() > 0) {
+            int updated =
+                SessionUtils.getWithoutCommit(
+                    CatalogMetaMapper.class,
+                    mapper ->
+                        mapper.updateCatalogMeta(
+                            POConverters.updateCatalogPOWithVersion(
+                                oldCatalogPO, newEntity, oldCatalogPO.getMetalakeId()),
+                            oldCatalogPO));

Review Comment:
   Correct — this CAS validates the catalog row and its version only, and a metalake rename changes neither. This is intentional.
   
   Rename in Gravitino is identity-preserving: it changes only the name column of the renamed row, and the ids this request already resolved (`metalakeId`/`catalogId`/`schemaId`) keep denoting the same entities. So the write lands on exactly the entity the caller resolved, just one that is now reachable under a different path — nothing is orphaned and no update is lost. The anomaly this PR closes is the other one: the parent is *deleted*, or replaced by a same-named entity with a fresh id, and a stale child write survives it. That case is caught by the id + existence checks these fences already do.
   
   Making a stale fully qualified path fail would require shared locks on the whole ancestor chain, root-to-leaf, on every write in the hierarchy — a metalake row read on every catalog/schema/table/model write. That is a much larger change than this PR, and it buys strictness rather than integrity, so I'd rather track it separately if we decide we want strict path semantics.
   



##########
core/src/main/java/org/apache/gravitino/storage/relational/service/CatalogMetaService.java:
##########
@@ -415,6 +420,72 @@ public boolean deleteCatalog(NameIdentifier identifier, boolean cascade) {
     return true;
   }
 
+  private void deleteCatalogWithVersion(NameIdentifier identifier, CatalogPO observedCatalogPO) {
+    int deleted =
+        SessionUtils.getWithoutCommit(
+            CatalogMetaMapper.class,
+            mapper ->
+                mapper.softDeleteCatalogMetasByCatalogId(
+                    observedCatalogPO.getCatalogId(), observedCatalogPO.getCurrentVersion()));

Review Comment:
   Correct — the catalog delete CAS checks the catalog row and its version, which a metalake rename leaves unchanged. This is intentional.
   
   Rename in Gravitino is identity-preserving: it changes only the name column of the renamed row, and the ids this request already resolved (`metalakeId`/`catalogId`/`schemaId`) keep denoting the same entities. So the write lands on exactly the entity the caller resolved, just one that is now reachable under a different path — nothing is orphaned and no update is lost. The anomaly this PR closes is the other one: the parent is *deleted*, or replaced by a same-named entity with a fresh id, and a stale child write survives it. That case is caught by the id + existence checks these fences already do.
   
   Making a stale fully qualified path fail would require shared locks on the whole ancestor chain, root-to-leaf, on every write in the hierarchy — a metalake row read on every catalog/schema/table/model write. That is a much larger change than this PR, and it buys strictness rather than integrity, so I'd rather track it separately if we decide we want strict path semantics.
   



##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SchemaMetaService.java:
##########
@@ -492,13 +470,151 @@ private List<SchemaPO> listSchemaPOs(Namespace namespace) {
         mapper -> POStorageReadRouting.listPOs(mapper, namespace, ops, Entity.EntityType.SCHEMA));
   }
 
+  private void lockCatalogForSchemaCreate(
+      CatalogPO observedCatalogPO, boolean createsImplicitAncestors) {
+    CatalogPO currentCatalogPO =
+        SessionUtils.getWithoutCommit(
+            CatalogMetaMapper.class,
+            mapper ->
+                createsImplicitAncestors
+                    ? mapper.selectCatalogMetaByIdForUpdate(observedCatalogPO.getCatalogId())
+                    : mapper.selectCatalogMetaByIdForShare(observedCatalogPO.getCatalogId()));
+    if (currentCatalogPO == null
+        || !Objects.equals(currentCatalogPO.getCatalogName(), observedCatalogPO.getCatalogName())
+        || !Objects.equals(currentCatalogPO.getMetalakeId(), observedCatalogPO.getMetalakeId())) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.CATALOG.name().toLowerCase(),
+          observedCatalogPO.getCatalogName());
+    }
+  }
+
+  private void lockCatalogForSchemaDelete(NameIdentifier identifier, SchemaPO observedSchemaPO) {
+    CatalogPO currentCatalogPO =
+        SessionUtils.getWithoutCommit(
+            CatalogMetaMapper.class,
+            mapper -> mapper.selectCatalogMetaByIdForUpdate(observedSchemaPO.getCatalogId()));
+    if (currentCatalogPO == null
+        || !Objects.equals(currentCatalogPO.getCatalogName(), identifier.namespace().level(1))
+        || !Objects.equals(currentCatalogPO.getMetalakeId(), observedSchemaPO.getMetalakeId())) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.CATALOG.name().toLowerCase(),
+          identifier.namespace().level(1));
+    }
+  }
+
+  void lockSchemaForEntityWrite(
+      NameIdentifier entityIdentifier,
+      Long observedSchemaId,
+      Long observedCatalogId,
+      Long observedMetalakeId) {

Review Comment:
   The premise is right: `lockSchemaForEntityWrite` is taken by the child *inserts* and by the cross-schema table move, not by same-schema updates. I looked into each path you named and confirmed the concrete defects:
   
   - `TableMetaService.updateTable` writes the new `table_version_info` row outside the `updateResult > 0` guard, so a lost CAS still commits an active version row. Since the legacy cleanup only removes rows with `deleted_at > 0`, that row is never collected.
   - `FunctionMetaService.updateFunction` discards the meta update result entirely, so a concurrent delete leaves an active orphan version row *and* returns success — a silent lost update.
   - `insertModelVersion` takes no schema fence at all.
   
   All three are pre-existing on `main` and sit outside this PR's scope (metalake/catalog/schema OCC), and this PR is already large, so I'm going to fix them in a follow-up issue rather than grow the diff here.
   
   I don't plan to take the broader suggestion of acquiring the shared schema lock at the start of every child write transaction. Same-schema updates are already mutually exclusive with a cascade delete through the per-row CAS (`current_version` + `deleted_at = 0`) — the defects above are about what the losing transaction commits, not about missing exclusion. Guarding the losing path (and adding the missing fence to `insertModelVersion`) is the smaller and more targeted fix.
   



-- 
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] [#12342] improvement(core): add OCC for namespace hierarchy [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/service/CatalogMetaService.java:
##########
@@ -415,6 +420,72 @@ public boolean deleteCatalog(NameIdentifier identifier, boolean cascade) {
     return true;
   }
 
+  private void deleteCatalogWithVersion(NameIdentifier identifier, CatalogPO observedCatalogPO) {
+    int deleted =
+        SessionUtils.getWithoutCommit(
+            CatalogMetaMapper.class,
+            mapper ->
+                mapper.softDeleteCatalogMetasByCatalogId(
+                    observedCatalogPO.getCatalogId(), observedCatalogPO.getCurrentVersion()));
+    if (deleted == 0) {
+      throw catalogWriteFailure(identifier, observedCatalogPO);
+    }
+  }
+
+  private void lockMetalakeForCatalogCreate(MetalakePO observedMetalakePO) {
+    MetalakePO currentMetalakePO =
+        SessionUtils.getWithoutCommit(
+            MetalakeMetaMapper.class,
+            mapper -> mapper.selectMetalakeMetaByIdForShare(observedMetalakePO.getMetalakeId()));
+    if (currentMetalakePO == null
+        || !Objects.equals(
+            currentMetalakePO.getMetalakeName(), observedMetalakePO.getMetalakeName())) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.METALAKE.name().toLowerCase(),
+          observedMetalakePO.getMetalakeName());
+    }
+  }
+
+  private RuntimeException catalogWriteFailure(
+      NameIdentifier identifier, CatalogPO observedCatalogPO) {
+    CatalogPO currentCatalogPO =
+        SessionUtils.getWithoutCommit(
+            CatalogMetaMapper.class,
+            mapper -> mapper.selectCatalogMetaByIdForUpdate(observedCatalogPO.getCatalogId()));
+    if (currentCatalogPO == null
+        || !Objects.equals(currentCatalogPO.getCatalogName(), observedCatalogPO.getCatalogName())
+        || !Objects.equals(currentCatalogPO.getMetalakeId(), observedCatalogPO.getMetalakeId())) {
+      return new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.CATALOG.name().toLowerCase(),
+          identifier.name());
+    }
+    return optimisticLockException(identifier);
+  }
+
+  private void deleteSchemasWithVersions(NameIdentifier catalogIdentifier, Long catalogId) {
+    List<SchemaPO> schemaPOs =
+        SessionUtils.getWithoutCommit(
+            SchemaMetaMapper.class, mapper -> mapper.listSchemaPOsByCatalogId(catalogId));
+    if (schemaPOs.isEmpty()) {
+      return;
+    }
+    int deleted =
+        SessionUtils.getWithoutCommit(
+            SchemaMetaMapper.class, mapper -> mapper.softDeleteSchemaMetasWithVersion(schemaPOs));
+    if (deleted != schemaPOs.size()) {
+      throw new OptimisticLockException(
+          "A schema under catalog %s was modified concurrently; retry the operation",
+          catalogIdentifier);
+    }
+  }
+
+  private OptimisticLockException optimisticLockException(NameIdentifier identifier) {
+    return new OptimisticLockException(
+        "The catalog %s was modified concurrently; retry the operation", identifier);
+  }

Review Comment:
   We can define this method in the helper method.



-- 
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] [#12342] improvement(core): add OCC for namespace hierarchy [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/service/MetalakeMetaService.java:
##########
@@ -420,6 +423,75 @@ public boolean deleteMetalake(NameIdentifier ident, boolean cascade) {
     return true;
   }
 
+  void deleteMetalakeWithVersion(NameIdentifier identifier, Long metalakeId, Long currentVersion) {
+    int deleted =
+        SessionUtils.getWithoutCommit(
+            MetalakeMetaMapper.class,
+            mapper -> mapper.softDeleteMetalakeMetaByMetalakeId(metalakeId, currentVersion));
+    if (deleted == 0) {
+      throw metalakeWriteFailure(identifier, metalakeId, identifier.name());
+    }
+  }
+
+  private RuntimeException metalakeWriteFailure(
+      NameIdentifier identifier, Long metalakeId, String observedName) {
+    MetalakePO currentMetalakePO =
+        SessionUtils.getWithoutCommit(
+            MetalakeMetaMapper.class, mapper -> mapper.selectMetalakeMetaByIdForUpdate(metalakeId));
+    if (currentMetalakePO == null
+        || !Objects.equals(currentMetalakePO.getMetalakeName(), observedName)) {
+      return new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.METALAKE.name().toLowerCase(),
+          identifier.name());
+    }
+    return optimisticLockException(identifier);
+  }
+
+  private void deleteCatalogsWithVersions(NameIdentifier metalakeIdentifier, Long metalakeId) {
+    List<CatalogPO> catalogPOs =
+        SessionUtils.getWithoutCommit(
+            CatalogMetaMapper.class,
+            mapper -> mapper.listCatalogPOsByMetalakeIdForUpdate(metalakeId));
+    if (catalogPOs.isEmpty()) {
+      return;
+    }
+    int deleted =
+        SessionUtils.getWithoutCommit(
+            CatalogMetaMapper.class,
+            mapper -> mapper.softDeleteCatalogMetasWithVersion(catalogPOs));
+    if (deleted != catalogPOs.size()) {
+      throw new OptimisticLockException(
+          "A catalog under metalake %s was modified concurrently; retry the operation",
+          metalakeIdentifier);
+    }
+  }
+
+  List<SchemaPO> listSchemaPOsForCascade(Long metalakeId) {
+    return SessionUtils.getWithoutCommit(
+        SchemaMetaMapper.class, mapper -> mapper.listSchemaPOsByMetalakeId(metalakeId));
+  }
+
+  private void deleteSchemasWithVersions(
+      NameIdentifier metalakeIdentifier, List<SchemaPO> schemaPOs) {
+    if (schemaPOs.isEmpty()) {
+      return;
+    }
+    int deleted =
+        SessionUtils.getWithoutCommit(
+            SchemaMetaMapper.class, mapper -> mapper.softDeleteSchemaMetasWithVersion(schemaPOs));
+    if (deleted != schemaPOs.size()) {
+      throw new OptimisticLockException(
+          "A schema under metalake %s was modified concurrently; retry the operation",
+          metalakeIdentifier);
+    }
+  }
+
+  private OptimisticLockException optimisticLockException(NameIdentifier identifier) {
+    return new OptimisticLockException(
+        "The metalake %s was modified concurrently; retry the operation", identifier);
+  }

Review Comment:
   You should fix lots of duplications.



-- 
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] [#12342] improvement(core): add OCC for namespace hierarchy [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/catalog/ManagedSchemaOperations.java:
##########
@@ -116,9 +117,11 @@ public Schema createSchema(NameIdentifier ident, String comment, Map<String, Str
                     .build())
             .build();
     try {
-      store().put(schemaEntity, true /* overwrite */);
+      store().put(schemaEntity, false /* overwrite */);

Review Comment:
   The interface is an explicit `create` operation, and we need to change it to false to avoid concurrent insertion of data into the database.



-- 
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] [#12342] improvement(core): add OCC for namespace hierarchy [gravitino]

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

   I really would suggest you split PRs into small one, so that we can have a better review.


-- 
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] [#12342] improvement(core): add OCC for namespace hierarchy [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/metalake/MetalakeManager.java:
##########
@@ -358,7 +358,9 @@ public boolean dropMetalake(NameIdentifier ident, boolean force)
             }
 
             return store.delete(ident, EntityType.METALAKE, true);
-          } catch (NoSuchMetalakeException e) {
+          } catch (NoSuchMetalakeException | NoSuchEntityException e) {

Review Comment:
   First, `catalogCache` is not an entity cache. It caches `CatalogWrapper` objects, which hold the live catalog instance and its class loader. A metalake has nothing like this, and `MetalakeManager` has no cache field
   at all. The "preload all metalakes" comment in the constructor talks about the entity cache in the store, not a cache in the manager.
   
   Second, the entity cache in the store is already invalidated for us. `RelationalEntityStore.delete()` calls `cache.invalidate(ident, entityType)` in a `finally` block, so it runs both when the delete succeeds and when
   the entity is already gone. So there is no stale entry left for this branch to clean up.
   
   Also, in this method the `NoSuchMetalakeException` / `NoSuchEntityException` mostly comes from `metalakeInUse()` and `store.list()`, which run before we reach the delete.



-- 
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] [#12342] improvement(core): add OCC for namespace hierarchy [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SchemaMetaService.java:
##########
@@ -492,13 +470,151 @@ private List<SchemaPO> listSchemaPOs(Namespace namespace) {
         mapper -> POStorageReadRouting.listPOs(mapper, namespace, ops, Entity.EntityType.SCHEMA));
   }
 
+  private void lockCatalogForSchemaCreate(
+      CatalogPO observedCatalogPO, boolean createsImplicitAncestors) {
+    CatalogPO currentCatalogPO =
+        SessionUtils.getWithoutCommit(
+            CatalogMetaMapper.class,
+            mapper ->
+                createsImplicitAncestors
+                    ? mapper.selectCatalogMetaByIdForUpdate(observedCatalogPO.getCatalogId())
+                    : mapper.selectCatalogMetaByIdForShare(observedCatalogPO.getCatalogId()));
+    if (currentCatalogPO == null
+        || !Objects.equals(currentCatalogPO.getCatalogName(), observedCatalogPO.getCatalogName())
+        || !Objects.equals(currentCatalogPO.getMetalakeId(), observedCatalogPO.getMetalakeId())) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.CATALOG.name().toLowerCase(),
+          observedCatalogPO.getCatalogName());
+    }
+  }
+
+  private void lockCatalogForSchemaDelete(NameIdentifier identifier, SchemaPO observedSchemaPO) {
+    CatalogPO currentCatalogPO =
+        SessionUtils.getWithoutCommit(
+            CatalogMetaMapper.class,
+            mapper -> mapper.selectCatalogMetaByIdForUpdate(observedSchemaPO.getCatalogId()));
+    if (currentCatalogPO == null
+        || !Objects.equals(currentCatalogPO.getCatalogName(), identifier.namespace().level(1))
+        || !Objects.equals(currentCatalogPO.getMetalakeId(), observedSchemaPO.getMetalakeId())) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.CATALOG.name().toLowerCase(),
+          identifier.namespace().level(1));
+    }
+  }
+
+  void lockSchemaForEntityWrite(
+      NameIdentifier entityIdentifier,
+      Long observedSchemaId,
+      Long observedCatalogId,
+      Long observedMetalakeId) {

Review Comment:
   This fence is currently used only by child inserts and cross-schema table moves, so it does not prevent all writes after a schema cascade. For example, `updateFunction` can read the function before the cascade, then—after the cascade commits—insert a new function-version row and ignore the zero-row metadata update, committing an active orphan; same-schema `updateTable` similarly commits its new version before reporting failure, and `insertModelVersion` has no schema fence. Acquire this shared schema lock at the start of every child write transaction (and fail inside the transaction when the child CAS/update misses), not only on inserts/moves.



-- 
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] [#12342] improvement(core): add OCC for namespace hierarchy [gravitino]

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

   Use #12454,  #12455, and #12456 to replace this big one. 


-- 
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] [#12342] improvement(core): add OCC for namespace hierarchy [gravitino]

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

   <!-- coverage-report -->
   ### Code Coverage Report
   |Overall Project|68.07% **`+0.43%`**|:green_circle:|
   |:-|:-|:-:|
   |Files changed|85.22%|:green_circle:|
   <br>
   
   |Module|Coverage||
   |:-|:-|:-:|
   |aliyun|1.72%|:red_circle:|
   |api|49.16% **`-0.05%`**|:green_circle:|
   |authorization-common|85.96%|:green_circle:|
   |aws|42.04%|:green_circle:|
   |azure|2.47%|:red_circle:|
   |catalog-common|9.92%|:red_circle:|
   |catalog-fileset|79.74%|:green_circle:|
   |catalog-glue|66.91%|:green_circle:|
   |catalog-hive|79.4%|:green_circle:|
   |catalog-jdbc-common|45.7%|:green_circle:|
   |catalog-jdbc-doris|81.8%|: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|77.01%|:green_circle:|
   |catalog-lakehouse-generic|59.18%|:green_circle:|
   |catalog-lakehouse-hudi|79.1%|:green_circle:|
   |catalog-lakehouse-iceberg|85.93%|:green_circle:|
   |catalog-lakehouse-paimon|84.23%|:green_circle:|
   |catalog-model|77.72%|:green_circle:|
   |cli|44.5%|:green_circle:|
   |client-java|78.27%|:green_circle:|
   |common|52.26% **`+0.03%`**|:green_circle:|
   |core|82.97% **`+0.43%`**|:green_circle:|
   |filesystem-hadoop3|77.28%|:green_circle:|
   |flink|0.0%|:red_circle:|
   |flink-common|48.68%|:green_circle:|
   |flink-runtime|0.0%|:red_circle:|
   |gcp|14.12%|:red_circle:|
   |hadoop-auth|68.0%|:green_circle:|
   |hadoop-common|12.7%|:red_circle:|
   |hive-metastore-common|53.4%|:green_circle:|
   |iceberg-common|64.75%|:green_circle:|
   |iceberg-rest-server|75.02%|:green_circle:|
   |idp-basic|86.02%|:green_circle:|
   |integration-test-common|0.0%|:red_circle:|
   |jobs|66.17%|:green_circle:|
   |lance-common|24.5%|:red_circle:|
   |lance-rest-server|64.23%|:green_circle:|
   |lineage|53.02%|:green_circle:|
   |optimizer|83.24%|:green_circle:|
   |optimizer-api|21.95%|:red_circle:|
   |server|85.9% **`-0.4%`**|:green_circle:|
   |server-common|76.43% **`-1.08%`**|:green_circle:|
   |spark|28.57%|:red_circle:|
   |spark-common|45.89%|:green_circle:|
   |tencent|69.84%|:green_circle:|
   |trino-connector|40.29%|:green_circle:|
   
   <details>
   <summary>Files</summary>
   
   |Module|File|Coverage||
   |:-|:-|:-|:-:|
   |api|[OptimisticLockException.java](https://github.com/yuqi1129/gravitino/blob/7955cfccdcab002de8080f453c5c6883a3a661a6/api/src/main/java/org/apache/gravitino/exceptions/OptimisticLockException.java)|0.0%|:red_circle:|
   |common|[ErrorResponse.java](https://github.com/yuqi1129/gravitino/blob/7955cfccdcab002de8080f453c5c6883a3a661a6/common/src/main/java/org/apache/gravitino/dto/responses/ErrorResponse.java)|54.32%|:red_circle:|
   ||[ErrorConstants.java](https://github.com/yuqi1129/gravitino/blob/7955cfccdcab002de8080f453c5c6883a3a661a6/common/src/main/java/org/apache/gravitino/dto/responses/ErrorConstants.java)|0.0%|:red_circle:|
   |core|[MetalakeMetaService.java](https://github.com/yuqi1129/gravitino/blob/7955cfccdcab002de8080f453c5c6883a3a661a6/core/src/main/java/org/apache/gravitino/storage/relational/service/MetalakeMetaService.java)|99.24%|:green_circle:|
   ||[SchemaMetaService.java](https://github.com/yuqi1129/gravitino/blob/7955cfccdcab002de8080f453c5c6883a3a661a6/core/src/main/java/org/apache/gravitino/storage/relational/service/SchemaMetaService.java)|97.08%|:green_circle:|
   ||[CatalogMetaService.java](https://github.com/yuqi1129/gravitino/blob/7955cfccdcab002de8080f453c5c6883a3a661a6/core/src/main/java/org/apache/gravitino/storage/relational/service/CatalogMetaService.java)|95.88%|:green_circle:|
   ||[MetalakeMetaSQLProviderFactory.java](https://github.com/yuqi1129/gravitino/blob/7955cfccdcab002de8080f453c5c6883a3a661a6/core/src/main/java/org/apache/gravitino/storage/relational/mapper/MetalakeMetaSQLProviderFactory.java)|95.45%|:green_circle:|
   ||[MetalakeMetaBaseSQLProvider.java](https://github.com/yuqi1129/gravitino/blob/7955cfccdcab002de8080f453c5c6883a3a661a6/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/MetalakeMetaBaseSQLProvider.java)|91.67%|:green_circle:|
   ||[POConverters.java](https://github.com/yuqi1129/gravitino/blob/7955cfccdcab002de8080f453c5c6883a3a661a6/core/src/main/java/org/apache/gravitino/storage/relational/utils/POConverters.java)|88.25%|:green_circle:|
   ||[CatalogMetaSQLProviderFactory.java](https://github.com/yuqi1129/gravitino/blob/7955cfccdcab002de8080f453c5c6883a3a661a6/core/src/main/java/org/apache/gravitino/storage/relational/mapper/CatalogMetaSQLProviderFactory.java)|85.19%|:green_circle:|
   ||[CatalogMetaPostgreSQLProvider.java](https://github.com/yuqi1129/gravitino/blob/7955cfccdcab002de8080f453c5c6883a3a661a6/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/CatalogMetaPostgreSQLProvider.java)|83.33%|:green_circle:|
   ||[CatalogMetaBaseSQLProvider.java](https://github.com/yuqi1129/gravitino/blob/7955cfccdcab002de8080f453c5c6883a3a661a6/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/CatalogMetaBaseSQLProvider.java)|82.35%|:green_circle:|
   ||[MetalakeMetaPostgreSQLProvider.java](https://github.com/yuqi1129/gravitino/blob/7955cfccdcab002de8080f453c5c6883a3a661a6/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/MetalakeMetaPostgreSQLProvider.java)|80.0%|:green_circle:|
   ||[SchemaMetaPostgreSQLProvider.java](https://github.com/yuqi1129/gravitino/blob/7955cfccdcab002de8080f453c5c6883a3a661a6/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/SchemaMetaPostgreSQLProvider.java)|77.78%|:green_circle:|
   ||[SchemaMetaSQLProviderFactory.java](https://github.com/yuqi1129/gravitino/blob/7955cfccdcab002de8080f453c5c6883a3a661a6/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SchemaMetaSQLProviderFactory.java)|75.76%|:green_circle:|
   ||[SchemaMetaBaseSQLProvider.java](https://github.com/yuqi1129/gravitino/blob/7955cfccdcab002de8080f453c5c6883a3a661a6/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SchemaMetaBaseSQLProvider.java)|69.57%|:green_circle:|
   ||[CatalogMetaMapper.java](https://github.com/yuqi1129/gravitino/blob/7955cfccdcab002de8080f453c5c6883a3a661a6/core/src/main/java/org/apache/gravitino/storage/relational/mapper/CatalogMetaMapper.java)|0.0%|:red_circle:|
   ||[MetalakeMetaMapper.java](https://github.com/yuqi1129/gravitino/blob/7955cfccdcab002de8080f453c5c6883a3a661a6/core/src/main/java/org/apache/gravitino/storage/relational/mapper/MetalakeMetaMapper.java)|0.0%|:red_circle:|
   ||[SchemaMetaMapper.java](https://github.com/yuqi1129/gravitino/blob/7955cfccdcab002de8080f453c5c6883a3a661a6/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SchemaMetaMapper.java)|0.0%|:red_circle:|
   |server|[ExceptionHandlers.java](https://github.com/yuqi1129/gravitino/blob/7955cfccdcab002de8080f453c5c6883a3a661a6/server/src/main/java/org/apache/gravitino/server/web/rest/ExceptionHandlers.java)|83.33%|:green_circle:|
   |server-common|[Utils.java](https://github.com/yuqi1129/gravitino/blob/7955cfccdcab002de8080f453c5c6883a3a661a6/server-common/src/main/java/org/apache/gravitino/server/web/Utils.java)|50.91%|: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] [#12342] improvement(core): add OCC for namespace hierarchy [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SchemaMetaService.java:
##########
@@ -492,13 +471,78 @@ private List<SchemaPO> listSchemaPOs(Namespace namespace) {
         mapper -> POStorageReadRouting.listPOs(mapper, namespace, ops, Entity.EntityType.SCHEMA));
   }
 
+  private void fenceCatalogForSchemaCreate(CatalogPO catalogPO) {
+    int fenced =
+        SessionUtils.getWithoutCommit(
+            CatalogMetaMapper.class,
+            mapper ->
+                mapper.fenceCatalogMeta(catalogPO.getCatalogId(), catalogPO.getCurrentVersion()));

Review Comment:
   The parent CAS means two overlapping schema creates that both read catalog version N cannot reach the insert sequentially: the winner advances the catalog to N+1, while the loser fails here with OptimisticLockException. For same-name managed creates, that contradicts the stated behavior that the losing create returns SchemaAlreadyExistsException; the current duplicate test is sequential and does not exercise this interleaving. It also makes concurrent creates of unrelated sibling schemas conflict. Could we either use a parent row lock/revalidation strategy or explicitly retry the fence while the parent remains active, and add a true concurrent same-name create test?



##########
core/src/main/java/org/apache/gravitino/storage/relational/service/MetalakeMetaService.java:
##########
@@ -206,30 +210,32 @@ public <E extends Entity & HasIdentifier> BaseMetalake updateMetalake(
       throw re;
     }
 
-    if (updateResult.get() > 0) {
-      return newMetalakeEntity;
-    } else {
-      throw new IOException("Failed to update the entity: " + ident);
-    }
+    return newMetalakeEntity;
   }
 
   @Monitored(
       metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
       baseMetricName = "deleteMetalake")
   public boolean deleteMetalake(NameIdentifier ident, boolean cascade) {
     NameIdentifierUtil.checkMetalake(ident);
-    Long metalakeId = getMetalakeIdByName(ident.name());
+    MetalakePO metalakePO =
+        SessionUtils.getWithoutCommit(
+            MetalakeMetaMapper.class, mapper -> mapper.selectMetalakeMetaByName(ident.name()));
+    if (metalakePO == null) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.METALAKE.name().toLowerCase(),
+          ident.toString());
+    }
+    Long metalakeId = metalakePO.getMetalakeId();
+    Long currentVersion = metalakePO.getCurrentVersion();
     if (metalakeId != null) {
       if (cascade) {
         SessionUtils.doMultipleWithCommit(
-            () ->
-                SessionUtils.doWithoutCommit(
-                    MetalakeMetaMapper.class,
-                    mapper -> mapper.softDeleteMetalakeMetaByMetalakeId(metalakeId)),
-            () ->
-                SessionUtils.doWithoutCommit(
-                    CatalogMetaMapper.class,
-                    mapper -> mapper.softDeleteCatalogMetasByMetalakeId(metalakeId)),
+            () -> {
+              deleteMetalakeWithVersion(ident, metalakeId, currentVersion);
+              deleteCatalogsWithVersions(ident, metalakeId);

Review Comment:
   **Blocking:** This cascade path CAS-deletes catalogs, but the immediately following schema cleanup still soft-deletes schemas only by metalake ID, without checking their observed OCC versions. A concurrent schema alter does not fence the metalake or catalog, so it can commit a newer schema version before that statement; the unconditional cleanup will then delete the newer row and the metalake deletion succeeds instead of reporting an OptimisticLockException. This also contradicts the PR description that descendant schemas and catalogs are CAS-deleted with identifier-and-version pairs. Could we collect the SchemaPOs and batch-delete them by ID/version, verify the affected-row count, and add an interleaving regression 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