jerryshao commented on code in PR #15034:
URL: https://github.com/apache/gravitino/pull/15034#discussion_r4610628420


##########
core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/GlossaryTermRelSQLProvider.java:
##########
@@ -0,0 +1,133 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.gravitino.storage.relational.mapper.provider.base;
+
+import org.apache.gravitino.storage.relational.JDBCBackend.JDBCBackendType;
+import org.apache.ibatis.builder.annotation.ProviderContext;
+
+/** SQL for glossary edges and the per-metalake hierarchy mutex, including 
MySQL 5.7. */
+public final class GlossaryTermRelSQLProvider {
+  private static final String COLUMNS =
+      "r.metalake_id AS metalakeId, r.from_term_id AS fromTermId, "
+          + "r.to_term_id AS toTermId, r.rel_type AS relType, r.deleted_at AS 
deletedAt";
+  private static final String KEY =
+      "metalake_id=#{metalakeId} AND from_term_id=#{fromId} AND 
to_term_id=#{toId} "
+          + "AND rel_type=#{type}";
+
+  private GlossaryTermRelSQLProvider() {}
+
+  /** Creates the mutex row without aborting a concurrent first-use 
transaction. */
+  public static String ensureLock(ProviderContext context) {
+    switch (JDBCBackendType.fromString(context.getDatabaseId())) {
+      case MYSQL:
+        return "INSERT INTO glossary_hierarchy_lock (metalake_id) VALUES 
(#{metalakeId}) "
+            + "ON DUPLICATE KEY UPDATE metalake_id=VALUES(metalake_id)";
+      case POSTGRESQL:
+        return "INSERT INTO glossary_hierarchy_lock (metalake_id) VALUES 
(#{metalakeId}) "
+            + "ON CONFLICT (metalake_id) DO NOTHING";
+      case H2:
+        return "MERGE INTO glossary_hierarchy_lock (metalake_id) KEY 
(metalake_id) "
+            + "VALUES (#{metalakeId})";
+      default:
+        throw new UnsupportedOperationException(
+            "Unsupported glossary database: " + context.getDatabaseId());
+    }
+  }
+
+  /** Locks the mutex until the caller transaction ends. */
+  public static String lockHierarchy() {
+    return "SELECT metalake_id FROM glossary_hierarchy_lock WHERE 
metalake_id=#{metalakeId} FOR UPDATE";
+  }
+
+  /** Locks one live endpoint after the metalake fence and hierarchy mutex. */
+  public static String lockTerm() {
+    return "SELECT term_id FROM glossary_term_meta WHERE 
metalake_id=#{metalakeId} "
+        + "AND term_id=#{termId} AND deleted_at=0 FOR UPDATE";
+  }
+
+  /** Inserts an already canonicalized edge. */
+  public static String insert() {
+    return "INSERT INTO glossary_term_rel (metalake_id, from_term_id, 
to_term_id, rel_type, deleted_at) "
+        + "VALUES (#{metalakeId}, #{fromId}, #{toId}, #{type}, 0)";
+  }
+
+  /** Tests whether a live edge already exists under the hierarchy mutex. */
+  public static String exists() {
+    return "SELECT COUNT(*) FROM glossary_term_rel WHERE " + KEY + " AND 
deleted_at=0";

Review Comment:
   On MySQL REPEATABLE READ this plain SELECT reads the transaction snapshot, 
which may predate the mutex if the caller already did a plain read (e.g. a 
manager wrapping withHierarchyLock), so a concurrently committed live edge is 
missed and insert fails with a duplicate-key error instead of returning false. 
Make it a locking read (FOR SHARE / LOCK IN SHARE MODE on 5.7) or use READ 
COMMITTED for these transactions, and apply the same to listEdges walks done 
under the lock.



##########
core/src/main/java/org/apache/gravitino/storage/relational/service/GlossaryTermMetaService.java:
##########
@@ -202,12 +202,14 @@ public boolean delete(NameIdentifier ident) {
     try {
       return transaction(
           ident.namespace(),
+          true,
           (mapper, metalakeId) -> {
             GlossaryTermPO row = require(mapper, ident, metalakeId);
             long deletedAt = Math.max(1, System.currentTimeMillis());
             requireUpdated(
                 mapper.delete(row.getTermId(), row.getCurrentVersion(), 
deletedAt), ident);
             mapper.deleteSynonyms(row.getTermId(), deletedAt);
+            GlossaryTermRelService.getInstance().removeTerm(metalakeId, 
row.getTermId());

Review Comment:
   delete() runs a plain metalake read (metalake(ns)) before taking the 
hierarchy mutex, so on MySQL lastDeletedAt here sees a stale snapshot and 
nextDeletedAt can reuse a tombstone value already committed for the same edge, 
failing the delete on the primary key. Read lastDeletedAt with a locking read, 
and add a MySQL test where another transaction removes and re-adds an edge 
between the snapshot and the mutex.



##########
core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/GlossaryTermRelSQLProvider.java:
##########
@@ -0,0 +1,133 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.gravitino.storage.relational.mapper.provider.base;
+
+import org.apache.gravitino.storage.relational.JDBCBackend.JDBCBackendType;
+import org.apache.ibatis.builder.annotation.ProviderContext;
+
+/** SQL for glossary edges and the per-metalake hierarchy mutex, including 
MySQL 5.7. */
+public final class GlossaryTermRelSQLProvider {
+  private static final String COLUMNS =
+      "r.metalake_id AS metalakeId, r.from_term_id AS fromTermId, "
+          + "r.to_term_id AS toTermId, r.rel_type AS relType, r.deleted_at AS 
deletedAt";
+  private static final String KEY =
+      "metalake_id=#{metalakeId} AND from_term_id=#{fromId} AND 
to_term_id=#{toId} "
+          + "AND rel_type=#{type}";
+
+  private GlossaryTermRelSQLProvider() {}
+
+  /** Creates the mutex row without aborting a concurrent first-use 
transaction. */
+  public static String ensureLock(ProviderContext context) {
+    switch (JDBCBackendType.fromString(context.getDatabaseId())) {
+      case MYSQL:
+        return "INSERT INTO glossary_hierarchy_lock (metalake_id) VALUES 
(#{metalakeId}) "
+            + "ON DUPLICATE KEY UPDATE metalake_id=VALUES(metalake_id)";
+      case POSTGRESQL:
+        return "INSERT INTO glossary_hierarchy_lock (metalake_id) VALUES 
(#{metalakeId}) "
+            + "ON CONFLICT (metalake_id) DO NOTHING";
+      case H2:
+        return "MERGE INTO glossary_hierarchy_lock (metalake_id) KEY 
(metalake_id) "
+            + "VALUES (#{metalakeId})";
+      default:
+        throw new UnsupportedOperationException(
+            "Unsupported glossary database: " + context.getDatabaseId());
+    }
+  }
+
+  /** Locks the mutex until the caller transaction ends. */
+  public static String lockHierarchy() {
+    return "SELECT metalake_id FROM glossary_hierarchy_lock WHERE 
metalake_id=#{metalakeId} FOR UPDATE";
+  }
+
+  /** Locks one live endpoint after the metalake fence and hierarchy mutex. */
+  public static String lockTerm() {
+    return "SELECT term_id FROM glossary_term_meta WHERE 
metalake_id=#{metalakeId} "
+        + "AND term_id=#{termId} AND deleted_at=0 FOR UPDATE";
+  }
+
+  /** Inserts an already canonicalized edge. */
+  public static String insert() {
+    return "INSERT INTO glossary_term_rel (metalake_id, from_term_id, 
to_term_id, rel_type, deleted_at) "
+        + "VALUES (#{metalakeId}, #{fromId}, #{toId}, #{type}, 0)";
+  }
+
+  /** Tests whether a live edge already exists under the hierarchy mutex. */
+  public static String exists() {
+    return "SELECT COUNT(*) FROM glossary_term_rel WHERE " + KEY + " AND 
deleted_at=0";
+  }
+
+  /** Retires one live edge. The caller supplies a collision-free tombstone 
time. */
+  public static String remove() {
+    return "UPDATE glossary_term_rel SET deleted_at=#{deletedAt} WHERE "
+        + KEY
+        + " AND deleted_at=0";
+  }
+
+  /** Reads the latest tombstone time under the metalake's hierarchy mutex or 
deletion fence. */
+  public static String lastDeletedAt() {
+    return "SELECT COALESCE(MAX(deleted_at), 0) FROM glossary_term_rel WHERE 
metalake_id=#{metalakeId}";
+  }
+
+  /** Retires every edge touching a term in the caller's deletion transaction. 
*/
+  public static String removeTerm() {
+    return "UPDATE glossary_term_rel SET deleted_at=#{deletedAt} WHERE 
metalake_id=#{metalakeId} "
+        + "AND (from_term_id=#{termId} OR to_term_id=#{termId}) AND 
deleted_at=0";
+  }
+
+  /** Retires all live edges of a metalake under its exclusive deletion fence. 
*/
+  public static String dropMetalake() {
+    return "UPDATE glossary_term_rel SET deleted_at=#{deletedAt} WHERE 
metalake_id=#{metalakeId} AND deleted_at=0";
+  }
+
+  /** Removes the mutex of a deleted metalake under its exclusive deletion 
fence. */
+  public static String dropLock() {
+    return "DELETE FROM glossary_hierarchy_lock WHERE 
metalake_id=#{metalakeId}";
+  }
+
+  /** Reads one complete frontier, excluding deleted endpoints, without 
recursive SQL or locks. */
+  public static String listEdges() {
+    return "<script>SELECT "
+        + COLUMNS
+        + " FROM glossary_term_rel r "
+        + "JOIN glossary_term_meta f ON f.term_id=r.from_term_id AND 
f.metalake_id=r.metalake_id AND f.deleted_at=0 "
+        + "JOIN glossary_term_meta t ON t.term_id=r.to_term_id AND 
t.metalake_id=r.metalake_id AND t.deleted_at=0 "
+        + "JOIN metalake_meta m ON m.metalake_id=r.metalake_id AND 
m.deleted_at=0 "
+        + "WHERE r.metalake_id=#{metalakeId} AND r.deleted_at=0 AND 
r.rel_type=#{type} AND ("
+        + "<choose><when 
test='reverse'>r.to_term_id</when><otherwise>r.from_term_id</otherwise></choose>
 IN "
+        + "<foreach collection='ids' item='id' open='(' separator=',' 
close=')'>#{id}</foreach>"

Review Comment:
   Frontier IDs are expanded into one unbounded IN list, so a wide hierarchy 
can produce very large statements and hit driver or database parameter limits. 
Chunk frontiers in readEdges (e.g. 500-1000 IDs per query).



##########
core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/GlossaryTermRelSQLProvider.java:
##########
@@ -0,0 +1,133 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.gravitino.storage.relational.mapper.provider.base;
+
+import org.apache.gravitino.storage.relational.JDBCBackend.JDBCBackendType;
+import org.apache.ibatis.builder.annotation.ProviderContext;
+
+/** SQL for glossary edges and the per-metalake hierarchy mutex, including 
MySQL 5.7. */
+public final class GlossaryTermRelSQLProvider {
+  private static final String COLUMNS =
+      "r.metalake_id AS metalakeId, r.from_term_id AS fromTermId, "
+          + "r.to_term_id AS toTermId, r.rel_type AS relType, r.deleted_at AS 
deletedAt";
+  private static final String KEY =
+      "metalake_id=#{metalakeId} AND from_term_id=#{fromId} AND 
to_term_id=#{toId} "
+          + "AND rel_type=#{type}";
+
+  private GlossaryTermRelSQLProvider() {}
+
+  /** Creates the mutex row without aborting a concurrent first-use 
transaction. */
+  public static String ensureLock(ProviderContext context) {
+    switch (JDBCBackendType.fromString(context.getDatabaseId())) {
+      case MYSQL:
+        return "INSERT INTO glossary_hierarchy_lock (metalake_id) VALUES 
(#{metalakeId}) "
+            + "ON DUPLICATE KEY UPDATE metalake_id=VALUES(metalake_id)";
+      case POSTGRESQL:
+        return "INSERT INTO glossary_hierarchy_lock (metalake_id) VALUES 
(#{metalakeId}) "
+            + "ON CONFLICT (metalake_id) DO NOTHING";
+      case H2:
+        return "MERGE INTO glossary_hierarchy_lock (metalake_id) KEY 
(metalake_id) "
+            + "VALUES (#{metalakeId})";
+      default:
+        throw new UnsupportedOperationException(
+            "Unsupported glossary database: " + context.getDatabaseId());
+    }
+  }
+
+  /** Locks the mutex until the caller transaction ends. */
+  public static String lockHierarchy() {
+    return "SELECT metalake_id FROM glossary_hierarchy_lock WHERE 
metalake_id=#{metalakeId} FOR UPDATE";
+  }
+
+  /** Locks one live endpoint after the metalake fence and hierarchy mutex. */
+  public static String lockTerm() {
+    return "SELECT term_id FROM glossary_term_meta WHERE 
metalake_id=#{metalakeId} "
+        + "AND term_id=#{termId} AND deleted_at=0 FOR UPDATE";
+  }
+
+  /** Inserts an already canonicalized edge. */
+  public static String insert() {
+    return "INSERT INTO glossary_term_rel (metalake_id, from_term_id, 
to_term_id, rel_type, deleted_at) "
+        + "VALUES (#{metalakeId}, #{fromId}, #{toId}, #{type}, 0)";
+  }
+
+  /** Tests whether a live edge already exists under the hierarchy mutex. */
+  public static String exists() {
+    return "SELECT COUNT(*) FROM glossary_term_rel WHERE " + KEY + " AND 
deleted_at=0";
+  }
+
+  /** Retires one live edge. The caller supplies a collision-free tombstone 
time. */
+  public static String remove() {
+    return "UPDATE glossary_term_rel SET deleted_at=#{deletedAt} WHERE "
+        + KEY
+        + " AND deleted_at=0";
+  }
+
+  /** Reads the latest tombstone time under the metalake's hierarchy mutex or 
deletion fence. */
+  public static String lastDeletedAt() {
+    return "SELECT COALESCE(MAX(deleted_at), 0) FROM glossary_term_rel WHERE 
metalake_id=#{metalakeId}";

Review Comment:
   This MAX query has the same snapshot problem as exists(): it is the only 
thing preventing tombstone collisions, so it must see the latest committed 
rows. Add FOR SHARE (LOCK IN SHARE MODE on MySQL 5.7) or compute it via a 
current read.



##########
core/src/main/java/org/apache/gravitino/storage/relational/service/GlossaryTermRelService.java:
##########
@@ -0,0 +1,318 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.gravitino.storage.relational.service;
+
+import com.google.common.base.Preconditions;
+import java.util.Collections;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.function.Supplier;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.storage.relational.mapper.GlossaryTermRelMapper;
+import org.apache.gravitino.storage.relational.mapper.MetalakeMetaMapper;
+import org.apache.gravitino.storage.relational.po.GlossaryTermRelPO;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+
+/**
+ * Stores glossary edges and serializes hierarchy changes per metalake using a 
database mutex.
+ *
+ * <p>Writes join an enclosing SessionUtils transaction or commit their own. 
Lock order is the live
+ * metalake fence, hierarchy mutex, then live term rows in ascending ID order. 
A missing metalake or
+ * endpoint throws NoSuchEntityException. Duplicate additions and absent 
removals return false.
+ * RELATED pairs are stored with the lower ID first. Self-links are rejected 
with
+ * IllegalArgumentException; cycles, depth, ancestor/RELATED overlap, 
authorization, revisions and
+ * audit changes belong to the manager (T4/T5), not this storage layer.
+ *
+ * <p>Use withHierarchyLock around the complete read/validate/write operation, 
before locking any
+ * terms. Multiple changes must plan and lock all their term IDs in order 
before making changes.
+ * Plain reads take no locks and return only live endpoints. Each frontier has 
a statement snapshot;
+ * a multi-level walk needs an enclosing hierarchy lock for a stable graph. 
These ID-only reads do
+ * not apply authorization/status filters: the manager must filter each 
frontier before expanding
+ * it.
+ */
+public final class GlossaryTermRelService {
+  private static final GlossaryTermRelService INSTANCE = new 
GlossaryTermRelService();
+
+  /** The two persisted edge kinds. BROADER points from child to parent. */
+  public enum RelationType {
+    /** A directed child-to-parent edge. */
+    BROADER,
+    /** An undirected pair stored in ascending ID order. */
+    RELATED
+  }
+
+  private GlossaryTermRelService() {}
+
+  /** Returns the shared relation storage service. */
+  public static GlossaryTermRelService getInstance() {
+    return INSTANCE;
+  }
+
+  /**
+   * Runs work under the live metalake fence and exclusive database hierarchy 
mutex. The lock stays
+   * held until the outermost transaction commits or rolls back, including 
after this method
+   * returns. Cached reads made before acquiring the lock are discarded. A 
standalone failure rolls
+   * back this operation. Nested transactions have no savepoints: an enclosing 
owner must propagate
+   * the failure or explicitly roll back, rather than catch it and commit 
partial work. The callback
+   * must not acquire new locks earlier than the hierarchy mutex in lock 
order. Reacquiring an
+   * already-held parent fence in the same mode (as add/remove do) is safe.
+   *
+   * @param metalakeId the live metalake ID
+   * @param work the complete read/validate/write operation
+   * @param <T> the result type
+   * @return the callback result
+   */
+  public <T> T withHierarchyLock(long metalakeId, Supplier<T> work) {
+    Preconditions.checkArgument(work != null, "work cannot be null");
+    return SessionUtils.doWithCommitAndFetchResult(
+        GlossaryTermRelMapper.class,
+        mapper -> {
+          SessionUtils.clearSessionCache();
+          if (SessionUtils.getWithoutCommit(
+                  MetalakeMetaMapper.class, m -> 
m.selectMetalakeMetaByIdForShare(metalakeId))
+              == null) {
+            throw new NoSuchEntityException("Metalake %s does not exist", 
metalakeId);
+          }
+          lockHierarchy(metalakeId);
+          return work.get();
+        });
+  }
+
+  /**
+   * Adds an edge if absent, verifying both live endpoints in this metalake. 
Graph semantic checks
+   * and revision changes are the caller's responsibility under 
withHierarchyLock.
+   */
+  public boolean add(long metalakeId, long fromId, long toId, RelationType 
type) {
+    checkEdge(fromId, toId, type);
+    long from = type == RelationType.RELATED ? Math.min(fromId, toId) : fromId;
+    long to = type == RelationType.RELATED ? Math.max(fromId, toId) : toId;
+    return withHierarchyLock(
+        metalakeId,
+        () -> {
+          lockTerms(metalakeId, Set.of(from, to));
+          return SessionUtils.getWithoutCommit(
+              GlossaryTermRelMapper.class,
+              mapper -> {
+                if (mapper.exists(metalakeId, from, to, type.name()) != 0) {
+                  return false;
+                }
+                mapper.insert(metalakeId, from, to, type.name());
+                return true;
+              });
+        });
+  }
+
+  /** Removes a live edge if present. Both endpoints must still exist in this 
metalake. */
+  public boolean remove(long metalakeId, long fromId, long toId, RelationType 
type) {
+    checkEdge(fromId, toId, type);
+    long from = type == RelationType.RELATED ? Math.min(fromId, toId) : fromId;
+    long to = type == RelationType.RELATED ? Math.max(fromId, toId) : toId;
+    return withHierarchyLock(
+        metalakeId,
+        () -> {
+          lockTerms(metalakeId, Set.of(from, to));
+          return SessionUtils.getWithoutCommit(
+              GlossaryTermRelMapper.class,
+              mapper ->
+                  mapper.remove(
+                          metalakeId, from, to, type.name(), 
nextDeletedAt(mapper, metalakeId))
+                      == 1);
+        });
+  }
+
+  /**
+   * Locks a planned set of live endpoints in ascending ID order in an 
existing hierarchy-locked
+   * transaction. Call before writes when an operation changes several edges; 
it must include all
+   * endpoints. A missing endpoint fails the transaction rather than silently 
dropping an edge.
+   */
+  public void lockTerms(long metalakeId, Set<Long> termIds) {
+    checkIds(termIds);
+    Preconditions.checkState(
+        SessionUtils.isInTransaction(), "Term locks require a hierarchy-locked 
transaction");

Review Comment:
   lockTerms is public and the message says it needs a hierarchy-locked 
transaction, but it only checks that some transaction exists, so a caller can 
lock terms before the mutex and break the documented lock order. Track that the 
mutex is held (e.g. a thread-local set in lockHierarchy) and check that instead.



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

To unsubscribe, e-mail: [email protected]

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

Reply via email to