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

yuqi1129 pushed a commit to branch glossary-term-dev
in repository https://gitbox.apache.org/repos/asf/gravitino.git


The following commit(s) were added to refs/heads/glossary-term-dev by this push:
     new d5d120312c [#14988] feat(core): Add glossary term relation storage 
(#15034)
d5d120312c is described below

commit d5d120312ca2176ca6a71986bbc3c319e2ecfd00
Author: Qi Yu <[email protected]>
AuthorDate: Thu Nov 19 09:00:46 2026 +0800

    [#14988] feat(core): Add glossary term relation storage (#15034)
    
    ### What changes were proposed in this pull request?
    
    Implement glossary design task T3 on top of #14992: store directed
    BROADER edges and canonical RELATED pairs, list relations in both
    directions, and walk ancestors/descendants with one query per batch of
    up to 500 frontier IDs.
    
    Add a per-metalake database hierarchy mutex with concurrent first-use
    initialization on H2, MySQL and PostgreSQL. The transaction entry point
    holds the live parent fence and mutex through outermost commit, with
    fresh reads after locking. Gravitino explicitly opens its MyBatis
    sessions at READ_COMMITTED on all three backends. Callers can supply the
    complete set of term IDs to the hierarchy-lock callback to acquire the
    mutex before locking those terms. Each edge write acquires the parent
    fence, hierarchy mutex and endpoint locks even inside a manager-planned
    batch. This repeats five SQL statements per nested edge change and keeps
    the standalone write path safe. Nested failures require the outer
    transaction owner to propagate the error or roll back; there are no
    savepoints.
    
    Include table/column comments, fresh schemas and upgrade scripts,
    term/metalake deletion cleanup, collision-free relation tombstones and
    indexed, bounded garbage collection through the existing glossary GC
    entry point.
    
    ### Why are the changes needed?
    
    Provide relation persistence and the shared transaction mutex needed by
    the glossary manager. #14992 has merged. This branch is rebased onto
    `glossary-term-dev` at `6e1afe00ff`; the diff contains only T3
    relation-storage changes.
    
    Fixes #14988
    
    ### Does this PR introduce _any_ user-facing change?
    
    No REST endpoints or new configuration. Cycle/depth/RELATED-overlap
    checks, authorization, name/synonym checks and revision/audit updates
    remain manager work in T4/T5. Plain relation reads use statement
    snapshots; a stable multi-level walk requires an enclosing
    hierarchy-lock transaction. Manager reads must filter each frontier
    before expanding it.
    
    ### How was this patch tested?
    
    - At `a2bbb73aeb`, the 44 focused H2 tests passed (18 definitions, 12
    relations and 14 SQL-script cases). Removing the parent-name check made
    the rename/delete race test fail. Skipping glossary cleanup during
    non-cascading metalake deletion made the stored-tombstone assertion
    fail. Both checks passed after restoring the implementation.
    - At `42ad61e9bd`, H2, MySQL and PostgreSQL each passed all 41 targeted
    cases (11 relation, 16 definition and 14 SQL-script cases). The core
    unit job also passed. [CI
    
results](https://github.com/yuqi1129/gravitino/actions/runs/44263467124/attempts/2)
    - Five concurrency tests run 20 rounds each, covering mutex
    initialization and exclusion, outer commit and rollback, and deletion
    races. A separate two-transaction test checks duplicate detection and
    tombstone allocation after a peer removes and re-adds an edge.
    - A diamond walk takes five queries. A 501-ID frontier takes two in
    either direction and preserves edge order. Temporarily switching to
    per-term queries or raising the batch limit to 1,000 made the
    corresponding query-count assertion fail.
    - Storage tests cover canonical pairs, live endpoints, term and metalake
    cleanup, bounded GC, fresh schemas and repeated upgrades. Core Spotless
    and the cumulative diff check passed.
---
 .../relational/mapper/GlossaryTermRelMapper.java   | 116 ++++
 .../provider/DefaultMapperPackageProvider.java     |   2 +
 .../provider/base/GlossaryTermRelSQLProvider.java  | 133 +++++
 .../storage/relational/po/GlossaryTermRelPO.java   |  34 ++
 .../service/GlossaryTermMetaService.java           |  56 +-
 .../relational/service/GlossaryTermRelService.java | 340 ++++++++++++
 .../apache/gravitino/storage/TestSQLScripts.java   |  36 ++
 .../relational/service/GlossaryInvariants.java     |  33 ++
 .../service/TestGlossaryTermMetaService.java       |  39 +-
 .../service/TestGlossaryTermRelService.java        | 616 +++++++++++++++++++++
 design-docs/glossary-design.md                     |  17 +-
 scripts/h2/schema-2.0.0-h2.sql                     |  24 +
 scripts/h2/upgrade-1.3.0-to-2.0.0-h2.sql           |  24 +
 scripts/mysql/schema-2.0.0-mysql.sql               |  16 +
 scripts/mysql/upgrade-1.3.0-to-2.0.0-mysql.sql     |  16 +
 scripts/postgresql/schema-2.0.0-postgresql.sql     |  24 +
 .../upgrade-1.3.0-to-2.0.0-postgresql.sql          |  24 +
 17 files changed, 1523 insertions(+), 27 deletions(-)

diff --git 
a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/GlossaryTermRelMapper.java
 
b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/GlossaryTermRelMapper.java
new file mode 100644
index 0000000000..0f24e68de6
--- /dev/null
+++ 
b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/GlossaryTermRelMapper.java
@@ -0,0 +1,116 @@
+/*
+ * 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;
+
+import java.util.Collection;
+import java.util.List;
+import javax.annotation.Nullable;
+import 
org.apache.gravitino.storage.relational.mapper.provider.base.GlossaryTermRelSQLProvider;
+import org.apache.gravitino.storage.relational.po.GlossaryTermRelPO;
+import org.apache.ibatis.annotations.DeleteProvider;
+import org.apache.ibatis.annotations.InsertProvider;
+import org.apache.ibatis.annotations.Options;
+import org.apache.ibatis.annotations.Options.FlushCachePolicy;
+import org.apache.ibatis.annotations.Param;
+import org.apache.ibatis.annotations.SelectProvider;
+import org.apache.ibatis.annotations.UpdateProvider;
+
+/** Glossary edges and hierarchy locks in the caller transaction. */
+public interface GlossaryTermRelMapper {
+  /** Creates the mutex row safely on first use. */
+  @InsertProvider(type = GlossaryTermRelSQLProvider.class, method = 
"ensureLock")
+  void ensureLock(@Param("metalakeId") long metalakeId);
+
+  /** Locks the existing hierarchy mutex in the caller transaction. */
+  @Nullable
+  @Options(useCache = false, flushCache = FlushCachePolicy.TRUE)
+  @SelectProvider(type = GlossaryTermRelSQLProvider.class, method = 
"lockHierarchy")
+  Long lockHierarchy(@Param("metalakeId") long metalakeId);
+
+  /** Locks a live term in this metalake, or returns null. */
+  @Nullable
+  @Options(useCache = false, flushCache = FlushCachePolicy.TRUE)
+  @SelectProvider(type = GlossaryTermRelSQLProvider.class, method = "lockTerm")
+  Long lockTerm(@Param("metalakeId") long metalakeId, @Param("termId") long 
termId);
+
+  /** Inserts a live canonical edge under the hierarchy mutex. */
+  @InsertProvider(type = GlossaryTermRelSQLProvider.class, method = "insert")
+  int insert(
+      @Param("metalakeId") long metalakeId,
+      @Param("fromId") long fromId,
+      @Param("toId") long toId,
+      @Param("type") String type);
+
+  /** Counts matching live edges. */
+  @Options(useCache = false, flushCache = FlushCachePolicy.TRUE)
+  @SelectProvider(type = GlossaryTermRelSQLProvider.class, method = "exists")
+  int exists(
+      @Param("metalakeId") long metalakeId,
+      @Param("fromId") long fromId,
+      @Param("toId") long toId,
+      @Param("type") String type);
+
+  /** Soft-deletes the matching live edge. */
+  @UpdateProvider(type = GlossaryTermRelSQLProvider.class, method = "remove")
+  int remove(
+      @Param("metalakeId") long metalakeId,
+      @Param("fromId") long fromId,
+      @Param("toId") long toId,
+      @Param("type") String type,
+      @Param("deletedAt") long deletedAt);
+
+  /** Returns the greatest retained deletion timestamp, or zero. */
+  @Options(useCache = false, flushCache = FlushCachePolicy.TRUE)
+  @SelectProvider(type = GlossaryTermRelSQLProvider.class, method = 
"lastDeletedAt")
+  long lastDeletedAt(@Param("metalakeId") long metalakeId);
+
+  /** Retires all edges touching a deleted term. */
+  @UpdateProvider(type = GlossaryTermRelSQLProvider.class, method = 
"removeTerm")
+  void removeTerm(
+      @Param("metalakeId") long metalakeId,
+      @Param("termId") long termId,
+      @Param("deletedAt") long deletedAt);
+
+  /** Retires all edges of a deleted metalake. */
+  @UpdateProvider(type = GlossaryTermRelSQLProvider.class, method = 
"dropMetalake")
+  void dropMetalake(@Param("metalakeId") long metalakeId, @Param("deletedAt") 
long deletedAt);
+
+  /** Removes the mutex under the exclusive metalake deletion fence. */
+  @DeleteProvider(type = GlossaryTermRelSQLProvider.class, method = "dropLock")
+  void dropLock(@Param("metalakeId") long metalakeId);
+
+  /** Reads one nonempty frontier batch with live endpoints in a single 
statement. */
+  @Options(useCache = false, flushCache = FlushCachePolicy.TRUE)
+  @SelectProvider(type = GlossaryTermRelSQLProvider.class, method = 
"listEdges")
+  List<GlossaryTermRelPO> listEdges(
+      @Param("metalakeId") long metalakeId,
+      @Param("ids") Collection<Long> ids,
+      @Param("type") String type,
+      @Param("reverse") boolean reverse);
+
+  /** Selects a bounded batch of expired generations. */
+  @Options(useCache = false, flushCache = FlushCachePolicy.TRUE)
+  @SelectProvider(type = GlossaryTermRelSQLProvider.class, method = "expired")
+  List<GlossaryTermRelPO> expired(@Param("cutoff") long cutoff, 
@Param("limit") int limit);
+
+  /** Deletes the exact expired generation, not the live replacement. */
+  @DeleteProvider(type = GlossaryTermRelSQLProvider.class, method = "purge")
+  int purge(@Param("p") GlossaryTermRelPO p);
+}
diff --git 
a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/DefaultMapperPackageProvider.java
 
b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/DefaultMapperPackageProvider.java
index 0cd1ee0e2b..e10341e3f9 100644
--- 
a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/DefaultMapperPackageProvider.java
+++ 
b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/DefaultMapperPackageProvider.java
@@ -29,6 +29,7 @@ import 
org.apache.gravitino.storage.relational.mapper.FilesetVersionMapper;
 import org.apache.gravitino.storage.relational.mapper.FunctionMetaMapper;
 import 
org.apache.gravitino.storage.relational.mapper.FunctionVersionMetaMapper;
 import org.apache.gravitino.storage.relational.mapper.GlossaryTermMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.GlossaryTermRelMapper;
 import org.apache.gravitino.storage.relational.mapper.GroupMetaMapper;
 import org.apache.gravitino.storage.relational.mapper.GroupRoleRelMapper;
 import org.apache.gravitino.storage.relational.mapper.JobMetaMapper;
@@ -103,6 +104,7 @@ public class DefaultMapperPackageProvider implements 
MapperPackageProvider {
         TagMetadataObjectRelMapper.class,
         TagMetaMapper.class,
         GlossaryTermMetaMapper.class,
+        GlossaryTermRelMapper.class,
         TopicMetaMapper.class,
         UserMetaMapper.class,
         UserRoleRelMapper.class,
diff --git 
a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/GlossaryTermRelSQLProvider.java
 
b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/GlossaryTermRelSQLProvider.java
new file mode 100644
index 0000000000..9d75d87cd8
--- /dev/null
+++ 
b/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 frontier batch, 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>"
+        + "<if test='type == &quot;RELATED&quot;'> OR r.to_term_id IN "
+        + "<foreach collection='ids' item='id' open='(' separator=',' 
close=')'>#{id}</foreach></if>"
+        + ") ORDER BY r.from_term_id, r.to_term_id</script>";
+  }
+
+  /** Selects a bounded batch of retired edges for garbage collection. */
+  public static String expired() {
+    return "SELECT "
+        + COLUMNS
+        + " FROM glossary_term_rel r WHERE r.deleted_at>0 "
+        + "AND r.deleted_at<#{cutoff} ORDER BY 
r.deleted_at,r.from_term_id,r.to_term_id,r.rel_type LIMIT #{limit}";
+  }
+
+  /** Deletes only the selected retired generation, never a newly added live 
edge. */
+  public static String purge() {
+    return "DELETE FROM glossary_term_rel WHERE metalake_id=#{p.metalakeId} 
AND from_term_id=#{p.fromTermId} "
+        + "AND to_term_id=#{p.toTermId} AND rel_type=#{p.relType} AND 
deleted_at=#{p.deletedAt} AND deleted_at>0";
+  }
+}
diff --git 
a/core/src/main/java/org/apache/gravitino/storage/relational/po/GlossaryTermRelPO.java
 
b/core/src/main/java/org/apache/gravitino/storage/relational/po/GlossaryTermRelPO.java
new file mode 100644
index 0000000000..0d96ce7bdb
--- /dev/null
+++ 
b/core/src/main/java/org/apache/gravitino/storage/relational/po/GlossaryTermRelPO.java
@@ -0,0 +1,34 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.gravitino.storage.relational.po;
+
+import lombok.Getter;
+import lombok.Setter;
+
+/** A glossary relation row, including its soft-deletion identity. */
+@Getter
+@Setter
+public class GlossaryTermRelPO {
+  private Long metalakeId;
+  private Long fromTermId;
+  private Long toTermId;
+  private String relType;
+  private Long deletedAt;
+}
diff --git 
a/core/src/main/java/org/apache/gravitino/storage/relational/service/GlossaryTermMetaService.java
 
b/core/src/main/java/org/apache/gravitino/storage/relational/service/GlossaryTermMetaService.java
index 0b933e4b9a..d568aae626 100644
--- 
a/core/src/main/java/org/apache/gravitino/storage/relational/service/GlossaryTermMetaService.java
+++ 
b/core/src/main/java/org/apache/gravitino/storage/relational/service/GlossaryTermMetaService.java
@@ -197,22 +197,27 @@ public final class GlossaryTermMetaService {
     }
   }
 
-  /** Soft-deletes a definition and all its synonyms; a missing definition 
returns false. */
+  /**
+   * Soft-deletes the definition, synonyms and incident edges. Returns false 
if the term is absent
+   * in a live metalake.
+   *
+   * @throws NoSuchEntityException if the parent metalake is absent or 
disappears before locking
+   */
   public boolean delete(NameIdentifier ident) {
-    try {
-      return transaction(
-          ident.namespace(),
-          (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);
-            return true;
-          });
-    } catch (NoSuchEntityException e) {
-      return false;
-    }
+    return transaction(
+        ident.namespace(),
+        true,
+        (mapper, metalakeId) -> {
+          GlossaryTermPO row = mapper.getForUpdate(metalakeId, 
GlossaryTermNames.key(ident.name()));
+          if (row == null) {
+            return false;
+          }
+          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());
+          return true;
+        });
   }
 
   /** Soft-deletes definitions and synonyms inside the metalake deletion 
transaction. */
@@ -223,16 +228,22 @@ public final class GlossaryTermMetaService {
         mapper -> {
           mapper.dropMetalake(metalakeId, deletedAt);
           mapper.dropMetalakeSynonyms(metalakeId, deletedAt);
+          GlossaryTermRelService.getInstance().dropMetalake(metalakeId);
         });
   }
 
-  /** Purges at most limit expired definitions and their deleted synonyms 
atomically. */
+  /**
+   * Purges at most limit expired relations/definitions and the definitions' 
synonyms atomically.
+   */
   public int collect(long cutoff, int limit) {
     return SessionUtils.doWithCommitAndFetchResult(
         GlossaryTermMetaMapper.class,
         mapper -> {
-          int count = 0;
-          for (Long id : mapper.expired(cutoff, limit)) {
+          int count = GlossaryTermRelService.getInstance().collect(cutoff, 
limit);
+          if (count == limit) {
+            return count;
+          }
+          for (Long id : mapper.expired(cutoff, limit - count)) {
             mapper.purgeSynonyms(id);
             count += mapper.purge(id);
           }
@@ -251,6 +262,11 @@ public final class GlossaryTermMetaService {
   }
 
   private <T> T transaction(Namespace ns, BiFunction<GlossaryTermMetaMapper, 
Long, T> work) {
+    return transaction(ns, false, work);
+  }
+
+  private <T> T transaction(
+      Namespace ns, boolean hierarchyLock, BiFunction<GlossaryTermMetaMapper, 
Long, T> work) {
     validateNamespace(ns);
     return SessionUtils.doWithCommitAndFetchResult(
         GlossaryTermMetaMapper.class,
@@ -268,6 +284,10 @@ public final class GlossaryTermMetaService {
                   m -> 
m.selectMetalakeMetaByIdForShare(observed.getMetalakeId()));
           if (locked == null || !Objects.equals(locked.getMetalakeName(), 
ns.level(0)))
             throw new NoSuchEntityException("Metalake %s no longer exists", 
ns.level(0));
+          if (hierarchyLock) {
+            // Term deletion must exclude new edges before locking the term 
itself.
+            
GlossaryTermRelService.getInstance().lockHierarchy(locked.getMetalakeId());
+          }
           SessionUtils.clearSessionCache();
           return work.apply(mapper, locked.getMetalakeId());
         });
diff --git 
a/core/src/main/java/org/apache/gravitino/storage/relational/service/GlossaryTermRelService.java
 
b/core/src/main/java/org/apache/gravitino/storage/relational/service/GlossaryTermRelService.java
new file mode 100644
index 0000000000..8b215a42ab
--- /dev/null
+++ 
b/core/src/main/java/org/apache/gravitino/storage/relational/service/GlossaryTermRelService.java
@@ -0,0 +1,340 @@
+/*
+ * 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 com.google.common.collect.Lists;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+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 query has a 
READ_COMMITTED
+ * 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 int FRONTIER_BATCH_SIZE = 500;
+  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();
+        });
+  }
+
+  /**
+   * Runs work after acquiring the metalake fence, hierarchy mutex and all 
planned live endpoints in
+   * ascending term ID order. A missing endpoint prevents the callback from 
running.
+   */
+  public <T> T withHierarchyLock(long metalakeId, Set<Long> termIds, 
Supplier<T> work) {
+    checkIds(termIds);
+    Preconditions.checkArgument(work != null, "work cannot be null");
+    return withHierarchyLock(
+        metalakeId,
+        () -> {
+          SessionUtils.doWithoutCommit(
+              GlossaryTermRelMapper.class,
+              mapper -> {
+                for (Long id : termIds.stream().sorted().toList()) {
+                  if (mapper.lockTerm(metalakeId, id) == null) {
+                    throw new NoSuchEntityException(
+                        "Glossary term %s does not exist in metalake %s", id, 
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,
+        Set.of(from, to),
+        () ->
+            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,
+        Set.of(from, to),
+        () ->
+            SessionUtils.getWithoutCommit(
+                GlossaryTermRelMapper.class,
+                mapper ->
+                    mapper.remove(
+                            metalakeId, from, to, type.name(), 
nextDeletedAt(mapper, metalakeId))
+                        == 1));
+  }
+
+  /** Returns the live direct broader IDs, or an empty set when none exist. */
+  public Set<Long> listBroader(long metalakeId, long termId) {
+    return neighbors(listBroaderEdges(metalakeId, Set.of(termId)), termId, 
false, false);
+  }
+
+  /** Returns the live direct narrower IDs, or an empty set when none exist. */
+  public Set<Long> listNarrower(long metalakeId, long termId) {
+    return neighbors(listNarrowerEdges(metalakeId, Set.of(termId)), termId, 
true, false);
+  }
+
+  /** Returns the live related IDs from either orientation of the stored pair. 
*/
+  public Set<Long> listRelated(long metalakeId, long termId) {
+    return neighbors(
+        readEdges(metalakeId, Set.of(termId), RelationType.RELATED, false), 
termId, false, true);
+  }
+
+  /**
+   * Reads all outgoing BROADER edges of a frontier in bounded batches; an 
empty frontier runs no
+   * SQL.
+   */
+  public List<GlossaryTermRelPO> listBroaderEdges(long metalakeId, Set<Long> 
termIds) {
+    return readEdges(metalakeId, termIds, RelationType.BROADER, false);
+  }
+
+  /**
+   * Reads all incoming BROADER edges of a frontier in bounded batches; an 
empty frontier runs no
+   * SQL.
+   */
+  public List<GlossaryTermRelPO> listNarrowerEdges(long metalakeId, Set<Long> 
termIds) {
+    return readEdges(metalakeId, termIds, RelationType.BROADER, true);
+  }
+
+  /**
+   * Walks all live ancestors in bounded batches at each level, including the 
terminal frontier. IDs
+   * are visited once, even for diamonds or malformed cycles; the root is 
excluded.
+   */
+  public Set<Long> ancestors(long metalakeId, long termId) {
+    return walk(metalakeId, termId, false);
+  }
+
+  /** Walks all live descendants with the same snapshot and deduplication 
rules as ancestors. */
+  public Set<Long> descendants(long metalakeId, long termId) {
+    return walk(metalakeId, termId, true);
+  }
+
+  /** Purges at most limit retired edges older than cutoff without touching 
live replacements. */
+  public int collect(long cutoff, int limit) {
+    Preconditions.checkArgument(limit >= 0, "limit must be nonnegative");
+    if (limit == 0) {
+      return 0;
+    }
+    return SessionUtils.doWithCommitAndFetchResult(
+        GlossaryTermRelMapper.class,
+        mapper -> {
+          int count = 0;
+          for (GlossaryTermRelPO row : mapper.expired(cutoff, limit)) {
+            count += mapper.purge(row);
+          }
+          return count;
+        });
+  }
+
+  // The caller already holds the live parent fence in the current transaction.
+  void lockHierarchy(long metalakeId) {
+    Preconditions.checkState(
+        SessionUtils.isInTransaction(), "Hierarchy locks require a 
transaction");
+    SessionUtils.doWithoutCommit(
+        GlossaryTermRelMapper.class,
+        mapper -> {
+          mapper.ensureLock(metalakeId);
+          Preconditions.checkState(
+              mapper.lockHierarchy(metalakeId) != null,
+              "Missing glossary hierarchy mutex for %s",
+              metalakeId);
+        });
+    SessionUtils.clearSessionCache();
+  }
+
+  // Storage cleanup only. The manager plans surviving-term revision/audit 
changes in T5.
+  void removeTerm(long metalakeId, long termId) {
+    SessionUtils.doWithoutCommit(
+        GlossaryTermRelMapper.class,
+        mapper -> mapper.removeTerm(metalakeId, termId, nextDeletedAt(mapper, 
metalakeId)));
+  }
+
+  // Exclusive metalake deletion excludes all hierarchy-lock holders and 
waiters via the parent
+  // fence.
+  void dropMetalake(long metalakeId) {
+    SessionUtils.doWithoutCommit(
+        GlossaryTermRelMapper.class,
+        mapper -> {
+          mapper.dropMetalake(metalakeId, nextDeletedAt(mapper, metalakeId));
+          mapper.dropLock(metalakeId);
+        });
+  }
+
+  private List<GlossaryTermRelPO> readEdges(
+      long metalakeId, Set<Long> ids, RelationType type, boolean reverse) {
+    checkIds(ids);
+    if (ids.isEmpty()) {
+      return Collections.emptyList();
+    }
+    return SessionUtils.getWithoutCommit(
+        GlossaryTermRelMapper.class,
+        mapper -> {
+          if (ids.size() <= FRONTIER_BATCH_SIZE) {
+            return mapper.listEdges(metalakeId, ids, type.name(), reverse);
+          }
+          List<GlossaryTermRelPO> edges = new ArrayList<>();
+          for (List<Long> batch : Lists.partition(List.copyOf(ids), 
FRONTIER_BATCH_SIZE)) {
+            edges.addAll(mapper.listEdges(metalakeId, batch, type.name(), 
reverse));
+          }
+          edges.sort(
+              Comparator.comparing(GlossaryTermRelPO::getFromTermId)
+                  .thenComparing(GlossaryTermRelPO::getToTermId));
+          return edges;
+        });
+  }
+
+  private Set<Long> walk(long metalakeId, long root, boolean reverse) {
+    Set<Long> visited = new LinkedHashSet<>();
+    visited.add(root);
+    Set<Long> frontier = Set.of(root);
+    while (!frontier.isEmpty()) {
+      List<GlossaryTermRelPO> edges =
+          reverse
+              ? listNarrowerEdges(metalakeId, frontier)
+              : listBroaderEdges(metalakeId, frontier);
+      Set<Long> next = new LinkedHashSet<>();
+      for (GlossaryTermRelPO edge : edges) {
+        long id = reverse ? edge.getFromTermId() : edge.getToTermId();
+        if (visited.add(id)) {
+          next.add(id);
+        }
+      }
+      frontier = next;
+    }
+    visited.remove(root);
+    return visited;
+  }
+
+  private Set<Long> neighbors(
+      List<GlossaryTermRelPO> edges, long root, boolean reverse, boolean 
related) {
+    Set<Long> result = new LinkedHashSet<>();
+    for (GlossaryTermRelPO edge : edges) {
+      result.add(
+          reverse || (related && edge.getToTermId() == root)
+              ? edge.getFromTermId()
+              : edge.getToTermId());
+    }
+    return result;
+  }
+
+  private void checkEdge(long fromId, long toId, RelationType type) {
+    Preconditions.checkArgument(type != null, "relation type cannot be null");
+    Preconditions.checkArgument(fromId != toId, "A glossary term cannot be 
linked to itself");
+  }
+
+  private void checkIds(Set<Long> ids) {
+    Preconditions.checkArgument(ids != null, "term IDs cannot be null");
+    for (Long id : ids) {
+      Preconditions.checkArgument(id != null, "term ID cannot be null");
+    }
+  }
+
+  private long nextDeletedAt(GlossaryTermRelMapper mapper, long metalakeId) {
+    // The mutex serializes tombstone generation; PostgreSQL's clock or 
repeated same-ms changes
+    // must not collide with retained generations of the same edge. The index 
starts with
+    // metalake_id.
+    return Math.max(
+        Math.max(1L, System.currentTimeMillis()),
+        Math.addExact(mapper.lastDeletedAt(metalakeId), 1L));
+  }
+}
diff --git 
a/core/src/test/java/org/apache/gravitino/storage/TestSQLScripts.java 
b/core/src/test/java/org/apache/gravitino/storage/TestSQLScripts.java
index 9ed378eea8..133fc7099c 100644
--- a/core/src/test/java/org/apache/gravitino/storage/TestSQLScripts.java
+++ b/core/src/test/java/org/apache/gravitino/storage/TestSQLScripts.java
@@ -52,6 +52,42 @@ import org.opentest4j.AssertionFailedError;
 @DatabaseFixture(resetStrategy = ResetStrategy.FRESH_DATABASE)
 public class TestSQLScripts extends TestJDBCBackend {
 
+  @TestTemplate
+  void testGlossaryRelationSchemasAndUpgrade() throws Exception {
+    Path scripts = upgradeScriptDirectory();
+    String suffix = "-" + backendType.toLowerCase(Locale.ROOT) + ".sql";
+    File upgrade = scripts.resolve("upgrade-1.3.0-to-2.0.0" + suffix).toFile();
+    for (String initialVersion : List.of("1.3.0", "2.0.0")) {
+      dropAllTables();
+      executeScript(scripts.resolve("schema-" + initialVersion + 
suffix).toFile());
+      if (initialVersion.equals("1.3.0")) {
+        executeScript(upgrade);
+        executeScript(upgrade);
+      }
+      try (SqlSession session =
+              
SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);
+          Connection connection = session.getConnection();
+          Statement statement = connection.createStatement()) {
+        statement.executeUpdate("INSERT INTO glossary_hierarchy_lock 
(metalake_id) VALUES (100)");
+        Assertions.assertThrows(
+            SQLException.class,
+            () ->
+                statement.executeUpdate(
+                    "INSERT INTO glossary_hierarchy_lock (metalake_id) VALUES 
(100)"));
+        String edge =
+            "INSERT INTO glossary_term_rel 
(metalake_id,from_term_id,to_term_id,rel_type,deleted_at) VALUES 
(100,101,102,'BROADER',0)";
+        statement.executeUpdate(edge);
+        Assertions.assertThrows(SQLException.class, () -> 
statement.executeUpdate(edge));
+        statement.executeUpdate("UPDATE glossary_term_rel SET deleted_at=123 
WHERE deleted_at=0");
+        statement.executeUpdate(edge);
+        try (ResultSet rows = statement.executeQuery("SELECT COUNT(*) FROM 
glossary_term_rel")) {
+          Assertions.assertTrue(rows.next());
+          Assertions.assertEquals(2, rows.getInt(1));
+        }
+      }
+    }
+  }
+
   @TestTemplate
   void testReimportedIdentifiersWithFreshAndUpgradedSchemas() throws 
SQLException, IOException {
     Path scripts = upgradeScriptDirectory();
diff --git 
a/core/src/test/java/org/apache/gravitino/storage/relational/service/GlossaryInvariants.java
 
b/core/src/test/java/org/apache/gravitino/storage/relational/service/GlossaryInvariants.java
index d957d2edc6..5c9a851f1e 100644
--- 
a/core/src/test/java/org/apache/gravitino/storage/relational/service/GlossaryInvariants.java
+++ 
b/core/src/test/java/org/apache/gravitino/storage/relational/service/GlossaryInvariants.java
@@ -58,4 +58,37 @@ public final class GlossaryInvariants {
       }
     }
   }
+
+  /** Checks canonical relation keys, live endpoints and the unique mutex 
rows. */
+  public static void assertRelations() throws Exception {
+    try (SqlSession session =
+            
SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession();
+        Connection connection = session.getConnection();
+        Statement statement = connection.createStatement()) {
+      Set<String> keys = new HashSet<>();
+      try (ResultSet rows =
+          statement.executeQuery(
+              "SELECT r.from_term_id, r.to_term_id, r.rel_type, f.term_id, 
t.term_id, m.metalake_id FROM glossary_term_rel r "
+                  + "LEFT 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 "
+                  + "LEFT 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 "
+                  + "LEFT JOIN metalake_meta m ON m.metalake_id=r.metalake_id 
AND m.deleted_at=0 WHERE r.deleted_at=0")) {
+        while (rows.next()) {
+          Assertions.assertNotEquals(rows.getLong(1), rows.getLong(2));
+          Assertions.assertTrue(
+              keys.add(rows.getLong(1) + ":" + rows.getLong(2) + ":" + 
rows.getString(3)));
+          Assertions.assertTrue(Set.of("BROADER", 
"RELATED").contains(rows.getString(3)));
+          if ("RELATED".equals(rows.getString(3)))
+            Assertions.assertTrue(rows.getLong(1) < rows.getLong(2));
+          for (int i = 4; i <= 6; i++)
+            Assertions.assertNotNull(
+                rows.getObject(i), "Live relation requires live endpoints and 
metalake");
+        }
+      }
+      Set<Long> metalakes = new HashSet<>();
+      try (ResultSet rows =
+          statement.executeQuery("SELECT metalake_id FROM 
glossary_hierarchy_lock")) {
+        while (rows.next()) 
Assertions.assertTrue(metalakes.add(rows.getLong(1)));
+      }
+    }
+  }
 }
diff --git 
a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestGlossaryTermMetaService.java
 
b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestGlossaryTermMetaService.java
index 05ce446d7f..00e53cf12f 100644
--- 
a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestGlossaryTermMetaService.java
+++ 
b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestGlossaryTermMetaService.java
@@ -209,6 +209,17 @@ public class TestGlossaryTermMetaService extends 
TestJDBCBackend {
         () -> service.update(ident("One"), old -> term(999, "One").build()));
   }
 
+  /** The backend distinguishes a missing parent from an absent child of a 
live metalake. */
+  @TestTemplate
+  public void testDeleteDistinguishesMissingMetalakeFromMissingTerm() throws 
Exception {
+    NoSuchEntityException missingParent =
+        Assertions.assertThrows(
+            NoSuchEntityException.class, () -> backend.delete(ident("Churn"), 
TYPE, false));
+    Assertions.assertEquals("No such metalake entity: glossary", 
missingParent.getMessage());
+    setupMetalake();
+    Assertions.assertFalse(backend.delete(ident("Churn"), TYPE, false));
+  }
+
   @TestTemplate
   public void testDeleteRecreateAndGc() throws Exception {
     setupMetalake();
@@ -424,7 +435,7 @@ public class TestGlossaryTermMetaService extends 
TestJDBCBackend {
 
   @TestTemplate
   public void testGetDoesNotFollowRenamedMetalake() throws Exception {
-    assertReadAfterMetalakeRename(
+    assertOperationAfterMetalakeRename(
         () ->
             Assertions.assertThrows(
                 NoSuchEntityException.class, () -> backend.get(ident("New 
term"), TYPE)));
@@ -432,26 +443,39 @@ public class TestGlossaryTermMetaService extends 
TestJDBCBackend {
 
   @TestTemplate
   public void testListDoesNotFollowRenamedMetalake() throws Exception {
-    assertReadAfterMetalakeRename(
+    assertOperationAfterMetalakeRename(
         () -> Assertions.assertTrue(backend.list(NS, TYPE, true).isEmpty()));
   }
 
   @TestTemplate
   public void testBatchGetDoesNotFollowRenamedMetalake() throws Exception {
-    assertReadAfterMetalakeRename(
+    assertOperationAfterMetalakeRename(
         () -> Assertions.assertTrue(backend.batchGet(List.of(ident("New 
term")), TYPE).isEmpty()));
   }
 
   @TestTemplate
   public void testIdsDoNotFollowRenamedMetalake() throws Exception {
-    assertReadAfterMetalakeRename(
+    assertOperationAfterMetalakeRename(
         () ->
             Assertions.assertThrows(
                 NoSuchEntityException.class,
                 () -> new 
RelationalEntityStoreIdResolver().getEntityIds(ident("New term"), TYPE)));
   }
 
-  private void assertReadAfterMetalakeRename(Executable read) throws Exception 
{
+  /** A delete that resolved the old parent name must leave the renamed 
metalake's term intact. */
+  @TestTemplate
+  public void testDeleteDoesNotFollowRenamedMetalake() throws Exception {
+    assertOperationAfterMetalakeRename(
+        () -> {
+          NoSuchEntityException missingParent =
+              Assertions.assertThrows(
+                  NoSuchEntityException.class,
+                  () -> backend.delete(ident("New term"), TYPE, false));
+          Assertions.assertEquals("Metalake glossary no longer exists", 
missingParent.getMessage());
+        });
+  }
+
+  private void assertOperationAfterMetalakeRename(Executable operation) throws 
Exception {
     setupMetalake();
     Namespace renamed =
         Namespace.of("renamed", Entity.SYSTEM_CATALOG_RESERVED_NAME, 
"glossary_term");
@@ -460,7 +484,8 @@ public class TestGlossaryTermMetaService extends 
TestJDBCBackend {
     Mockito.doAnswer(
             invocation -> {
               MetalakePO observed = (MetalakePO) invocation.callRealMethod();
-              // Commit on an independent session after name resolution but 
before the term SELECT.
+              // Commit on an independent session after name resolution and 
before the caller
+              // continues.
               // This term has never existed under the old namespace, so 
returning it cannot
               // represent
               // an earlier valid snapshot. The spy changes timing only; all 
reads and writes hit
@@ -488,7 +513,7 @@ public class TestGlossaryTermMetaService extends 
TestJDBCBackend {
     try (MockedStatic<MetalakeMetaService> services =
         Mockito.mockStatic(MetalakeMetaService.class, 
Mockito.CALLS_REAL_METHODS)) {
       services.when(MetalakeMetaService::getInstance).thenReturn(metalakes);
-      Assertions.assertDoesNotThrow(read);
+      Assertions.assertDoesNotThrow(operation);
       Mockito.verify(metalakes).requireMetalakeByName("glossary");
     } finally {
       writer.shutdownNow();
diff --git 
a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestGlossaryTermRelService.java
 
b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestGlossaryTermRelService.java
new file mode 100644
index 0000000000..ae1daa7e86
--- /dev/null
+++ 
b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestGlossaryTermRelService.java
@@ -0,0 +1,616 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.gravitino.storage.relational.service;
+
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.Statement;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.CyclicBarrier;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.exceptions.NonEmptyEntityException;
+import org.apache.gravitino.meta.GlossaryTermEntity;
+import org.apache.gravitino.storage.relational.TestJDBCBackend;
+import org.apache.gravitino.storage.relational.mapper.GlossaryTermRelMapper;
+import org.apache.gravitino.storage.relational.po.GlossaryTermRelPO;
+import 
org.apache.gravitino.storage.relational.service.GlossaryTermRelService.RelationType;
+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
+import org.apache.gravitino.storage.relational.session.SqlSessions;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.ibatis.session.SqlSession;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.function.Executable;
+import org.mockito.AdditionalAnswers;
+import org.mockito.MockedStatic;
+import org.mockito.Mockito;
+
+/** Exercises glossary edges and mutexes with real backend transactions. */
+public class TestGlossaryTermRelService extends TestJDBCBackend {
+  private static final Namespace NS =
+      Namespace.of("glossary", Entity.SYSTEM_CATALOG_RESERVED_NAME, 
"glossary_term");
+  private final GlossaryTermRelService service = 
GlossaryTermRelService.getInstance();
+
+  /** Checks the T3 endpoint, canonical-pair and transaction-lifecycle 
invariants. */
+  @AfterEach
+  public void checkInvariants() throws Exception {
+    Assertions.assertFalse(
+        SessionUtils.isInTransaction(), "Storage operations must close owned 
transactions");
+    GlossaryInvariants.assertDefinitions();
+    GlossaryInvariants.assertRelations();
+  }
+
+  /** T3.1/T3.2: relation directions, canonical RELATED pairs and idempotent 
mutations. */
+  @TestTemplate
+  public void testRelationsAndCanonicalPairs() throws Exception {
+    setupTerms(4);
+    Assertions.assertTrue(service.add(100, 101, 102, RelationType.BROADER));
+    Assertions.assertFalse(service.add(100, 101, 102, RelationType.BROADER));
+    Assertions.assertTrue(service.add(100, 103, 101, RelationType.RELATED));
+    Assertions.assertFalse(service.add(100, 101, 103, RelationType.RELATED));
+    Assertions.assertEquals(Set.of(102L), service.listBroader(100, 101));
+    Assertions.assertEquals(Set.of(101L), service.listNarrower(100, 102));
+    Assertions.assertEquals(Set.of(103L), service.listRelated(100, 101));
+    Assertions.assertEquals(Set.of(101L), service.listRelated(100, 103));
+    Assertions.assertEquals(
+        1,
+        scalar(
+            "SELECT COUNT(*) FROM glossary_term_rel WHERE rel_type='RELATED' 
AND from_term_id=101 AND to_term_id=103 AND deleted_at=0"));
+    Assertions.assertTrue(service.remove(100, 103, 101, RelationType.RELATED));
+    Assertions.assertFalse(service.remove(100, 101, 103, 
RelationType.RELATED));
+    Assertions.assertTrue(service.listRelated(100, 101).isEmpty());
+    Assertions.assertTrue(service.remove(100, 101, 102, RelationType.BROADER));
+    Assertions.assertTrue(service.listNarrower(100, 102).isEmpty());
+    Assertions.assertTrue(service.listBroader(100, 104).isEmpty());
+  }
+
+  /** T3.1: rejects invalid input and missing or cross-metalake endpoints 
without writes. */
+  @TestTemplate
+  public void testRejectInvalidEndpoints() throws Exception {
+    setupTerms(2);
+    backend.insert(createBaseMakeLake(200L, "other", AUDIT_INFO), false);
+    backend.insert(
+        term(
+            201,
+            "Other",
+            Namespace.of("other", Entity.SYSTEM_CATALOG_RESERVED_NAME, 
"glossary_term")),
+        false);
+    Assertions.assertThrows(
+        IllegalArgumentException.class, () -> service.add(100, 101, 101, 
RelationType.BROADER));
+    Assertions.assertThrows(IllegalArgumentException.class, () -> 
service.add(100, 101, 102, null));
+    Assertions.assertThrows(
+        NoSuchEntityException.class, () -> service.add(100, 101, 999, 
RelationType.BROADER));
+    Assertions.assertThrows(
+        NoSuchEntityException.class, () -> service.add(100, 101, 201, 
RelationType.RELATED));
+    Assertions.assertThrows(
+        NoSuchEntityException.class, () -> service.withHierarchyLock(999, () 
-> null));
+    Assertions.assertThrows(
+        IllegalArgumentException.class, () -> service.withHierarchyLock(100, 
null));
+    Assertions.assertThrows(
+        IllegalArgumentException.class, () -> service.listBroaderEdges(100, 
null));
+    Set<Long> invalid = new HashSet<>();
+    invalid.add(null);
+    Assertions.assertThrows(
+        IllegalArgumentException.class, () -> service.listBroaderEdges(100, 
invalid));
+    Assertions.assertThrows(
+        NoSuchEntityException.class,
+        () ->
+            service.withHierarchyLock(
+                100,
+                Set.of(101L, 201L),
+                () -> Assertions.fail("Missing endpoint must prevent 
callback")));
+    Assertions.assertThrows(
+        IllegalArgumentException.class, () -> service.collect(Long.MAX_VALUE, 
-1));
+    Assertions.assertEquals(0, scalar("SELECT COUNT(*) FROM 
glossary_term_rel"));
+    Assertions.assertEquals(
+        0, scalar("SELECT COUNT(*) FROM glossary_hierarchy_lock WHERE 
metalake_id=999"));
+  }
+
+  /** T3.3/T3.4: deduplicates diamonds and guards one real mapper query per 
frontier. */
+  @TestTemplate
+  public void testBatchedWalkAndDiamond() throws Exception {
+    setupTerms(8);
+    // Five frontiers: {101}, {102,103}, {104,105}, {106,107}, {108}.
+    for (long[] pair :
+        new long[][] {
+          {101, 102},
+          {101, 103},
+          {102, 104},
+          {103, 104},
+          {103, 105},
+          {104, 106},
+          {105, 107},
+          {106, 108},
+          {107, 108}
+        }) {
+      service.add(100, pair[0], pair[1], RelationType.BROADER);
+    }
+    AtomicInteger queries = new AtomicInteger();
+    // A default answer avoids invoking getMapper while configuring a static 
stub: that would
+    // increment the thread-local session count and leak a transaction into 
the next test.
+    try (MockedStatic<SqlSessions> sessions =
+        Mockito.mockStatic(
+            SqlSessions.class,
+            call -> {
+              Object result = call.callRealMethod();
+              if (!call.getMethod().getName().equals("getMapper")
+                  || call.getArgument(0) != GlossaryTermRelMapper.class) {
+                return result;
+              }
+              return Mockito.mock(
+                  GlossaryTermRelMapper.class,
+                  invocation -> {
+                    if (invocation.getMethod().getName().equals("listEdges")) {
+                      queries.incrementAndGet();
+                    }
+                    return 
AdditionalAnswers.delegatesTo(result).answer(invocation);
+                  });
+            })) {
+      Assertions.assertEquals(
+          Set.of(102L, 103L, 104L, 105L, 106L, 107L, 108L), 
service.ancestors(100, 101));
+      Assertions.assertEquals(5, queries.get(), "One mapper query per 
frontier, not per term");
+      queries.set(0);
+      Assertions.assertEquals(
+          Set.of(101L, 102L, 103L, 104L, 105L, 106L, 107L), 
service.descendants(100, 108));
+      Assertions.assertEquals(5, queries.get());
+      Set<Long> wide = new LinkedHashSet<>();
+      wide.add(107L);
+      for (long id = 1000; id < 1499; id++) {
+        wide.add(id);
+      }
+      wide.add(101L);
+      queries.set(0);
+      Assertions.assertEquals(
+          List.of(101L, 101L, 107L),
+          service.listBroaderEdges(100, wide).stream()
+              .map(GlossaryTermRelPO::getFromTermId)
+              .toList());
+      Assertions.assertEquals(2, queries.get());
+      queries.set(0);
+      Assertions.assertEquals(
+          List.of(105L),
+          service.listNarrowerEdges(100, wide).stream()
+              .map(GlossaryTermRelPO::getFromTermId)
+              .toList());
+      Assertions.assertEquals(2, queries.get());
+      queries.set(0);
+      Assertions.assertTrue(service.listBroaderEdges(100, Set.of()).isEmpty());
+      Assertions.assertTrue(service.listNarrowerEdges(100, 
Set.of()).isEmpty());
+      Assertions.assertEquals(0, queries.get());
+    }
+    // T5 rejects cycles. The storage walk must still terminate on malformed 
graphs.
+    service.add(100, 108, 101, RelationType.BROADER);
+    Assertions.assertEquals(7, service.ancestors(100, 101).size());
+    service.remove(100, 108, 101, RelationType.BROADER);
+  }
+
+  /** T3.5: transaction ownership and fresh reads after acquiring the 
hierarchy mutex. */
+  @TestTemplate
+  public void testRollbackAndFreshReadsUnderMutex() throws Exception {
+    repeatRace(
+        () -> {
+          setupTerms(3);
+          Assertions.assertThrows(
+              IllegalStateException.class,
+              () ->
+                  service.withHierarchyLock(
+                      100,
+                      () -> {
+                        service.add(100, 101, 102, RelationType.BROADER);
+                        throw new IllegalStateException("rollback graph");
+                      }));
+          Assertions.assertTrue(service.listBroader(100, 101).isEmpty());
+          Assertions.assertEquals(0, scalar("SELECT COUNT(*) FROM 
glossary_hierarchy_lock"));
+          SessionUtils.beginTransaction();
+          try {
+            Assertions.assertThrows(
+                IllegalStateException.class,
+                () ->
+                    service.withHierarchyLock(
+                        100,
+                        () -> {
+                          service.add(100, 101, 102, RelationType.BROADER);
+                          throw new IllegalStateException("nested callback 
failed");
+                        }));
+          } finally {
+            // SessionUtils has no savepoints. A caller catching a nested 
failure owns the rollback.
+            SessionUtils.rollbackTransaction();
+          }
+          Assertions.assertTrue(service.listBroader(100, 101).isEmpty());
+          ExecutorService writer = Executors.newSingleThreadExecutor();
+          try {
+            SessionUtils.beginTransaction();
+            try {
+              Assertions.assertTrue(service.listBroader(100, 101).isEmpty());
+              writer
+                  .submit(() -> service.add(100, 101, 102, 
RelationType.BROADER))
+                  .get(10, TimeUnit.SECONDS);
+              service.withHierarchyLock(
+                  100,
+                  () -> {
+                    Assertions.assertEquals(Set.of(102L), 
service.listBroader(100, 101));
+                    return null;
+                  });
+              SessionUtils.commitTransaction();
+            } finally {
+              if (SessionUtils.isInTransaction()) 
SessionUtils.rollbackTransaction();
+            }
+            Assertions.assertEquals(1, scalar("SELECT COUNT(*) FROM 
glossary_hierarchy_lock"));
+            service.withHierarchyLock(100, () -> null);
+            Assertions.assertEquals(1, scalar("SELECT COUNT(*) FROM 
glossary_hierarchy_lock"));
+          } finally {
+            writer.shutdownNow();
+            Assertions.assertTrue(writer.awaitTermination(10, 
TimeUnit.SECONDS));
+          }
+        });
+  }
+
+  /** A pre-mutex read sees later commits when checking duplicate edges and 
retiring a term. */
+  @TestTemplate
+  public void testPeerReplacementBeforeHierarchyLock() throws Exception {
+    setupTerms(2);
+    long future = 4102444800000L;
+    execute("INSERT INTO glossary_term_rel VALUES (100,101,102,'BROADER'," + 
future + ")");
+    ExecutorService writer = Executors.newSingleThreadExecutor();
+    try {
+      SessionUtils.beginTransaction();
+      try {
+        Assertions.assertTrue(service.listBroader(100, 101).isEmpty());
+        writer
+            .submit(
+                () -> {
+                  Assertions.assertTrue(service.add(100, 101, 102, 
RelationType.BROADER));
+                  Assertions.assertTrue(service.remove(100, 101, 102, 
RelationType.BROADER));
+                  Assertions.assertTrue(service.add(100, 101, 102, 
RelationType.BROADER));
+                })
+            .get(10, TimeUnit.SECONDS);
+        Assertions.assertFalse(service.add(100, 101, 102, 
RelationType.BROADER));
+        Assertions.assertTrue(
+            GlossaryTermMetaService.getInstance().delete(NameIdentifier.of(NS, 
"Term102")));
+        SessionUtils.commitTransaction();
+      } finally {
+        if (SessionUtils.isInTransaction()) SessionUtils.rollbackTransaction();
+      }
+      Assertions.assertEquals(future + 2, scalar("SELECT MAX(deleted_at) FROM 
glossary_term_rel"));
+    } finally {
+      writer.shutdownNow();
+      Assertions.assertTrue(writer.awaitTermination(10, TimeUnit.SECONDS));
+    }
+  }
+
+  /** T3.5: two independent transactions concurrently initialize the same 
mutex, 20 rounds. */
+  @TestTemplate
+  public void testConcurrentFirstUse() throws Exception {
+    repeatRace(
+        () -> {
+          setupTerms(3);
+          CyclicBarrier ready = new CyclicBarrier(2);
+          AtomicInteger inside = new AtomicInteger();
+          ExecutorService writers = Executors.newFixedThreadPool(2);
+          try {
+            List<Future<Boolean>> results = new ArrayList<>();
+            for (int i = 0; i < 2; i++) {
+              final long to = 102L + i;
+              results.add(
+                  writers.submit(
+                      () -> {
+                        ready.await(10, TimeUnit.SECONDS);
+                        return service.withHierarchyLock(
+                            100,
+                            () -> {
+                              Assertions.assertEquals(1, 
inside.incrementAndGet());
+                              try {
+                                return service.add(100, 101, to, 
RelationType.BROADER);
+                              } finally {
+                                inside.decrementAndGet();
+                              }
+                            });
+                      }));
+            }
+            for (Future<Boolean> result : results)
+              Assertions.assertTrue(result.get(20, TimeUnit.SECONDS));
+            Assertions.assertEquals(Set.of(102L, 103L), 
service.listBroader(100, 101));
+            Assertions.assertEquals(1, scalar("SELECT COUNT(*) FROM 
glossary_hierarchy_lock"));
+          } finally {
+            writers.shutdownNow();
+            Assertions.assertTrue(writers.awaitTermination(10, 
TimeUnit.SECONDS));
+          }
+        });
+  }
+
+  /**
+   * T3.5: a returned operation retains its lock through outer commit while 
reads remain unlocked.
+   */
+  @TestTemplate
+  public void testLockHeldThroughOuterCommitAndReadersDoNotBlock() throws 
Exception {
+    repeatRace(
+        () -> {
+          setupTerms(3);
+          ExecutorService worker = Executors.newFixedThreadPool(2);
+          CountDownLatch attempted = new CountDownLatch(1);
+          try {
+            SessionUtils.beginTransaction();
+            Future<Boolean> waiting;
+            try {
+              service.add(100, 101, 102, RelationType.BROADER);
+              waiting =
+                  worker.submit(
+                      () -> {
+                        attempted.countDown();
+                        return service.add(100, 101, 103, 
RelationType.BROADER);
+                      });
+              Assertions.assertTrue(attempted.await(10, TimeUnit.SECONDS));
+              Assertions.assertThrows(
+                  TimeoutException.class, () -> waiting.get(200, 
TimeUnit.MILLISECONDS));
+              Assertions.assertTrue(
+                  worker
+                      .submit(() -> service.listBroader(100, 101))
+                      .get(10, TimeUnit.SECONDS)
+                      .isEmpty());
+              SessionUtils.commitTransaction();
+            } finally {
+              if (SessionUtils.isInTransaction()) 
SessionUtils.rollbackTransaction();
+            }
+            Assertions.assertTrue(waiting.get(10, TimeUnit.SECONDS));
+            Assertions.assertEquals(Set.of(102L, 103L), 
service.listBroader(100, 101));
+          } finally {
+            worker.shutdownNow();
+            Assertions.assertTrue(worker.awaitTermination(10, 
TimeUnit.SECONDS));
+          }
+        });
+  }
+
+  /** T3.1: repeated edge generations, strict expiry cutoff and bounded 
garbage collection. */
+  @TestTemplate
+  public void testRetiredGenerationsAndBoundedGc() throws Exception {
+    setupTerms(2);
+    for (int i = 0; i < 3; i++) {
+      Assertions.assertTrue(service.add(100, 101, 102, RelationType.BROADER));
+      // Force all removals behind a retained future tombstone, independently 
of clock precision.
+      if (i == 0) {
+        execute("INSERT INTO glossary_term_rel VALUES 
(100,101,102,'BROADER',4102444800000)");
+      }
+      Assertions.assertTrue(service.remove(100, 101, 102, 
RelationType.BROADER));
+    }
+    Assertions.assertEquals(4, scalar("SELECT COUNT(DISTINCT deleted_at) FROM 
glossary_term_rel"));
+    Assertions.assertTrue(service.add(100, 101, 102, RelationType.BROADER));
+    Assertions.assertEquals(0, service.collect(4102444800000L, 20));
+    Assertions.assertEquals(0, service.collect(Long.MAX_VALUE, 0));
+    Assertions.assertEquals(2, service.collect(Long.MAX_VALUE, 2));
+    Assertions.assertEquals(2, service.collect(Long.MAX_VALUE, 2));
+    Assertions.assertEquals(0, service.collect(Long.MAX_VALUE, 2));
+    Assertions.assertEquals(Set.of(102L), service.listBroader(100, 101));
+  }
+
+  /** T3.1: definition and metalake deletion retire edges and collect their 
tombstones. */
+  @TestTemplate
+  public void testTermAndMetalakeCleanup() throws Exception {
+    setupTerms(3);
+    service.add(100, 101, 102, RelationType.BROADER);
+    service.add(100, 103, 102, RelationType.RELATED);
+    Assertions.assertTrue(
+        GlossaryTermMetaService.getInstance().delete(NameIdentifier.of(NS, 
"Term102")));
+    Assertions.assertTrue(service.listBroader(100, 101).isEmpty());
+    Assertions.assertTrue(service.listRelated(100, 103).isEmpty());
+    Assertions.assertEquals(0, scalar("SELECT COUNT(*) FROM glossary_term_rel 
WHERE deleted_at=0"));
+    Assertions.assertThrows(
+        NoSuchEntityException.class, () -> service.add(100, 101, 102, 
RelationType.BROADER));
+    service.add(100, 101, 103, RelationType.RELATED);
+    backend.delete(NameIdentifier.of("glossary"), Entity.EntityType.METALAKE, 
true);
+    Assertions.assertEquals(0, scalar("SELECT COUNT(*) FROM glossary_term_rel 
WHERE deleted_at=0"));
+    Assertions.assertEquals(0, scalar("SELECT COUNT(*) FROM 
glossary_hierarchy_lock"));
+    Assertions.assertTrue(service.ancestors(100, 101).isEmpty());
+    // The existing GLOSSARY_TERM GC entry point also drains relation 
tombstones.
+    while (GlossaryTermMetaService.getInstance().collect(Long.MAX_VALUE, 1) != 
0) {}
+    Assertions.assertEquals(0, scalar("SELECT COUNT(*) FROM 
glossary_term_rel"));
+    Assertions.assertEquals(0, scalar("SELECT COUNT(*) FROM 
glossary_term_meta"));
+  }
+
+  /**
+   * Non-cascading metalake deletion preserves glossary state on rejection and 
retires it on
+   * success.
+   */
+  @TestTemplate
+  public void testNonCascadeMetalakeCleanup() throws Exception {
+    setupTerms(2);
+    NameIdentifier metalake = NameIdentifier.of("glossary");
+    NameIdentifier catalog = createAndInsertCatalog("glossary", 
"catalog").nameIdentifier();
+    Assertions.assertTrue(service.add(100, 101, 102, RelationType.BROADER));
+
+    Assertions.assertThrows(
+        NonEmptyEntityException.class,
+        () -> backend.delete(metalake, Entity.EntityType.METALAKE, false));
+    Assertions.assertEquals(Set.of(102L), service.listBroader(100, 101));
+    Assertions.assertEquals(
+        1, scalar("SELECT COUNT(*) FROM glossary_hierarchy_lock WHERE 
metalake_id=100"));
+
+    Assertions.assertTrue(backend.delete(catalog, Entity.EntityType.CATALOG, 
false));
+    Assertions.assertTrue(backend.delete(metalake, Entity.EntityType.METALAKE, 
false));
+    // Joins against the retired parent would hide a leaked live edge. Check 
the stored generations.
+    Assertions.assertEquals(
+        1, scalar("SELECT COUNT(*) FROM glossary_term_rel WHERE 
metalake_id=100 AND deleted_at>0"));
+    Assertions.assertEquals(
+        0, scalar("SELECT COUNT(*) FROM glossary_term_rel WHERE 
metalake_id=100 AND deleted_at=0"));
+    Assertions.assertEquals(
+        0, scalar("SELECT COUNT(*) FROM glossary_hierarchy_lock WHERE 
metalake_id=100"));
+  }
+
+  /** T3.5: the committed mutex itself excludes a writer independently of the 
parent fence. */
+  @TestTemplate
+  public void testMutexExcludesIndependentDatabaseWriter() throws Exception {
+    repeatRace(
+        () -> {
+          setupTerms(2);
+          service.withHierarchyLock(100, () -> null);
+          ExecutorService worker = Executors.newSingleThreadExecutor();
+          CountDownLatch attempted = new CountDownLatch(1);
+          try {
+            SessionUtils.beginTransaction();
+            Future<Long> waiting;
+            try {
+              service.withHierarchyLock(100, () -> null);
+              waiting =
+                  worker.submit(
+                      () ->
+                          SessionUtils.doWithCommitAndFetchResult(
+                              GlossaryTermRelMapper.class,
+                              mapper -> {
+                                attempted.countDown();
+                                // Deliberately skip the parent fence to prove 
the mutex itself,
+                                // including
+                                // on H2.
+                                mapper.ensureLock(100);
+                                return mapper.lockHierarchy(100);
+                              }));
+              Assertions.assertTrue(attempted.await(10, TimeUnit.SECONDS));
+              Assertions.assertThrows(
+                  TimeoutException.class, () -> waiting.get(200, 
TimeUnit.MILLISECONDS));
+              SessionUtils.commitTransaction();
+            } finally {
+              if (SessionUtils.isInTransaction()) 
SessionUtils.rollbackTransaction();
+            }
+            Assertions.assertEquals(100L, waiting.get(10, TimeUnit.SECONDS));
+          } finally {
+            worker.shutdownNow();
+            Assertions.assertTrue(worker.awaitTermination(10, 
TimeUnit.SECONDS));
+          }
+        });
+  }
+
+  /**
+   * T3.1/T3.5: deletion rollback restores edges and committed deletion fences 
concurrent additions.
+   */
+  @TestTemplate
+  public void testDeleteFencesNewEdgesAndRollbackRestoresRelations() throws 
Exception {
+    repeatRace(
+        () -> {
+          setupTerms(3);
+          service.add(100, 101, 102, RelationType.BROADER);
+          Assertions.assertThrows(
+              IllegalStateException.class,
+              () ->
+                  SessionUtils.doMultipleWithCommit(
+                      () -> {
+                        GlossaryTermMetaService.getInstance()
+                            .delete(NameIdentifier.of(NS, "Term102"));
+                        throw new IllegalStateException("rollback deletion");
+                      }));
+          Assertions.assertEquals(Set.of(102L), service.listBroader(100, 101));
+          ExecutorService writer = Executors.newSingleThreadExecutor();
+          CountDownLatch attempted = new CountDownLatch(1);
+          try {
+            SessionUtils.beginTransaction();
+            Future<?> waiting;
+            try {
+              Assertions.assertTrue(
+                  
GlossaryTermMetaService.getInstance().delete(NameIdentifier.of(NS, "Term102")));
+              waiting =
+                  writer.submit(
+                      () -> {
+                        attempted.countDown();
+                        Assertions.assertThrows(
+                            NoSuchEntityException.class,
+                            () -> service.add(100, 103, 102, 
RelationType.RELATED));
+                      });
+              Assertions.assertTrue(attempted.await(10, TimeUnit.SECONDS));
+              Assertions.assertThrows(
+                  TimeoutException.class, () -> waiting.get(200, 
TimeUnit.MILLISECONDS));
+              SessionUtils.commitTransaction();
+            } finally {
+              if (SessionUtils.isInTransaction()) 
SessionUtils.rollbackTransaction();
+            }
+            waiting.get(10, TimeUnit.SECONDS);
+            Assertions.assertEquals(
+                0, scalar("SELECT COUNT(*) FROM glossary_term_rel WHERE 
deleted_at=0"));
+          } finally {
+            writer.shutdownNow();
+            Assertions.assertTrue(writer.awaitTermination(10, 
TimeUnit.SECONDS));
+          }
+        });
+  }
+
+  private void repeatRace(Executable race) {
+    Assertions.assertTimeoutPreemptively(
+        Duration.ofMinutes(2),
+        () -> {
+          for (int round = 0; round < 20; round++) {
+            race.execute();
+            checkInvariants();
+            // Reset only this test's completed fixture, so each round starts 
without a mutex row.
+            // All worker futures have finished and owned transactions are 
closed before this reset.
+            execute("DELETE FROM glossary_term_rel WHERE metalake_id=100");
+            execute("DELETE FROM glossary_hierarchy_lock WHERE 
metalake_id=100");
+            execute("DELETE FROM glossary_term_synonym WHERE metalake_id=100");
+            execute("DELETE FROM glossary_term_meta WHERE metalake_id=100");
+            execute("DELETE FROM metalake_meta WHERE metalake_id=100");
+          }
+        });
+  }
+
+  private void setupTerms(int count) throws Exception {
+    backend.insert(createBaseMakeLake(100L, "glossary", AUDIT_INFO), false);
+    for (int i = 1; i <= count; i++) backend.insert(term(100 + i, "Term" + 
(100 + i), NS), false);
+  }
+
+  private GlossaryTermEntity term(long id, String name, Namespace ns) {
+    return GlossaryTermEntity.builder()
+        .withId(id)
+        .withName(name)
+        .withNamespace(ns)
+        .withAuditInfo(AUDIT_INFO)
+        .build();
+  }
+
+  private long scalar(String sql) throws Exception {
+    try (SqlSession session =
+            
SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession();
+        Connection connection = session.getConnection();
+        Statement statement = connection.createStatement();
+        ResultSet result = statement.executeQuery(sql)) {
+      Assertions.assertTrue(result.next());
+      return result.getLong(1);
+    }
+  }
+
+  private void execute(String sql) throws Exception {
+    try (SqlSession session =
+            
SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);
+        Connection connection = session.getConnection();
+        Statement statement = connection.createStatement()) {
+      statement.execute(sql);
+    }
+  }
+}
diff --git a/design-docs/glossary-design.md b/design-docs/glossary-design.md
index bf7127c6e5..584699e6ad 100644
--- a/design-docs/glossary-design.md
+++ b/design-docs/glossary-design.md
@@ -158,6 +158,19 @@ TermVersion  { termId, version, state, snapshot, 
audit_info }   // Step 2 only;
   discriminator (`1` for live rows, `NULL` for deleted rows) to the unique 
keys. Keep the actual
   deletion timestamp for GC; distinct deleted generations may share that 
timestamp without
   colliding. MySQL indexes the binary source-reference key described below.
+- **Relation storage boundary (T3)**: `BROADER` points from child to parent, 
and `RELATED`
+  endpoints are stored in ascending ID order. The storage service rejects 
self-links and missing or
+  cross-metalake endpoints, and makes duplicate additions and absent removals 
no-ops. Cycle/depth
+  and overlap checks, authorization, and surviving-term revision/audit updates 
remain manager work
+  in T4/T5. Reads return live endpoint IDs without authorization or status 
filtering. Each batch
+  of up to 500 frontier IDs uses one statement snapshot. A stable walk 
requires a hierarchy-lock
+  transaction. Manager reads must filter each frontier before expanding it.
+- **Relation cleanup**: term deletion retires touching edges under the 
hierarchy mutex, and metalake
+  deletion retires its edges and removes its mutex row under the exclusive 
parent fence. Relation
+  deletion timestamps advance beyond retained timestamps in that metalake, 
avoiding primary-key
+  collisions when an edge is removed and re-added within a millisecond. The 
glossary garbage
+  collector counts expired relation generations and definitions toward the 
batch limit. It also
+  purges the synonyms of each collected definition in the same transaction.
 - **Normalized key**: `key(s)` trims `s`, turns each run of spaces into one 
space, and lower-cases
   it (`Locale.ROOT`). Names, synonyms and lookups all use `key()`, so they 
compare the same way.
 - **Names** are unique in a metalake by `name_key = key(name)`. So `Churn` and 
`churn` are the same
@@ -222,7 +235,7 @@ TermVersion  { termId, version, state, snapshot, audit_info 
}   // Step 2 only;
   X → A, B → Y and X `RELATED` Y make A → B invalid. Walking only upward from 
B misses X.
   Both walks and the pair check run under the hierarchy lock, with visited IDs 
deduplicated
   across each walk. An alter validates its complete proposed relation graph 
before committing.
-- **No recursive SQL**: the walk runs in code, with one batched query per 
level. The backend still
+- **No recursive SQL**: the walk runs in code, with queries of up to 500 
frontier IDs per level. The backend still
   supports MySQL 5.7, which has no `WITH RECURSIVE`.
 - A hierarchy read returns all ancestors or all descendants of a term. There 
are no cycles, so the
   walk always ends.
@@ -1319,7 +1332,7 @@ also need `-PskipDockerTests=false` and a running Docker.
 - T3.2 `RELATED` from A to B and from B to A is one row, with `from_term_id < 
to_term_id`. Adding
   the second one is a duplicate.
 - T3.3 Diamond: A → B, A → C, B → D, C → D. Walking up from A returns B, C and 
D, each once.
-- T3.4 The walk sends one query per level. For a chain of 5 levels, it sends 5 
queries. (Count the
+- T3.4 The walk sends one query per batch of up to 500 IDs per level. For a 
chain of 5 levels, it sends 5 queries. (Count the
   calls on the mapper.) **(guard: a version with one query per term fails this 
test.)**
 - T3.5 The first use of the hierarchy lock inserts its row. A second use does 
not insert another
   row. Two threads using it for the first time at the same time both succeed.
diff --git a/scripts/h2/schema-2.0.0-h2.sql b/scripts/h2/schema-2.0.0-h2.sql
index 179283dc9e..d3850bccb7 100644
--- a/scripts/h2/schema-2.0.0-h2.sql
+++ b/scripts/h2/schema-2.0.0-h2.sql
@@ -859,3 +859,27 @@ CREATE TABLE IF NOT EXISTS glossary_term_synonym (
 );
 COMMENT ON TABLE glossary_term_synonym IS 'glossary term synonyms, different 
terms may share the same synonym';
 CREATE INDEX IF NOT EXISTS idx_glossary_synonym ON glossary_term_synonym 
(metalake_id, synonym_key, deleted_at);
+
+CREATE TABLE IF NOT EXISTS glossary_term_rel (
+    metalake_id BIGINT NOT NULL,
+    from_term_id BIGINT NOT NULL,
+    to_term_id BIGINT NOT NULL,
+    rel_type VARCHAR(16) NOT NULL,
+    deleted_at BIGINT NOT NULL DEFAULT 0,
+    PRIMARY KEY (from_term_id, to_term_id, rel_type, deleted_at)
+);
+CREATE INDEX IF NOT EXISTS idx_glossary_rel_to ON glossary_term_rel 
(to_term_id, rel_type, deleted_at);
+CREATE INDEX IF NOT EXISTS idx_glossary_rel_metalake ON glossary_term_rel 
(metalake_id, deleted_at);
+CREATE INDEX IF NOT EXISTS idx_glossary_rel_deleted ON glossary_term_rel 
(deleted_at, from_term_id, to_term_id, rel_type);
+COMMENT ON TABLE glossary_term_rel IS 'glossary directed broader and canonical 
related edges';
+COMMENT ON COLUMN glossary_term_rel.metalake_id IS 'owning metalake id';
+COMMENT ON COLUMN glossary_term_rel.from_term_id IS 'child id for BROADER, 
smaller endpoint id for RELATED';
+COMMENT ON COLUMN glossary_term_rel.to_term_id IS 'parent id for BROADER, 
larger endpoint id for RELATED';
+COMMENT ON COLUMN glossary_term_rel.rel_type IS 'BROADER or RELATED, e.g. A 
BROADER B means A is a kind of B';
+COMMENT ON COLUMN glossary_term_rel.deleted_at IS 'retirement time in epoch 
milliseconds, advanced past retained generations to avoid collisions, 0 means 
live';
+
+CREATE TABLE IF NOT EXISTS glossary_hierarchy_lock (
+    metalake_id BIGINT NOT NULL PRIMARY KEY
+);
+COMMENT ON TABLE glossary_hierarchy_lock IS 'serializes glossary hierarchy and 
name checks within a metalake';
+COMMENT ON COLUMN glossary_hierarchy_lock.metalake_id IS 'owning metalake id, 
one database mutex row per metalake';
diff --git a/scripts/h2/upgrade-1.3.0-to-2.0.0-h2.sql 
b/scripts/h2/upgrade-1.3.0-to-2.0.0-h2.sql
index 97b262a739..f1be7be8c4 100644
--- a/scripts/h2/upgrade-1.3.0-to-2.0.0-h2.sql
+++ b/scripts/h2/upgrade-1.3.0-to-2.0.0-h2.sql
@@ -456,3 +456,27 @@ CREATE TABLE IF NOT EXISTS glossary_term_synonym (
 );
 COMMENT ON TABLE glossary_term_synonym IS 'glossary term synonyms, different 
terms may share the same synonym';
 CREATE INDEX IF NOT EXISTS idx_glossary_synonym ON glossary_term_synonym 
(metalake_id, synonym_key, deleted_at);
+
+CREATE TABLE IF NOT EXISTS glossary_term_rel (
+    metalake_id BIGINT NOT NULL,
+    from_term_id BIGINT NOT NULL,
+    to_term_id BIGINT NOT NULL,
+    rel_type VARCHAR(16) NOT NULL,
+    deleted_at BIGINT NOT NULL DEFAULT 0,
+    PRIMARY KEY (from_term_id, to_term_id, rel_type, deleted_at)
+);
+CREATE INDEX IF NOT EXISTS idx_glossary_rel_to ON glossary_term_rel 
(to_term_id, rel_type, deleted_at);
+CREATE INDEX IF NOT EXISTS idx_glossary_rel_metalake ON glossary_term_rel 
(metalake_id, deleted_at);
+CREATE INDEX IF NOT EXISTS idx_glossary_rel_deleted ON glossary_term_rel 
(deleted_at, from_term_id, to_term_id, rel_type);
+COMMENT ON TABLE glossary_term_rel IS 'glossary directed broader and canonical 
related edges';
+COMMENT ON COLUMN glossary_term_rel.metalake_id IS 'owning metalake id';
+COMMENT ON COLUMN glossary_term_rel.from_term_id IS 'child id for BROADER, 
smaller endpoint id for RELATED';
+COMMENT ON COLUMN glossary_term_rel.to_term_id IS 'parent id for BROADER, 
larger endpoint id for RELATED';
+COMMENT ON COLUMN glossary_term_rel.rel_type IS 'BROADER or RELATED, e.g. A 
BROADER B means A is a kind of B';
+COMMENT ON COLUMN glossary_term_rel.deleted_at IS 'retirement time in epoch 
milliseconds, advanced past retained generations to avoid collisions, 0 means 
live';
+
+CREATE TABLE IF NOT EXISTS glossary_hierarchy_lock (
+    metalake_id BIGINT NOT NULL PRIMARY KEY
+);
+COMMENT ON TABLE glossary_hierarchy_lock IS 'serializes glossary hierarchy and 
name checks within a metalake';
+COMMENT ON COLUMN glossary_hierarchy_lock.metalake_id IS 'owning metalake id, 
one database mutex row per metalake';
diff --git a/scripts/mysql/schema-2.0.0-mysql.sql 
b/scripts/mysql/schema-2.0.0-mysql.sql
index 2cfaaed4fd..781288d6a8 100644
--- a/scripts/mysql/schema-2.0.0-mysql.sql
+++ b/scripts/mysql/schema-2.0.0-mysql.sql
@@ -847,3 +847,19 @@ CREATE TABLE IF NOT EXISTS glossary_term_synonym (
     PRIMARY KEY (term_id, synonym_key, deleted_at),
     KEY idx_glossary_synonym (metalake_id, synonym_key, deleted_at)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'glossary 
term synonyms, different terms may share the same synonym';
+
+CREATE TABLE IF NOT EXISTS glossary_term_rel (
+    metalake_id BIGINT NOT NULL COMMENT 'owning metalake id',
+    from_term_id BIGINT NOT NULL COMMENT 'child id for BROADER, smaller 
endpoint id for RELATED',
+    to_term_id BIGINT NOT NULL COMMENT 'parent id for BROADER, larger endpoint 
id for RELATED',
+    rel_type VARCHAR(16) NOT NULL COMMENT 'BROADER or RELATED, e.g. A BROADER 
B means A is a kind of B',
+    deleted_at BIGINT NOT NULL DEFAULT 0 COMMENT 'retirement time in epoch 
milliseconds, advanced past retained generations to avoid collisions, 0 means 
live',
+    PRIMARY KEY (from_term_id, to_term_id, rel_type, deleted_at),
+    KEY idx_glossary_rel_to (to_term_id, rel_type, deleted_at),
+    KEY idx_glossary_rel_metalake (metalake_id, deleted_at),
+    KEY idx_glossary_rel_deleted (deleted_at, from_term_id, to_term_id, 
rel_type)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'glossary 
directed broader and canonical related edges';
+
+CREATE TABLE IF NOT EXISTS glossary_hierarchy_lock (
+    metalake_id BIGINT NOT NULL PRIMARY KEY COMMENT 'owning metalake id, one 
database mutex row per metalake'
+) ENGINE=InnoDB COMMENT 'serializes glossary hierarchy and name checks within 
a metalake';
diff --git a/scripts/mysql/upgrade-1.3.0-to-2.0.0-mysql.sql 
b/scripts/mysql/upgrade-1.3.0-to-2.0.0-mysql.sql
index 9741432c97..737f91dfa5 100644
--- a/scripts/mysql/upgrade-1.3.0-to-2.0.0-mysql.sql
+++ b/scripts/mysql/upgrade-1.3.0-to-2.0.0-mysql.sql
@@ -954,3 +954,19 @@ CREATE TABLE IF NOT EXISTS glossary_term_synonym (
     PRIMARY KEY (term_id, synonym_key, deleted_at),
     KEY idx_glossary_synonym (metalake_id, synonym_key, deleted_at)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'glossary 
term synonyms, different terms may share the same synonym';
+
+CREATE TABLE IF NOT EXISTS glossary_term_rel (
+    metalake_id BIGINT NOT NULL COMMENT 'owning metalake id',
+    from_term_id BIGINT NOT NULL COMMENT 'child id for BROADER, smaller 
endpoint id for RELATED',
+    to_term_id BIGINT NOT NULL COMMENT 'parent id for BROADER, larger endpoint 
id for RELATED',
+    rel_type VARCHAR(16) NOT NULL COMMENT 'BROADER or RELATED, e.g. A BROADER 
B means A is a kind of B',
+    deleted_at BIGINT NOT NULL DEFAULT 0 COMMENT 'retirement time in epoch 
milliseconds, advanced past retained generations to avoid collisions, 0 means 
live',
+    PRIMARY KEY (from_term_id, to_term_id, rel_type, deleted_at),
+    KEY idx_glossary_rel_to (to_term_id, rel_type, deleted_at),
+    KEY idx_glossary_rel_metalake (metalake_id, deleted_at),
+    KEY idx_glossary_rel_deleted (deleted_at, from_term_id, to_term_id, 
rel_type)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'glossary 
directed broader and canonical related edges';
+
+CREATE TABLE IF NOT EXISTS glossary_hierarchy_lock (
+    metalake_id BIGINT NOT NULL PRIMARY KEY COMMENT 'owning metalake id, one 
database mutex row per metalake'
+) ENGINE=InnoDB COMMENT 'serializes glossary hierarchy and name checks within 
a metalake';
diff --git a/scripts/postgresql/schema-2.0.0-postgresql.sql 
b/scripts/postgresql/schema-2.0.0-postgresql.sql
index 77d44ab1e8..8030337dd6 100644
--- a/scripts/postgresql/schema-2.0.0-postgresql.sql
+++ b/scripts/postgresql/schema-2.0.0-postgresql.sql
@@ -1464,3 +1464,27 @@ COMMENT ON COLUMN glossary_term_synonym.metalake_id IS 
'owning metalake id';
 COMMENT ON COLUMN glossary_term_synonym.synonym IS 'glossary term synonym 
display name';
 COMMENT ON COLUMN glossary_term_synonym.synonym_key IS 'synonym lookup key: 
trimmed, whitespace-collapsed and lowercased synonym, e.g. " ACTIVE   USER " -> 
"active user"';
 COMMENT ON COLUMN glossary_term_synonym.deleted_at IS 'soft deletion time in 
epoch milliseconds, 0 means live';
+
+CREATE TABLE IF NOT EXISTS glossary_term_rel (
+    metalake_id BIGINT NOT NULL,
+    from_term_id BIGINT NOT NULL,
+    to_term_id BIGINT NOT NULL,
+    rel_type VARCHAR(16) NOT NULL,
+    deleted_at BIGINT NOT NULL DEFAULT 0,
+    PRIMARY KEY (from_term_id, to_term_id, rel_type, deleted_at)
+);
+CREATE INDEX IF NOT EXISTS idx_glossary_rel_to ON glossary_term_rel 
(to_term_id, rel_type, deleted_at);
+CREATE INDEX IF NOT EXISTS idx_glossary_rel_metalake ON glossary_term_rel 
(metalake_id, deleted_at);
+CREATE INDEX IF NOT EXISTS idx_glossary_rel_deleted ON glossary_term_rel 
(deleted_at, from_term_id, to_term_id, rel_type);
+COMMENT ON TABLE glossary_term_rel IS 'glossary directed broader and canonical 
related edges';
+COMMENT ON COLUMN glossary_term_rel.metalake_id IS 'owning metalake id';
+COMMENT ON COLUMN glossary_term_rel.from_term_id IS 'child id for BROADER, 
smaller endpoint id for RELATED';
+COMMENT ON COLUMN glossary_term_rel.to_term_id IS 'parent id for BROADER, 
larger endpoint id for RELATED';
+COMMENT ON COLUMN glossary_term_rel.rel_type IS 'BROADER or RELATED, e.g. A 
BROADER B means A is a kind of B';
+COMMENT ON COLUMN glossary_term_rel.deleted_at IS 'retirement time in epoch 
milliseconds, advanced past retained generations to avoid collisions, 0 means 
live';
+
+CREATE TABLE IF NOT EXISTS glossary_hierarchy_lock (
+    metalake_id BIGINT NOT NULL PRIMARY KEY
+);
+COMMENT ON TABLE glossary_hierarchy_lock IS 'serializes glossary hierarchy and 
name checks within a metalake';
+COMMENT ON COLUMN glossary_hierarchy_lock.metalake_id IS 'owning metalake id, 
one database mutex row per metalake';
diff --git a/scripts/postgresql/upgrade-1.3.0-to-2.0.0-postgresql.sql 
b/scripts/postgresql/upgrade-1.3.0-to-2.0.0-postgresql.sql
index 4675950537..39c5585cdf 100644
--- a/scripts/postgresql/upgrade-1.3.0-to-2.0.0-postgresql.sql
+++ b/scripts/postgresql/upgrade-1.3.0-to-2.0.0-postgresql.sql
@@ -603,3 +603,27 @@ COMMENT ON COLUMN glossary_term_synonym.metalake_id IS 
'owning metalake id';
 COMMENT ON COLUMN glossary_term_synonym.synonym IS 'glossary term synonym 
display name';
 COMMENT ON COLUMN glossary_term_synonym.synonym_key IS 'synonym lookup key: 
trimmed, whitespace-collapsed and lowercased synonym, e.g. " ACTIVE   USER " -> 
"active user"';
 COMMENT ON COLUMN glossary_term_synonym.deleted_at IS 'soft deletion time in 
epoch milliseconds, 0 means live';
+
+CREATE TABLE IF NOT EXISTS glossary_term_rel (
+    metalake_id BIGINT NOT NULL,
+    from_term_id BIGINT NOT NULL,
+    to_term_id BIGINT NOT NULL,
+    rel_type VARCHAR(16) NOT NULL,
+    deleted_at BIGINT NOT NULL DEFAULT 0,
+    PRIMARY KEY (from_term_id, to_term_id, rel_type, deleted_at)
+);
+CREATE INDEX IF NOT EXISTS idx_glossary_rel_to ON glossary_term_rel 
(to_term_id, rel_type, deleted_at);
+CREATE INDEX IF NOT EXISTS idx_glossary_rel_metalake ON glossary_term_rel 
(metalake_id, deleted_at);
+CREATE INDEX IF NOT EXISTS idx_glossary_rel_deleted ON glossary_term_rel 
(deleted_at, from_term_id, to_term_id, rel_type);
+COMMENT ON TABLE glossary_term_rel IS 'glossary directed broader and canonical 
related edges';
+COMMENT ON COLUMN glossary_term_rel.metalake_id IS 'owning metalake id';
+COMMENT ON COLUMN glossary_term_rel.from_term_id IS 'child id for BROADER, 
smaller endpoint id for RELATED';
+COMMENT ON COLUMN glossary_term_rel.to_term_id IS 'parent id for BROADER, 
larger endpoint id for RELATED';
+COMMENT ON COLUMN glossary_term_rel.rel_type IS 'BROADER or RELATED, e.g. A 
BROADER B means A is a kind of B';
+COMMENT ON COLUMN glossary_term_rel.deleted_at IS 'retirement time in epoch 
milliseconds, advanced past retained generations to avoid collisions, 0 means 
live';
+
+CREATE TABLE IF NOT EXISTS glossary_hierarchy_lock (
+    metalake_id BIGINT NOT NULL PRIMARY KEY
+);
+COMMENT ON TABLE glossary_hierarchy_lock IS 'serializes glossary hierarchy and 
name checks within a metalake';
+COMMENT ON COLUMN glossary_hierarchy_lock.metalake_id IS 'owning metalake id, 
one database mutex row per metalake';

Reply via email to