yuqi1129 commented on code in PR #14239: URL: https://github.com/apache/gravitino/pull/14239#discussion_r4563672664
########## design-docs/glossary-design.md: ########## @@ -0,0 +1,1661 @@ +<!-- + 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. +--> + +# Design: Business Glossary + +| Version | Author | Date | Status | +| ------- | ------ | ---------- | ------ | +| 0.6 | Qi Yu | 2026-11-09 | Draft | + +## Background + +Gravitino knows where data lives: catalogs, schemas and tables. With Domains +(apache/gravitino#13867), it also knows the business area of the data. But it does not know what a +business word means. Words like "Active Customer" or "Net Revenue" are defined in wikis and BI +tools. Each user and each agent maps the word to tables and metrics in its own way. Nobody owns the +definition. + +A business glossary solves this. It is a managed list of **terms**. Each term has a definition, +synonyms, an owner and a status. Terms are grouped by domain and by a parent-child hierarchy. A term +is linked to the columns, tables and metrics behind it. An agent can look up a word from a question, +find the approved term, and follow its links to the data. + +The glossary is built in two steps. **Step 1** is this design: terms, relations, bindings, status, +privileges on the metalake, APIs and agent lookup. **Step 2** adds review of changes, version +history and grants on domains. Implementation Steps lists what each step contains. + +## Goals + +1. **Term object**: a `GlossaryTerm` under the metalake. It has a name, definition, synonyms, owner, + status, domains, documentation links, properties and an optional source reference. There is no + glossary container. Domains and the term hierarchy group the terms. Terms can carry tags through + the existing tag APIs. +2. **Hierarchy**: a term can have several broader (parent) terms, in any domain. Narrower (child) + terms come from the other side. `RELATED` links two terms both ways. The server rejects cycles. +3. **Bindings**: a term can be linked to catalogs, schemas, tables, views, columns, filesets, + topics and models (where the data is), and to semantic-model metrics (what is computed from it). + Column bindings in Step 1 support table columns only; views themselves can be bound. A term + lists its objects, and an object lists its terms. A binding never gives access to data. +4. **Domains**: a term belongs to zero or more domains. A domain is optional when a term is + created. In Step 1, domains group and filter terms. They do not change who can see or manage a + term. +5. **Status**: `DRAFT`, `APPROVED` or `DEPRECATED`. New terms are `APPROVED`. Anyone who can edit a + term can set its status, in the create or update call. There are no transition rules. Agents + only see `APPROVED` terms they can read. Step 1 has no approval decision; `APPROVED` means + available for agent use. +6. **Privileges**: `VIEW_DEFINITION`, `CREATE_DEFINITION` and `MANAGE_DEFINITIONS`, granted on the + metalake. CREATE permits creation and maintenance of own terms; MANAGE permits reading, + editing and deleting any term, without an approval role in Step 1. Drafts are visible only to + their owner with CREATE and to MANAGE. Deny wins over allow. REST and MCP use the same rules. +7. **Revisions**: every content change increases the revision number of the term, and is audited. + There are no content snapshots and no history API in Step 1. +8. **APIs**: REST, Java and Python clients, read-only MCP tools, events and audit. Each view of the + glossary page needs one or two REST calls. An agent can look up all business words of a question + in one call. + +## Non-Goals + +1. **Approval workflow, version history and grants on domains**: these come in Step 2 (see + Implementation Steps). In Step 1, edits take effect at once. Step 2 plugs in through + `TermChangeHandler` (see Status and versions). +2. **CSV import/export in Step 1, external connectors and SKOS export**: Step 1 provides APIs + and a source reference for future importers. CSV is retained as Step 2 task S2.6, not dropped + from the feature plan. External connectors and SKOS export remain later work. +3. **Ranked, fuzzy or semantic lookup in Step 1**: Step 1 only matches names and synonyms exactly + (ignoring case and extra spaces). This is enough for words that the glossary defines. Better + matching can come later without an API change: `matchedBy` can get new values (for example + `FUZZY` or `SEMANTIC`) and a score, and `resolve_business_term` keeps the same input and output. +4. **Access through terms**: a term or a binding never gives or blocks access to data. Terms have + no policies. +5. **Agent writes and the UI itself**: the MCP tools are read-only. The UI uses the REST API. Web UI + support lists the calls for each part of the page. + +## Delivery Scope and Tracking + +This is a design PR. T1–T19 describe future implementation work, not runtime functionality +delivered by merging this document. [Issue #14238](https://github.com/apache/gravitino/issues/14238) +also lists design requirements assigned to Step 2, including CSV import/export. The scope is: + +| Requirement in #14238 | Step 1 design | Later work and tracking | +| ------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ------------------------------------------------------------------- | +| Terms, explicit domain membership, hierarchy, asset/metric bindings, REST, clients and exact MCP lookup | Covered by this document and T1–T19; membership uses selected Option A | Step 2 extends the same identities and live store | +| Definition grants on domains | Metalake grants only | S2.3: domain grants and inherited authorization | +| Version snapshots and history | Revision and audit only; no snapshots | S2.2: approved snapshots, history and diffs | +| Independent review and no self-approval | No review; default APPROVED and immediate edits | S2.1: proposed changes, reviewer authorization and no self-approval | +| CSV import/export | No CSV endpoint or format; APIs and source references are prerequisites only | S2.6: a separate CSV design and implementation task | + +Until the remaining design requirements are accepted or explicitly split into linked follow-up +issues, #14238 remains open. The PR description should use `Related to #14238`, rather than +`Fixes #14238`. The S2 task IDs below track the deferred scope locally; they are not GitHub issue +numbers. Filing the follow-up issues and linking them from #14238 is still a separate step. +CSV remains planned, with its scope tracked in S2.6. + +## Usage Scenario + +1. An admin with `MANAGE_DEFINITIONS` on the metalake creates term `Customer` in domain Sales. New + terms are `APPROVED`, so users with `VIEW_DEFINITION` can see it at once. +2. An analyst with `CREATE_DEFINITION` on the metalake creates `Active Customer` with status + `DRAFT`, so agents do not use it yet. Its broader term is `Customer` and its synonym is + `active user`. The analyst links it to column `dw.sales.customers.is_active` (Implemented by). +3. When the definition is ready, the analyst sets `Active Customer` to `APPROVED`. The analyst owns + this term, so the analyst can edit it and set its status. The analyst cannot edit `Customer`. +4. The owner of semantic model `dw.sales.sales_model` links its metric `active_customers` to + `Active Customer`. The term now shows the metric under Used by. +5. A user asks an agent for "net revenue from VIP active users last month". The agent picks the + business words and calls `resolve_business_term(["net revenue", "VIP", "active user"])` once: + - `active user` returns `Active Customer` (matched by synonym), with its column and metric. + `net revenue` returns `Net revenue`, with its metric. The result only contains what the user + can read. + - `VIP` has no match. The agent asks the user what VIP means. It does not guess a column. + + Then the agent loads the table or the semantic model with the existing tools. The full flow is + in Agent integration. +6. Later the term is replaced. The owner or the admin can set it to `DEPRECATED`, and agents stop + seeing it. The admin can delete it in any status; deprecation is optional before deletion. + +## Design + +### Data model + +``` +GlossaryTerm { id, name, definition, synonyms[], status: DRAFT | APPROVED | DEPRECATED, + links[{label, url}], sourceRef?, properties, currentVersion, audit_info } + // tags: the existing tag relation tables +TermRelation { fromTermId, toTermId, type: BROADER | RELATED, audit_info } +TermDomain { termId, domainId, audit_info } // Option A in Domain membership +TermBinding { termId, targetId, targetType, audit_info } +TermVersion { termId, version, state, snapshot, audit_info } // created now; rows from Step 2 +``` + +| Table | Unique key | Other index | +| ---------------------------- | ------------------------------------------------------------------------------ | ---------------------------------------- | +| `glossary_term_meta` | `(metalake_id, name_key, deleted_at)`, `(metalake_id, source_ref, deleted_at)` | | +| `glossary_term_synonym` | `(term_id, synonym_key, deleted_at)` | `(metalake_id, synonym_key, deleted_at)` | +| `glossary_term_rel` | `(from_term_id, to_term_id, rel_type, deleted_at)` | `(to_term_id, rel_type)` | +| `glossary_term_domain_rel` | `(term_id, domain_id, deleted_at)` | `(domain_id)` | +| `glossary_term_binding` | `(term_id, target_type, target_id, deleted_at)` | `(target_type, target_id)` | +| `glossary_term_version_info` | `(term_id, version, deleted_at)` | `(term_id, state)` | + +- The tables are added to the H2, MySQL and PostgreSQL schemas and to the `upgrade-1.3.0-to-2.0.0` + scripts. +- **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 + name on every database. Responses return the name as the user typed it. Names follow the tag and + domain rules: up to 128 characters, and `/` is allowed (URL-encoded in paths). +- **Synonyms** are stored one per row, with `synonym_key = key(synonym)`. Two terms can share a + synonym. A synonym cannot be the name of another term. The server checks this in both + directions: when a synonym is added, and when a term is created or renamed (400). Create, rename + and synonym changes take the same per-metalake hierarchy lock before checking (see Locking). +- **Documentation links** (a label and a URL) are shown on the term page. They are stored in a JSON + column of `glossary_term_meta`. No query reads inside them. +- **Source reference** is optional. When set, it is unique in the metalake. It records where an + imported term came from, in the form `<system>:<id>`, for example + `datahub:urn:li:glossaryTerm:Customer`. A new import can then update the term instead of creating + a copy. A term without a source reference was created in Gravitino. +- `MetadataObject.Type.GLOSSARY_TERM` is added for owners, tags, events and audit. Privileges + **cannot be granted on a single term**: the role APIs reject them. +- Terms, relations and bindings are not cached. Every request reads the store, the same as for + domains. + +### Relations + +- `BROADER` is stored on the child. A → B means "A is a kind of B". Narrower terms are not stored; + the server finds them from the `BROADER` rows. `RELATED` is stored once per pair (with + `from_term_id < to_term_id`) and shows on both terms. +- Setting the broader or related term of A only changes A. The caller needs the edit privilege on A + and read access to the other term, including its draft visibility check (see Access control). +- **Cycle check**: adding A → B fails with 400 if B already reaches A through `BROADER` links. The + server walks up from B, level by level, under the hierarchy lock (see Locking). A term cannot be + its own parent. +- **Depth limit**: a `BROADER` chain has at most `L` links, where `L` is the release depth-limit + constant in `GlossaryManager`. A new link that makes a chain longer fails with 400. This bounds + the cycle check and the hierarchy read. 20 is the provisional value; T18 in Testing selects the + final release value. Boundary tests use the loaded limit, not the provisional number. +- **No overlap**: two terms cannot be `RELATED` if one is an ancestor of the other. Adding such a + `RELATED` link, or a `BROADER` link that creates such a pair, fails with 400. This follows the + SKOS rule. For a new `RELATED` pair, check ancestry in both directions. Before adding A → B, + collect A and all its descendants, and B and all its ancestors. Reject the link if any + `RELATED` pair crosses these two sets, regardless of how that pair is stored. For example, + 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 + 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. +- Deprecating a term does not change its children. Deleting a term removes its links. Each child + that loses a parent, and each surviving term that loses a `RELATED` link, gets one revision + increment and its own audit record in the cleanup transaction (see Status and versions). The + child keeps its other parents, or becomes a top-level term. + +How other systems store term relations: + +| System | Where relations are stored | Parents per term | Cycle check | +| ---------------- | ---------------------------------------------- | ---------------- | ------------------- | +| DataHub | a list of outgoing links on the source term | one term group | not documented | +| OpenMetadata | one shared relation table for all entities | one | tree, so not needed | +| Apache Atlas | edges in a graph database | many (`isA`) | self-link only | +| Gravitino Domain | `DomainRel { parentId, childId }` edge table | one, one level | not needed | +| This design | `glossary_term_rel` edge table, like DomainRel | many, any depth | yes, under a lock | + +All of them store one direction and derive the other. The only new part here is many parents at +any depth. That is why this design needs the cycle check and the hierarchy lock. + +### Domain membership + +A term belongs to zero or more domains. In Step 1 the definition privileges are granted on the +metalake only, so a domain groups and filters terms but does not change who can see or manage them. +In Step 2, domains also become the scope of grants (see Implementation Steps). Then membership +decides who manages a term. **Decision: Option A, explicit relations.** Jerry selected it in the +[November 9 review](https://github.com/apache/gravitino/pull/14239#discussion_r4512415347), and +the author acknowledged the choice. Step 1 and Step 2 use this single membership source. +Backing tags (Option B) are retained under [Alternatives Considered](#alternatives-considered), +not as an implementation prerequisite. + +**Selected design: explicit relation (Option A)** + +- A table `glossary_term_domain_rel (term_id, domain_id)`. Only the term API changes it: `domains` + on create, `addDomain` and `removeDomain`. These changes go through `TermChangeHandler`, like any + term change. +- To add a term to a domain, the caller needs the edit privilege on the term, and must be able to + see the domain (`USE_DOMAIN`). In Step 2, the caller also needs `CREATE_DEFINITION` on that + domain, so nobody can move a term into a domain where they cannot write. +- **Terms of a domain** (`GET /terms?domain=`) use the same scope as the Domain design: terms in + the domain, and terms in its subdomains that the caller can see. +- **Domains in a response**: every `TermDTO.domains` contains only domains the caller can see + through the ordinary domain-read check (`USE_DOMAIN`). Apply this to direct gets, list and + lookup results, nested terms, and create/alter responses. A readable term remains readable + even if some or all of its domains are hidden; its returned domain list can be empty. Filtering + a response never changes stored membership or reveals a hidden-domain count. +- Dropping a domain that still has terms fails with 409 `NonEmptyDomainException`. This is the same + as a domain with subdomains. Removing the terms silently would change how they are grouped, and in + Step 2 who manages them. The change is one more check in `DomainManager#dropDomain`. +- **Descriptive tags** on terms use the existing tag APIs and `APPLY_TAG`. A tag on a term never + changes its domains, even when the tag backs a domain. + +**Rationale for Option A.** Most reasons are about Step 2: + +1. **In Step 2, the domain decides who can read and manage a term.** For an asset, being in a domain + gives nobody any permission. That is why the Domain design lets anyone with `APPLY_TAG` add an + asset. It is also why the Domain design does not allow access grants on domains. Terms are the + opposite case: in Step 2, the grants on a term's domains decide who can see, edit and approve + it. With Option B, adding a tag would change these permissions. +2. **Tag permissions go to other people.** In the Domain design, admins give `APPLY_TAG` on a + domain's tag to the owners of the tables in that domain. With Option B in Step 2, any of these + table owners could move a term into the domain. The domain admins would then control the term. Or + the term would be hidden from a role that the domain denies. One tag cannot allow this for tables + and forbid it for terms. +3. **The benefits of tags do not apply to terms.** The Domain design uses tags for three things: + inheritance from catalogs and schemas, tag-based policies, and the existing tag checks. Terms + are not under a catalog or schema. Terms have no policies. And in Step 2 terms need stricter + checks than `APPLY_TAG`. +4. **Permissions do not change by accident.** With Option B, replacing or deleting a domain's tag + silently removes its terms. In Step 2, who can see or edit them changes, but nobody edited a + term. With + Option A, membership changes only through the term API. It is checked and audited like any + other term edit, and in Step 2 it is reviewed. +5. **Smaller change to the Domain design.** Option A adds one check when a domain is dropped. + Option B makes terms taggable, adds a member type, and adds term-only rules to the shared tag + code. + +The cost: the terms of a domain are listed by `GET /terms?domain=`, not by +`GET /domains/{domain}/objects`. Both use the same rules: a term can be in several domains, and a +domain includes its subdomains. + +### Bindings + +A binding links a term to the data behind it. A term page shows two kinds of bindings. An object +page shows the terms linked to the object. + +| Kind | Meaning | Targets | Example | +| ------------------ | ---------------------------------------------- | --------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | +| **Implemented by** | The object stores or computes the term | `CATALOG`, `SCHEMA`, `TABLE`, `VIEW`, `COLUMN`, `FILESET`, `TOPIC`, `MODEL` | `Customer` is implemented by table `sales.public.customers` and column `customers.customer_id` | +| **Used by** | A semantic-model metric is built from the term | `METRIC`, identified by its existing `metric_id` | metric `net_revenue` uses `Net revenue` and `Order` | + +**Column scope in Step 1**: `COLUMN` means a table column. Resolve its identity as +`catalog.schema.table.column`, using the table and column IDs, and authorize through that table. +The endpoint fence is metalake -> catalog -> schema -> table, followed by the existing column +identity check. Table alteration fences column changes and cleans up removed-column bindings; +table/column renames preserve the IDs and bindings. A COLUMN lookup whose parent resolves only +as a view returns 404; do not reinterpret a view as a table. View-column bindings are outside +Step 1. Binding a view itself remains supported, but `children=true` on a view returns 400. + +Both kinds are stored in `glossary_term_binding`, using the target's own stable ID: + +- `target_type` identifies one of the eight Implemented by asset types, or `METRIC` for Used by. + This is a binding-specific type; it does not add `METRIC` to `MetadataObject.Type`. +- `target_id` is the asset's ID, the stable column ID for `COLUMN` (not a version-row ID), or the + existing `semantic_model_metric_meta.metric_id` for `METRIC`. It is never the containing + semantic-model ID for a metric binding. The containing table or semantic model is resolved + from the target identity for authorization, endpoint locking and cleanup. +- All columns of `(term_id, target_type, target_id, deleted_at)` are `NOT NULL`, with + `deleted_at = 0` for a live row. This key prevents duplicate bindings on H2, MySQL and PostgreSQL + without nullable fields, empty-string markers or metric names in the key. +- REST and client inputs still identify a metric by semantic model and exact metric name. The + server resolves that input to a live metric ID before binding. Responses resolve the ID back + to its current model/name; the existing `TermBindingDTO` and MCP argument shapes are unchanged. + +A binding is direct only: binding a table does not bind its columns. `glossary_term_rel` stores +term-to-term relations; `glossary_term_binding` stores term-to-asset and term-to-metric bindings. + +- There is no semantic view type in Gravitino. A semantic view from another system (for example + Snowflake) is stored as a semantic model, so its metrics use Used by. + +**One write endpoint, two ways to be allowed** + +Bindings are written on the object, the same as tags and policies: +`POST /objects/{type}/{fullName}/terms`, or `POST /objects/semantic_model/{fullName}/metrics/{metric}/terms` +for a metric. Two kinds of people know about a binding: + +- the object admin knows what the object means; +- the term owner knows which data implements the term. + +Both can write bindings. The server checks each term in the request separately: + +| Caller | Needs | Terms allowed | +| ------------ | ---------------------------------------------------------------- | ------------------------------------------------- | +| Object admin | Admin privilege on the object, and `VIEW_DEFINITION` on the term | `APPROVED` only | +| Term editor | Edit privilege on the term, and read access to the object | Any status, so a draft can get its bindings early | + +- **Admin privilege on an object**: + - tables and columns: the existing `MODIFY_TABLE_AUTHORIZATION_EXPRESSION` (owner of the table or + of a parent, or `MODIFY_TABLE` with `USE_CATALOG` and `USE_SCHEMA`); + - views: the existing `VIEW_OWNER_AUTHORIZATION_EXPRESSION` (owner of the view or of a parent); + - metrics: `MODIFY_SEMANTIC_MODEL_AUTHORIZATION_EXPRESSION`; + - other types have no modify privilege, so the caller must own the object or one of its parents + (metalake, catalog, schema). +- The endpoint checks the object once, and then checks each term in the request body in code. + A missing or hidden term returns 404 before checking its status. For a visible term, allow the + term-editor path in any status, even when the caller is also an object admin. Otherwise, an + object admin can use only `APPROVED` terms; another status returns 400. A caller satisfying + neither authorization path gets 403. Failure on any term rejects the whole request and + changes nothing. Removing a binding uses the same checks as adding it. +- Each changed term gets a new revision and goes through `TermChangeHandler`. So the Step 2 workflow + can hold a binding change, like any other term change. +- Binding a missing object or metric fails with 404. Binding any other object type fails with 400. + The status restriction on the object-admin path applies only after term visibility is checked + and only when the term-editor path does not allow the operation. +- When a term is deprecated later, it keeps its bindings. It no longer shows in lookups or MCP + results. + +**Reads** + +- `GET /terms/{term}/objects?kind=IMPLEMENTED_BY|USED_BY&types=` lists the bindings of a term. It + first checks read access to the root term, then returns only objects and metrics the caller + can access (`filterMetadataObject`). A table column requires read access to its table. A metric + requires read access to its semantic model. +- `GET /objects/{type}/{fullName}/terms` and `GET /objects/semantic_model/{fullName}/metrics/{metric}/terms` + first authorize reading the target using its ordinary metadata-read expression, then list only + terms the caller can see. For COLUMN, authorize its table; for a metric, authorize its semantic + model and verify the metric exists. Glossary VIEW or MANAGE never replaces target access. + Insufficient target read access returns 403, and a missing target returns 404, with no terms, + child names or counts in the error. Check target access before enumerating children or reading + their bindings. Reuse `LOAD_TABLE_AUTHORIZATION_EXPRESSION` for tables and table columns, + `LOAD_VIEW_AUTHORIZATION_EXPRESSION` for views, `LOAD_SEMANTIC_MODEL_AUTHORIZATION_EXPRESSION` + for models' metrics, and the existing load expression for each other supported type. +- `?children=true` on a table or semantic model also returns the terms of each table column or + metric that has readable terms. A schema tab or a metric table then loads in one call, not one + call per column. On the server it is one query on `glossary_term_binding`, by the table and its + column IDs. For a semantic model, resolve its live metric IDs in a batch and query bindings + with `target_type = METRIC` and those IDs; do not query one metric at a time. Other types, + including VIEW, reject `children=true` with 400. Views still support listing their own terms + with no children. + +**Cleanup** + +- Dropping an object soft-deletes its bindings. This happens in the same places that clean up + `tag_relation_meta` (by object, schema, catalog and metalake). Renames keep the bindings, because + bindings use IDs. +- Dropping a column in `alterTable` soft-deletes the bindings of the column, in the same + transaction. +- Metrics already have internal IDs. When a semantic model is altered, clean up bindings by + `target_type = METRIC` and the retired metric IDs. Reuse the existing metric identity lifecycle: + content edits and semantic-model renames preserve a metric ID; removing a metric retires its ID. + A metric rename is currently removal of the old name and addition of the new name, with a new + ID: its old bindings are removed and must be linked again. Reintroducing a removed name also + gets a new ID and must not revive old bindings. The cleanup writes one audit record per + affected term, listing its ID and name, the semantic-model ID and name, the retired metric IDs + and names, the triggering alter operation and the resulting term revision. This also applies + to metric removal without a rename; bindings are never silently transferred to a new identity. +- Every surviving term that loses bindings gets one revision increment in the same transaction + as the object change and binding cleanup, even if it loses several bindings. Unaffected terms + do not change. The transaction locks all affected term rows in ID order before deleting the + bindings (see Locking). Failure rolls back the object change, bindings and revisions together, + with no successful cleanup audit record. + +### Status and versions + +| Status | Who can see it | Who can delete it | +| -------------------- | ---------------------------------------------------------------- | -------------------- | +| `DRAFT` | owner with `CREATE_DEFINITION`, or `MANAGE_DEFINITIONS`; not MCP | `MANAGE_DEFINITIONS` | +| `APPROVED` (default) | `VIEW_DEFINITION`; MCP also requires this privilege | `MANAGE_DEFINITIONS` | +| `DEPRECATED` | `VIEW_DEFINITION`; not MCP | `MANAGE_DEFINITIONS` | + +- **Status is an ordinary field.** It is set in the create request (default `APPROVED`) or with + `setStatus` in the update request. Anyone who can edit the term can set it: the owner with + `CREATE_DEFINITION`, or `MANAGE_DEFINITIONS`. There are no transition rules and no separate + status endpoint. +- **What `APPROVED` means in Step 1**: the term can be used by agents. It does not mean that a + reviewer accepted it. Creation defaults to this status and makes the term immediately visible + to callers with read access. Content edits to an `APPROVED` term also take effect immediately. + An owner with CREATE can explicitly create a draft, or set any status on an existing own term; + MANAGE can do the same for any term. Neither action is an approval decision or requires a + reviewer in Step 1. Step 2 introduces review separately. +- **Delete** requires `MANAGE_DEFINITIONS` in every status, including `APPROVED`. Being the owner + with CREATE never permits deletion, even after changing a term back to `DRAFT`. Deprecation + before deletion is optional. MANAGE is an administration privilege in Step 1, not an approval + privilege. +- **Why three states**: each term is used on its own. `DRAFT` keeps a term away from agents while + it is written. Bindings and people keep using a term after it is replaced, so `DEPRECATED` keeps + it readable, which a delete cannot do. In Step 2, `APPROVED` also records that a reviewer + accepted the term. A domain or an ontology (#14310) is published as a whole and has no review per + item, so `DRAFT` / `PUBLISHED` is enough there. +- **Every API applies the same term-read authorization** (REST, clients, MCP); MCP additionally + excludes non-`APPROVED` terms. If the caller cannot see a term, lists leave it out and get + returns 404. The same rule applies inside responses. The `broader`, + `narrower` and `related` lists of a term, the terms of an object, and the terms of a domain all + leave out terms the caller cannot see. So a hidden draft never shows up as a relation. +- **Known leaks**: hiding a term does not make it secret. A user can still find out that it exists + in two ways: creating a term with the same name returns 409, and adding a synonym equal to its + name returns 400. +- **Revision**: each change to the name, definition, synonyms, links, properties, relations, + domains, bindings or status increases `current_version` by one, in the same transaction. + Responses return it as `version`, so a client can see that a term changed after it read it. + Owner and tag changes are only audited. +- **Cleanup revisions**: deleting a term, object, column or metric also increments each surviving + term that loses a broader relation, a `RELATED` relation or a binding. Each affected term gets + exactly one increment per cleanup transaction, regardless of the number of removed rows, and + an audit record of the losses with its resulting revision. A change to a derived `narrower` + list alone does not increment the parent, just as adding or removing a broader relation only + changes the child. Terms deleted in the same transaction need no increment. No-op cleanup + changes no revisions; failed cleanup commits neither losses nor revision increments. These + are required cleanup effects, applied with the endpoint deletion rather than left pending for + review in Step 2. +- **No snapshots in Step 1**: the audit log holds the change record. There is no history API. + `glossary_term_version_info` is created with the other tables, but Step 1 writes no rows to it. + Term reads and writes do not need it. A revision is not an approved version. +- **Workflow hook**: `GlossaryManager` sends every change to a `TermChangeHandler`: content, status, + relations, domains, and both binding paths. The default handler applies the change at once. In + Step 2, a review handler keeps the proposed change apart from the live tables until it is + approved. +- Dropping a term soft-deletes its synonyms, relations, domain links, bindings and version rows, in + the same transaction. Dropping a metalake soft-deletes all its glossary rows in + `MetalakeMetaService#deleteMetalake`, next to the tag cleanup. + +### Access control + +In Step 1, the three privileges are granted on the metalake: + +| Action | `VIEW_DEFINITION` | `CREATE_DEFINITION` | `MANAGE_DEFINITIONS` | +| --------------------------------------------------------- | ----------------- | ------------------- | -------------------- | +| Read `APPROVED` and `DEPRECATED` terms; look up words | ✓ | ✓ | ✓ | +| Create a term (the creator becomes the owner) | | ✓ | ✓ | +| See own `DRAFT` terms | | ✓ | ✓ | +| See other users' `DRAFT` terms | | | ✓ | +| Edit, bind and set the status of own terms, in any status | | ✓ | ✓ | +| Edit, bind and set the status of any term | | | ✓ | +| Delete any term, in any status | | | ✓ | + +- `MANAGE_DEFINITIONS` includes `CREATE_DEFINITION`, and `CREATE_DEFINITION` includes + `VIEW_DEFINITION`. The names are general, so other business-definition objects can use them too. +- **Owner versus any term**: `CREATE_DEFINITION` lets a user write and maintain their own terms. + `MANAGE_DEFINITIONS` lets an admin read, edit and delete any term. Ownership means the current + owner, including group members, not necessarily the original creator. Changing status is an Review Comment: Agreed. Glossary ownership checks resolve the current term identity, owner and user/group IDs from the store, bypassing shared owner/name caches, including the generic GLOSSARY_TERM owner-transfer route. New requests after transfer commit must use the new owner; already authorized in-flight work may finish. Group membership itself comes from the authenticated principal, not a Gravitino user-to-group membership table. A still-valid JWT retaining an old group claim follows platform credential freshness until refresh or expiry; owner-cache bypass does not revoke it. T6.12/CUJ 8 exercise two servers with prewarmed caches and a paused invalidation poller. T6.13 covers group-owner transfer and a refreshed principal without the owner group, with separate CREATE held constant. Updated design: [158ae1b688](https://github.com/apache/gravitino/pull/14239/commits/158ae1b688648b04e5b2f34f248d0e0d8e235e04). These are requirements for implementation PRs, not claims that runtime tests have already passed. ########## design-docs/glossary-design.md: ########## @@ -0,0 +1,1661 @@ +<!-- + 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. +--> + +# Design: Business Glossary + +| Version | Author | Date | Status | +| ------- | ------ | ---------- | ------ | +| 0.6 | Qi Yu | 2026-11-09 | Draft | + +## Background + +Gravitino knows where data lives: catalogs, schemas and tables. With Domains +(apache/gravitino#13867), it also knows the business area of the data. But it does not know what a +business word means. Words like "Active Customer" or "Net Revenue" are defined in wikis and BI +tools. Each user and each agent maps the word to tables and metrics in its own way. Nobody owns the +definition. + +A business glossary solves this. It is a managed list of **terms**. Each term has a definition, +synonyms, an owner and a status. Terms are grouped by domain and by a parent-child hierarchy. A term +is linked to the columns, tables and metrics behind it. An agent can look up a word from a question, +find the approved term, and follow its links to the data. + +The glossary is built in two steps. **Step 1** is this design: terms, relations, bindings, status, +privileges on the metalake, APIs and agent lookup. **Step 2** adds review of changes, version +history and grants on domains. Implementation Steps lists what each step contains. + +## Goals + +1. **Term object**: a `GlossaryTerm` under the metalake. It has a name, definition, synonyms, owner, + status, domains, documentation links, properties and an optional source reference. There is no + glossary container. Domains and the term hierarchy group the terms. Terms can carry tags through + the existing tag APIs. +2. **Hierarchy**: a term can have several broader (parent) terms, in any domain. Narrower (child) + terms come from the other side. `RELATED` links two terms both ways. The server rejects cycles. +3. **Bindings**: a term can be linked to catalogs, schemas, tables, views, columns, filesets, + topics and models (where the data is), and to semantic-model metrics (what is computed from it). + Column bindings in Step 1 support table columns only; views themselves can be bound. A term + lists its objects, and an object lists its terms. A binding never gives access to data. +4. **Domains**: a term belongs to zero or more domains. A domain is optional when a term is + created. In Step 1, domains group and filter terms. They do not change who can see or manage a + term. +5. **Status**: `DRAFT`, `APPROVED` or `DEPRECATED`. New terms are `APPROVED`. Anyone who can edit a + term can set its status, in the create or update call. There are no transition rules. Agents + only see `APPROVED` terms they can read. Step 1 has no approval decision; `APPROVED` means + available for agent use. +6. **Privileges**: `VIEW_DEFINITION`, `CREATE_DEFINITION` and `MANAGE_DEFINITIONS`, granted on the + metalake. CREATE permits creation and maintenance of own terms; MANAGE permits reading, + editing and deleting any term, without an approval role in Step 1. Drafts are visible only to + their owner with CREATE and to MANAGE. Deny wins over allow. REST and MCP use the same rules. +7. **Revisions**: every content change increases the revision number of the term, and is audited. + There are no content snapshots and no history API in Step 1. +8. **APIs**: REST, Java and Python clients, read-only MCP tools, events and audit. Each view of the + glossary page needs one or two REST calls. An agent can look up all business words of a question + in one call. + +## Non-Goals + +1. **Approval workflow, version history and grants on domains**: these come in Step 2 (see + Implementation Steps). In Step 1, edits take effect at once. Step 2 plugs in through + `TermChangeHandler` (see Status and versions). +2. **CSV import/export in Step 1, external connectors and SKOS export**: Step 1 provides APIs + and a source reference for future importers. CSV is retained as Step 2 task S2.6, not dropped + from the feature plan. External connectors and SKOS export remain later work. +3. **Ranked, fuzzy or semantic lookup in Step 1**: Step 1 only matches names and synonyms exactly + (ignoring case and extra spaces). This is enough for words that the glossary defines. Better + matching can come later without an API change: `matchedBy` can get new values (for example + `FUZZY` or `SEMANTIC`) and a score, and `resolve_business_term` keeps the same input and output. +4. **Access through terms**: a term or a binding never gives or blocks access to data. Terms have + no policies. +5. **Agent writes and the UI itself**: the MCP tools are read-only. The UI uses the REST API. Web UI + support lists the calls for each part of the page. + +## Delivery Scope and Tracking + +This is a design PR. T1–T19 describe future implementation work, not runtime functionality +delivered by merging this document. [Issue #14238](https://github.com/apache/gravitino/issues/14238) +also lists design requirements assigned to Step 2, including CSV import/export. The scope is: + +| Requirement in #14238 | Step 1 design | Later work and tracking | +| ------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ------------------------------------------------------------------- | +| Terms, explicit domain membership, hierarchy, asset/metric bindings, REST, clients and exact MCP lookup | Covered by this document and T1–T19; membership uses selected Option A | Step 2 extends the same identities and live store | +| Definition grants on domains | Metalake grants only | S2.3: domain grants and inherited authorization | +| Version snapshots and history | Revision and audit only; no snapshots | S2.2: approved snapshots, history and diffs | +| Independent review and no self-approval | No review; default APPROVED and immediate edits | S2.1: proposed changes, reviewer authorization and no self-approval | +| CSV import/export | No CSV endpoint or format; APIs and source references are prerequisites only | S2.6: a separate CSV design and implementation task | + +Until the remaining design requirements are accepted or explicitly split into linked follow-up +issues, #14238 remains open. The PR description should use `Related to #14238`, rather than +`Fixes #14238`. The S2 task IDs below track the deferred scope locally; they are not GitHub issue +numbers. Filing the follow-up issues and linking them from #14238 is still a separate step. +CSV remains planned, with its scope tracked in S2.6. + +## Usage Scenario + +1. An admin with `MANAGE_DEFINITIONS` on the metalake creates term `Customer` in domain Sales. New + terms are `APPROVED`, so users with `VIEW_DEFINITION` can see it at once. +2. An analyst with `CREATE_DEFINITION` on the metalake creates `Active Customer` with status + `DRAFT`, so agents do not use it yet. Its broader term is `Customer` and its synonym is + `active user`. The analyst links it to column `dw.sales.customers.is_active` (Implemented by). +3. When the definition is ready, the analyst sets `Active Customer` to `APPROVED`. The analyst owns + this term, so the analyst can edit it and set its status. The analyst cannot edit `Customer`. +4. The owner of semantic model `dw.sales.sales_model` links its metric `active_customers` to + `Active Customer`. The term now shows the metric under Used by. +5. A user asks an agent for "net revenue from VIP active users last month". The agent picks the + business words and calls `resolve_business_term(["net revenue", "VIP", "active user"])` once: + - `active user` returns `Active Customer` (matched by synonym), with its column and metric. + `net revenue` returns `Net revenue`, with its metric. The result only contains what the user + can read. + - `VIP` has no match. The agent asks the user what VIP means. It does not guess a column. + + Then the agent loads the table or the semantic model with the existing tools. The full flow is + in Agent integration. +6. Later the term is replaced. The owner or the admin can set it to `DEPRECATED`, and agents stop + seeing it. The admin can delete it in any status; deprecation is optional before deletion. + +## Design + +### Data model + +``` +GlossaryTerm { id, name, definition, synonyms[], status: DRAFT | APPROVED | DEPRECATED, + links[{label, url}], sourceRef?, properties, currentVersion, audit_info } + // tags: the existing tag relation tables +TermRelation { fromTermId, toTermId, type: BROADER | RELATED, audit_info } +TermDomain { termId, domainId, audit_info } // Option A in Domain membership +TermBinding { termId, targetId, targetType, audit_info } +TermVersion { termId, version, state, snapshot, audit_info } // created now; rows from Step 2 +``` + +| Table | Unique key | Other index | +| ---------------------------- | ------------------------------------------------------------------------------ | ---------------------------------------- | +| `glossary_term_meta` | `(metalake_id, name_key, deleted_at)`, `(metalake_id, source_ref, deleted_at)` | | +| `glossary_term_synonym` | `(term_id, synonym_key, deleted_at)` | `(metalake_id, synonym_key, deleted_at)` | +| `glossary_term_rel` | `(from_term_id, to_term_id, rel_type, deleted_at)` | `(to_term_id, rel_type)` | +| `glossary_term_domain_rel` | `(term_id, domain_id, deleted_at)` | `(domain_id)` | +| `glossary_term_binding` | `(term_id, target_type, target_id, deleted_at)` | `(target_type, target_id)` | +| `glossary_term_version_info` | `(term_id, version, deleted_at)` | `(term_id, state)` | + +- The tables are added to the H2, MySQL and PostgreSQL schemas and to the `upgrade-1.3.0-to-2.0.0` + scripts. +- **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 + name on every database. Responses return the name as the user typed it. Names follow the tag and + domain rules: up to 128 characters, and `/` is allowed (URL-encoded in paths). +- **Synonyms** are stored one per row, with `synonym_key = key(synonym)`. Two terms can share a + synonym. A synonym cannot be the name of another term. The server checks this in both + directions: when a synonym is added, and when a term is created or renamed (400). Create, rename + and synonym changes take the same per-metalake hierarchy lock before checking (see Locking). +- **Documentation links** (a label and a URL) are shown on the term page. They are stored in a JSON + column of `glossary_term_meta`. No query reads inside them. +- **Source reference** is optional. When set, it is unique in the metalake. It records where an + imported term came from, in the form `<system>:<id>`, for example + `datahub:urn:li:glossaryTerm:Customer`. A new import can then update the term instead of creating + a copy. A term without a source reference was created in Gravitino. +- `MetadataObject.Type.GLOSSARY_TERM` is added for owners, tags, events and audit. Privileges + **cannot be granted on a single term**: the role APIs reject them. +- Terms, relations and bindings are not cached. Every request reads the store, the same as for + domains. + +### Relations + +- `BROADER` is stored on the child. A → B means "A is a kind of B". Narrower terms are not stored; + the server finds them from the `BROADER` rows. `RELATED` is stored once per pair (with + `from_term_id < to_term_id`) and shows on both terms. +- Setting the broader or related term of A only changes A. The caller needs the edit privilege on A + and read access to the other term, including its draft visibility check (see Access control). +- **Cycle check**: adding A → B fails with 400 if B already reaches A through `BROADER` links. The + server walks up from B, level by level, under the hierarchy lock (see Locking). A term cannot be + its own parent. +- **Depth limit**: a `BROADER` chain has at most `L` links, where `L` is the release depth-limit + constant in `GlossaryManager`. A new link that makes a chain longer fails with 400. This bounds + the cycle check and the hierarchy read. 20 is the provisional value; T18 in Testing selects the + final release value. Boundary tests use the loaded limit, not the provisional number. +- **No overlap**: two terms cannot be `RELATED` if one is an ancestor of the other. Adding such a + `RELATED` link, or a `BROADER` link that creates such a pair, fails with 400. This follows the + SKOS rule. For a new `RELATED` pair, check ancestry in both directions. Before adding A → B, + collect A and all its descendants, and B and all its ancestors. Reject the link if any + `RELATED` pair crosses these two sets, regardless of how that pair is stored. For example, + 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 + 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. +- Deprecating a term does not change its children. Deleting a term removes its links. Each child + that loses a parent, and each surviving term that loses a `RELATED` link, gets one revision + increment and its own audit record in the cleanup transaction (see Status and versions). The + child keeps its other parents, or becomes a top-level term. + +How other systems store term relations: + +| System | Where relations are stored | Parents per term | Cycle check | +| ---------------- | ---------------------------------------------- | ---------------- | ------------------- | +| DataHub | a list of outgoing links on the source term | one term group | not documented | +| OpenMetadata | one shared relation table for all entities | one | tree, so not needed | +| Apache Atlas | edges in a graph database | many (`isA`) | self-link only | +| Gravitino Domain | `DomainRel { parentId, childId }` edge table | one, one level | not needed | +| This design | `glossary_term_rel` edge table, like DomainRel | many, any depth | yes, under a lock | + +All of them store one direction and derive the other. The only new part here is many parents at +any depth. That is why this design needs the cycle check and the hierarchy lock. + +### Domain membership + +A term belongs to zero or more domains. In Step 1 the definition privileges are granted on the +metalake only, so a domain groups and filters terms but does not change who can see or manage them. +In Step 2, domains also become the scope of grants (see Implementation Steps). Then membership +decides who manages a term. **Decision: Option A, explicit relations.** Jerry selected it in the +[November 9 review](https://github.com/apache/gravitino/pull/14239#discussion_r4512415347), and +the author acknowledged the choice. Step 1 and Step 2 use this single membership source. +Backing tags (Option B) are retained under [Alternatives Considered](#alternatives-considered), +not as an implementation prerequisite. + +**Selected design: explicit relation (Option A)** + +- A table `glossary_term_domain_rel (term_id, domain_id)`. Only the term API changes it: `domains` + on create, `addDomain` and `removeDomain`. These changes go through `TermChangeHandler`, like any + term change. +- To add a term to a domain, the caller needs the edit privilege on the term, and must be able to + see the domain (`USE_DOMAIN`). In Step 2, the caller also needs `CREATE_DEFINITION` on that + domain, so nobody can move a term into a domain where they cannot write. +- **Terms of a domain** (`GET /terms?domain=`) use the same scope as the Domain design: terms in + the domain, and terms in its subdomains that the caller can see. +- **Domains in a response**: every `TermDTO.domains` contains only domains the caller can see + through the ordinary domain-read check (`USE_DOMAIN`). Apply this to direct gets, list and + lookup results, nested terms, and create/alter responses. A readable term remains readable + even if some or all of its domains are hidden; its returned domain list can be empty. Filtering + a response never changes stored membership or reveals a hidden-domain count. +- Dropping a domain that still has terms fails with 409 `NonEmptyDomainException`. This is the same + as a domain with subdomains. Removing the terms silently would change how they are grouped, and in + Step 2 who manages them. The change is one more check in `DomainManager#dropDomain`. +- **Descriptive tags** on terms use the existing tag APIs and `APPLY_TAG`. A tag on a term never + changes its domains, even when the tag backs a domain. + +**Rationale for Option A.** Most reasons are about Step 2: + +1. **In Step 2, the domain decides who can read and manage a term.** For an asset, being in a domain + gives nobody any permission. That is why the Domain design lets anyone with `APPLY_TAG` add an + asset. It is also why the Domain design does not allow access grants on domains. Terms are the + opposite case: in Step 2, the grants on a term's domains decide who can see, edit and approve + it. With Option B, adding a tag would change these permissions. +2. **Tag permissions go to other people.** In the Domain design, admins give `APPLY_TAG` on a + domain's tag to the owners of the tables in that domain. With Option B in Step 2, any of these + table owners could move a term into the domain. The domain admins would then control the term. Or + the term would be hidden from a role that the domain denies. One tag cannot allow this for tables + and forbid it for terms. +3. **The benefits of tags do not apply to terms.** The Domain design uses tags for three things: + inheritance from catalogs and schemas, tag-based policies, and the existing tag checks. Terms + are not under a catalog or schema. Terms have no policies. And in Step 2 terms need stricter + checks than `APPLY_TAG`. +4. **Permissions do not change by accident.** With Option B, replacing or deleting a domain's tag + silently removes its terms. In Step 2, who can see or edit them changes, but nobody edited a + term. With + Option A, membership changes only through the term API. It is checked and audited like any + other term edit, and in Step 2 it is reviewed. +5. **Smaller change to the Domain design.** Option A adds one check when a domain is dropped. + Option B makes terms taggable, adds a member type, and adds term-only rules to the shared tag + code. + +The cost: the terms of a domain are listed by `GET /terms?domain=`, not by +`GET /domains/{domain}/objects`. Both use the same rules: a term can be in several domains, and a +domain includes its subdomains. + +### Bindings + +A binding links a term to the data behind it. A term page shows two kinds of bindings. An object +page shows the terms linked to the object. + +| Kind | Meaning | Targets | Example | +| ------------------ | ---------------------------------------------- | --------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | +| **Implemented by** | The object stores or computes the term | `CATALOG`, `SCHEMA`, `TABLE`, `VIEW`, `COLUMN`, `FILESET`, `TOPIC`, `MODEL` | `Customer` is implemented by table `sales.public.customers` and column `customers.customer_id` | +| **Used by** | A semantic-model metric is built from the term | `METRIC`, identified by its existing `metric_id` | metric `net_revenue` uses `Net revenue` and `Order` | + +**Column scope in Step 1**: `COLUMN` means a table column. Resolve its identity as +`catalog.schema.table.column`, using the table and column IDs, and authorize through that table. +The endpoint fence is metalake -> catalog -> schema -> table, followed by the existing column +identity check. Table alteration fences column changes and cleans up removed-column bindings; +table/column renames preserve the IDs and bindings. A COLUMN lookup whose parent resolves only +as a view returns 404; do not reinterpret a view as a table. View-column bindings are outside +Step 1. Binding a view itself remains supported, but `children=true` on a view returns 400. + +Both kinds are stored in `glossary_term_binding`, using the target's own stable ID: + +- `target_type` identifies one of the eight Implemented by asset types, or `METRIC` for Used by. + This is a binding-specific type; it does not add `METRIC` to `MetadataObject.Type`. +- `target_id` is the asset's ID, the stable column ID for `COLUMN` (not a version-row ID), or the + existing `semantic_model_metric_meta.metric_id` for `METRIC`. It is never the containing + semantic-model ID for a metric binding. The containing table or semantic model is resolved + from the target identity for authorization, endpoint locking and cleanup. +- All columns of `(term_id, target_type, target_id, deleted_at)` are `NOT NULL`, with + `deleted_at = 0` for a live row. This key prevents duplicate bindings on H2, MySQL and PostgreSQL + without nullable fields, empty-string markers or metric names in the key. +- REST and client inputs still identify a metric by semantic model and exact metric name. The + server resolves that input to a live metric ID before binding. Responses resolve the ID back + to its current model/name; the existing `TermBindingDTO` and MCP argument shapes are unchanged. + +A binding is direct only: binding a table does not bind its columns. `glossary_term_rel` stores +term-to-term relations; `glossary_term_binding` stores term-to-asset and term-to-metric bindings. + +- There is no semantic view type in Gravitino. A semantic view from another system (for example + Snowflake) is stored as a semantic model, so its metrics use Used by. + +**One write endpoint, two ways to be allowed** + +Bindings are written on the object, the same as tags and policies: +`POST /objects/{type}/{fullName}/terms`, or `POST /objects/semantic_model/{fullName}/metrics/{metric}/terms` +for a metric. Two kinds of people know about a binding: + +- the object admin knows what the object means; +- the term owner knows which data implements the term. + +Both can write bindings. The server checks each term in the request separately: + +| Caller | Needs | Terms allowed | +| ------------ | ---------------------------------------------------------------- | ------------------------------------------------- | +| Object admin | Admin privilege on the object, and `VIEW_DEFINITION` on the term | `APPROVED` only | +| Term editor | Edit privilege on the term, and read access to the object | Any status, so a draft can get its bindings early | + +- **Admin privilege on an object**: + - tables and columns: the existing `MODIFY_TABLE_AUTHORIZATION_EXPRESSION` (owner of the table or + of a parent, or `MODIFY_TABLE` with `USE_CATALOG` and `USE_SCHEMA`); + - views: the existing `VIEW_OWNER_AUTHORIZATION_EXPRESSION` (owner of the view or of a parent); + - metrics: `MODIFY_SEMANTIC_MODEL_AUTHORIZATION_EXPRESSION`; + - other types have no modify privilege, so the caller must own the object or one of its parents + (metalake, catalog, schema). +- The endpoint checks the object once, and then checks each term in the request body in code. + A missing or hidden term returns 404 before checking its status. For a visible term, allow the + term-editor path in any status, even when the caller is also an object admin. Otherwise, an + object admin can use only `APPROVED` terms; another status returns 400. A caller satisfying + neither authorization path gets 403. Failure on any term rejects the whole request and + changes nothing. Removing a binding uses the same checks as adding it. +- Each changed term gets a new revision and goes through `TermChangeHandler`. So the Step 2 workflow + can hold a binding change, like any other term change. +- Binding a missing object or metric fails with 404. Binding any other object type fails with 400. + The status restriction on the object-admin path applies only after term visibility is checked + and only when the term-editor path does not allow the operation. +- When a term is deprecated later, it keeps its bindings. It no longer shows in lookups or MCP + results. + +**Reads** + +- `GET /terms/{term}/objects?kind=IMPLEMENTED_BY|USED_BY&types=` lists the bindings of a term. It + first checks read access to the root term, then returns only objects and metrics the caller + can access (`filterMetadataObject`). A table column requires read access to its table. A metric + requires read access to its semantic model. +- `GET /objects/{type}/{fullName}/terms` and `GET /objects/semantic_model/{fullName}/metrics/{metric}/terms` + first authorize reading the target using its ordinary metadata-read expression, then list only + terms the caller can see. For COLUMN, authorize its table; for a metric, authorize its semantic + model and verify the metric exists. Glossary VIEW or MANAGE never replaces target access. + Insufficient target read access returns 403, and a missing target returns 404, with no terms, + child names or counts in the error. Check target access before enumerating children or reading + their bindings. Reuse `LOAD_TABLE_AUTHORIZATION_EXPRESSION` for tables and table columns, + `LOAD_VIEW_AUTHORIZATION_EXPRESSION` for views, `LOAD_SEMANTIC_MODEL_AUTHORIZATION_EXPRESSION` + for models' metrics, and the existing load expression for each other supported type. +- `?children=true` on a table or semantic model also returns the terms of each table column or + metric that has readable terms. A schema tab or a metric table then loads in one call, not one + call per column. On the server it is one query on `glossary_term_binding`, by the table and its + column IDs. For a semantic model, resolve its live metric IDs in a batch and query bindings + with `target_type = METRIC` and those IDs; do not query one metric at a time. Other types, + including VIEW, reject `children=true` with 400. Views still support listing their own terms + with no children. + +**Cleanup** + +- Dropping an object soft-deletes its bindings. This happens in the same places that clean up + `tag_relation_meta` (by object, schema, catalog and metalake). Renames keep the bindings, because + bindings use IDs. +- Dropping a column in `alterTable` soft-deletes the bindings of the column, in the same + transaction. +- Metrics already have internal IDs. When a semantic model is altered, clean up bindings by + `target_type = METRIC` and the retired metric IDs. Reuse the existing metric identity lifecycle: + content edits and semantic-model renames preserve a metric ID; removing a metric retires its ID. + A metric rename is currently removal of the old name and addition of the new name, with a new + ID: its old bindings are removed and must be linked again. Reintroducing a removed name also + gets a new ID and must not revive old bindings. The cleanup writes one audit record per + affected term, listing its ID and name, the semantic-model ID and name, the retired metric IDs + and names, the triggering alter operation and the resulting term revision. This also applies + to metric removal without a rename; bindings are never silently transferred to a new identity. +- Every surviving term that loses bindings gets one revision increment in the same transaction + as the object change and binding cleanup, even if it loses several bindings. Unaffected terms + do not change. The transaction locks all affected term rows in ID order before deleting the + bindings (see Locking). Failure rolls back the object change, bindings and revisions together, + with no successful cleanup audit record. + +### Status and versions + +| Status | Who can see it | Who can delete it | +| -------------------- | ---------------------------------------------------------------- | -------------------- | +| `DRAFT` | owner with `CREATE_DEFINITION`, or `MANAGE_DEFINITIONS`; not MCP | `MANAGE_DEFINITIONS` | +| `APPROVED` (default) | `VIEW_DEFINITION`; MCP also requires this privilege | `MANAGE_DEFINITIONS` | +| `DEPRECATED` | `VIEW_DEFINITION`; not MCP | `MANAGE_DEFINITIONS` | + +- **Status is an ordinary field.** It is set in the create request (default `APPROVED`) or with + `setStatus` in the update request. Anyone who can edit the term can set it: the owner with + `CREATE_DEFINITION`, or `MANAGE_DEFINITIONS`. There are no transition rules and no separate + status endpoint. +- **What `APPROVED` means in Step 1**: the term can be used by agents. It does not mean that a + reviewer accepted it. Creation defaults to this status and makes the term immediately visible + to callers with read access. Content edits to an `APPROVED` term also take effect immediately. + An owner with CREATE can explicitly create a draft, or set any status on an existing own term; + MANAGE can do the same for any term. Neither action is an approval decision or requires a + reviewer in Step 1. Step 2 introduces review separately. +- **Delete** requires `MANAGE_DEFINITIONS` in every status, including `APPROVED`. Being the owner + with CREATE never permits deletion, even after changing a term back to `DRAFT`. Deprecation + before deletion is optional. MANAGE is an administration privilege in Step 1, not an approval + privilege. +- **Why three states**: each term is used on its own. `DRAFT` keeps a term away from agents while + it is written. Bindings and people keep using a term after it is replaced, so `DEPRECATED` keeps + it readable, which a delete cannot do. In Step 2, `APPROVED` also records that a reviewer + accepted the term. A domain or an ontology (#14310) is published as a whole and has no review per + item, so `DRAFT` / `PUBLISHED` is enough there. +- **Every API applies the same term-read authorization** (REST, clients, MCP); MCP additionally + excludes non-`APPROVED` terms. If the caller cannot see a term, lists leave it out and get + returns 404. The same rule applies inside responses. The `broader`, + `narrower` and `related` lists of a term, the terms of an object, and the terms of a domain all + leave out terms the caller cannot see. So a hidden draft never shows up as a relation. +- **Known leaks**: hiding a term does not make it secret. A user can still find out that it exists + in two ways: creating a term with the same name returns 409, and adding a synonym equal to its + name returns 400. +- **Revision**: each change to the name, definition, synonyms, links, properties, relations, + domains, bindings or status increases `current_version` by one, in the same transaction. + Responses return it as `version`, so a client can see that a term changed after it read it. + Owner and tag changes are only audited. +- **Cleanup revisions**: deleting a term, object, column or metric also increments each surviving + term that loses a broader relation, a `RELATED` relation or a binding. Each affected term gets + exactly one increment per cleanup transaction, regardless of the number of removed rows, and + an audit record of the losses with its resulting revision. A change to a derived `narrower` + list alone does not increment the parent, just as adding or removing a broader relation only + changes the child. Terms deleted in the same transaction need no increment. No-op cleanup + changes no revisions; failed cleanup commits neither losses nor revision increments. These + are required cleanup effects, applied with the endpoint deletion rather than left pending for + review in Step 2. +- **No snapshots in Step 1**: the audit log holds the change record. There is no history API. + `glossary_term_version_info` is created with the other tables, but Step 1 writes no rows to it. + Term reads and writes do not need it. A revision is not an approved version. +- **Workflow hook**: `GlossaryManager` sends every change to a `TermChangeHandler`: content, status, + relations, domains, and both binding paths. The default handler applies the change at once. In + Step 2, a review handler keeps the proposed change apart from the live tables until it is + approved. +- Dropping a term soft-deletes its synonyms, relations, domain links, bindings and version rows, in + the same transaction. Dropping a metalake soft-deletes all its glossary rows in + `MetalakeMetaService#deleteMetalake`, next to the tag cleanup. + +### Access control + +In Step 1, the three privileges are granted on the metalake: + +| Action | `VIEW_DEFINITION` | `CREATE_DEFINITION` | `MANAGE_DEFINITIONS` | +| --------------------------------------------------------- | ----------------- | ------------------- | -------------------- | +| Read `APPROVED` and `DEPRECATED` terms; look up words | ✓ | ✓ | ✓ | +| Create a term (the creator becomes the owner) | | ✓ | ✓ | +| See own `DRAFT` terms | | ✓ | ✓ | +| See other users' `DRAFT` terms | | | ✓ | +| Edit, bind and set the status of own terms, in any status | | ✓ | ✓ | +| Edit, bind and set the status of any term | | | ✓ | +| Delete any term, in any status | | | ✓ | + +- `MANAGE_DEFINITIONS` includes `CREATE_DEFINITION`, and `CREATE_DEFINITION` includes + `VIEW_DEFINITION`. The names are general, so other business-definition objects can use them too. +- **Owner versus any term**: `CREATE_DEFINITION` lets a user write and maintain their own terms. + `MANAGE_DEFINITIONS` lets an admin read, edit and delete any term. Ownership means the current + owner, including group members, not necessarily the original creator. Changing status is an + ordinary edit in Step 1; CREATE and MANAGE have no separate approval capability. Step 2 adds + submission and review, including reviewer authorization and no self-approval. +- **Read privilege on a term**: `VIEW_DEFINITION` for `APPROVED` and `DEPRECATED`; for `DRAFT`, + `MANAGE_DEFINITIONS`, or being the owner with `CREATE_DEFINITION`. CREATE alone gives no access + to another owner's draft. Apply this rule to direct gets, lists and every nested term result. +- **Edit privilege on a term**, used by Relations, Domain membership and Bindings: + `MANAGE_DEFINITIONS`, or being the owner with `CREATE_DEFINITION`. +- **Delete privilege on a term**: `MANAGE_DEFINITIONS` only, independent of status or ownership. +- **Registration**: three new `Privilege.Name` values. In Step 1 their `canBindTo` accepts + `METALAKE` only. The role APIs return 400 when these privileges are granted on any other object, + or when anything is granted on `GLOSSARY_TERM`. Step 2 adds `DOMAIN`. +- **Deny** works as for other privileges: expand the allowed grant implications above, then + apply explicit denies to each required capability. Every glossary operation requires effective + VIEW, so denying VIEW blocks both reads and writes, even for a term owner. Creating requires + effective CREATE; editing uses effective MANAGE or the owner-with-effective-CREATE path; + deleting requires effective MANAGE. A deny on MANAGE removes the all-term path, but leaves + effective CREATE usable on own terms. The metalake owner always passes. +- **Bindings** are written on the object, by the object admin (`APPROVED` terms only) or by the + term editor. See Bindings. +- **Owner** (a user or a group), set through `/owners/glossary_term/{term}`. When a group owns a + term, all its members count as the owner. To change the owner, the caller must be the current + owner, or have `MANAGE_GRANTS` on the metalake. +- **Create** needs `CREATE_DEFINITION` on the metalake, and `USE_DOMAIN` on each domain in the + request. The creator becomes the owner. +- **Implementation**: add shared glossary authorization checks for effective VIEW, CREATE and + MANAGE on the metalake, and for reading, editing and deleting a term using the rules above. + REST endpoints and request-body checks use these same checks. Do not use + `JcasbinAuthorizer#hasMetadataPrivilegePermission` as the term-edit check: it controls managing + grants and ownership, not glossary content. Owner-transfer and role-grant APIs retain their + existing authorization; MANAGE does not grant `MANAGE_GRANTS`. In Step 2, a `TermScopeResolver` + adds the domains of a term, and their parents, as more levels of the glossary checks. + +### Locking + +Before writing, plan the locks for the whole request, including every update in an alter and +every relation and domain in a create. Acquire their union using the existing store tools, +always in this order: + +1. the live-endpoint fence (`LiveEndpointService.lockLiveEndpoint`, shared): the metalake, plus the + chain of the bound object when binding; +2. the per-metalake hierarchy lock, if needed; +3. term rows, in ID order (exclusive); +4. domain rows (shared). + +Each row is locked only once, in its final mode. Do not process updates one by one and acquire a +hierarchy lock after a term lock. Once locked, reread and validate the current state, apply all +updates in one transaction, and hold the locks until commit or rollback. If a reread shows that +the plan needs an earlier lock or an additional term row that would break ID order, roll back +and rebuild the plan before writing. + +| Operation | Locks | Conflict it prevents | +| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- | +| Create, including initial relations and domains | metalake (shared) -> hierarchy lock -> referenced terms (exclusive, ID order) -> domains (shared) | name/synonym conflict; invalid relations; endpoint drop | +| Rename or change synonyms | metalake (shared) -> hierarchy lock -> term (exclusive) | name/synonym conflict; concurrent edits | +| Edit other content, status or domains | metalake (shared) -> term (exclusive) -> added domains (shared) | concurrent edits; endpoint drop | +| Add or remove a relation | metalake (shared) -> hierarchy lock -> all referenced terms (exclusive, ID order) -> added domains (shared), if any | a cycle or overlap; endpoint drop; mixed alters | +| Bind / unbind | object chain (`lockLiveEndpoint`, shared) -> terms (exclusive, ID order) | object drop; concurrent term edits | +| Delete a term | metalake (shared) -> hierarchy lock -> deleted and affected surviving terms (exclusive, ID order) | new links; lost cleanup revisions | +| Object, column or metric cleanup | endpoint locks in the deleting or altering operation's final mode -> affected surviving terms (exclusive, ID order) | new bindings; lost cleanup revisions | + +For an alter that combines rows of this table, use the union of locks in the global order. For +example, rename plus `addBroader` plus `addDomain` takes the metalake fence, hierarchy lock, the +edited and referenced terms in ID order, then the added domain rows. Create with relations locks +the existing referenced terms before inserting the new term and its relations. Relation cleanup +finds the affected surviving terms after taking the hierarchy lock; binding cleanup finds them +after taking the endpoint deletion or alteration locks, which must exclude concurrent binding +writes. A metalake drop deletes all its terms, so there are no surviving terms to increment. + +- The **hierarchy lock** is a `SELECT … FOR UPDATE` on one row per metalake in + `glossary_hierarchy_lock`. The row is inserted on first use. Locking only the two terms is not + enough. Example: A → B and C → D are added at the same time, then B → C and D → A. Each link + passes its own check, but together they form a cycle. Every relation change and term delete + takes this lock. Every create, rename and synonym change also takes it, so checking names in + `glossary_term_meta` and synonyms in `glossary_term_synonym` cannot race. These writes run one + at a time per metalake; other content edits do not take this lock. +- Name/synonym checks and hierarchy walks run after the lock is taken and read the latest + committed state, including a transaction that committed while this request waited for the + lock. They must not reuse an earlier transaction snapshot or a MyBatis cached result. If a term + was deleted before the lock was taken, the server sees that when it locks the term row, and + returns 404. +- For operations by name, the server finds the row by name, locks it, and then checks the name and + `deleted_at` again. If they changed, it returns 404. The unique key on the name protects + concurrent creates (409). + +### REST API + +All paths are under `/api/metalakes/{metalake}`. They follow the Tag, Policy and Domain APIs: + +- a top-level `/terms` collection (there is no glossary container, so no `/glossary` level); +- `?details=` on lists; +- `PUT` with a list of updates to alter, including the status; +- `DropResponse` on delete; +- bindings are written on the object. + +| Operation | Endpoint | Request -> response | +| ---------------------- | -------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | +| List, filter, match | `GET /terms?details=&domain=&status=&nameContains=&match=&bindings=` | -> `NameListResponse` / `TermListResponse` | +| Create | `POST /terms` | `TermCreateRequest` -> `TermResponse` | +| Get | `GET /terms/{term}?status=` | -> `TermResponse` | +| Alter | `PUT /terms/{term}` | `TermUpdatesRequest` -> `TermResponse` | +| Drop | `DELETE /terms/{term}` | -> `DropResponse` | +| Hierarchy | `GET /terms/{term}/hierarchy?direction=BROADER\|NARROWER&status=` | -> `TermTreeResponse` | +| Bindings of a term | `GET /terms/{term}/objects?kind=&types=&status=` | -> `TermBindingListResponse` | +| Terms of an object | `GET /objects/{type}/{fullName}/terms?details=&children=&status=` | -> `NameListResponse` / `ObjectTermsResponse` | +| Bind / unbind | `POST /objects/{type}/{fullName}/terms` | `TermsAssociateRequest{termsToAdd, termsToRemove}` -> `NameListResponse` | +| Terms of a metric | `GET /objects/semantic_model/{fullName}/metrics/{metric}/terms?details=&status=` | -> `NameListResponse` / `TermListResponse` | +| Bind / unbind a metric | `POST /objects/semantic_model/{fullName}/metrics/{metric}/terms` | `TermsAssociateRequest` -> `NameListResponse` | +| Owner | existing `/owners/glossary_term/{term}` | | +| Tags | existing `/objects/glossary_term/{term}/tags` | | + +``` +TermCreateRequest { name, definition, synonyms, status?, domains, broader, related, links, + sourceRef, properties } +TermUpdatesRequest { updates: [rename, updateDefinition, setStatus, addSynonym, removeSynonym, + addDomain, removeDomain, addBroader, removeBroader, addRelated, + removeRelated, updateLinks, setSourceRef, setProperty, removeProperty] } +TermDTO { name, definition, synonyms, status, domains, broader, narrower, related, + links, owner, sourceRef, properties, version, audit, + matchedBy?: [{word, field: NAME | SYNONYM}], + bindings?: [TermBindingDTO], bindingsTruncated? } +TermBindingDTO { kind: IMPLEMENTED_BY | USED_BY, object: MetadataObjectDTO, metric? } +ObjectTermsResponse { terms: [TermDTO], children: [{ name, terms: [TermDTO] }] } +TermsAssociateRequest { termsToAdd: [name], termsToRemove: [name] } +``` + +- **Status filtering on reads**: `status` is optional on the term collection, get, hierarchy, + term-binding and reverse object/metric GET endpoints. With no filter, return any term the + caller is allowed to read. With a filter, apply both + authorization and that status to all terms: roots, list items, `broader`, `narrower`, `related`, + hierarchy nodes and terms inside object/metric responses. A named root that is hidden, missing + or in another status returns 404, including on `/terms/{term}/objects`, even though that + response contains only bindings. A list omits nonmatching terms; a hierarchy stops at each + nonmatching or hidden node and does not traverse through it. An invalid status returns 400. + Read root status and response data from one consistent database snapshot, using one query or + a read transaction for multiple queries. Do not check status in a separate request and then + fetch unguarded bindings or relations. This requires no write locks; each response reflects + its read snapshot, and later requests can observe subsequent status changes. +- **Domain filtering on responses**: every occurrence of a term uses the domain visibility rule + in Domain membership, including terms embedded by hierarchy, object and metric endpoints. +- **List** is used both to browse and to look up words: + - `domain` returns the terms of the domain and of the subdomains the caller can see. + - `nameContains` finds names that contain the text, ignoring case. It is for search boxes. + - `match` looks up business words: one `match` per word, up to 20. Each word is looked up on its + own, and a term is returned when it matches any word (OR). The server compares `key(word)` + with `name_key` and `synonym_key`. Each returned term has `matchedBy`. With + `status=APPROVED`, a word that only matches `DEPRECATED` terms returns nothing. + - `bindings=true` adds at most 20 authorized bindings per term. Apply target-read authorization + before the limit: collect up to 21 visible bindings, return the first 20, and set + `bindingsTruncated` only when a 21st visible binding exists. Hidden bindings do not consume + the limit or affect the flag. A query may fetch candidates in batches, but must continue + through hidden rows until it finds 21 visible bindings or exhausts the candidates. It only Review Comment: Agreed. Inline binding expansion has a 1,000-candidate per-term budget and a 10,000-authorization-candidate lookup-request budget. Hidden candidates consume work, while the 20-visible-binding limit and bindingsTruncated retain their original meaning. If completion or the 21st visible binding cannot be established within budget, return typed 400 LookupTooBroadException, without partial success, hidden counts or target identities. For the full binding endpoint, a hard total cap would leave a legitimate term with 1,001 TABLE bindings permanently unreadable. It therefore returns bounded cursor pages: at most 1,000 candidates scanned and 100 authorized results per call, with continuation even when a page contains only hidden candidates. Cursors bind term identity/revision and filters; every page rechecks authorization. MCP exposes one page per call and never presents a continuing/abandoned page as complete. Definition-only lookup remains available, still subject to its overall budget. T12.9, T13.13/T13.14, client page tests and T16.9/T16.10 cover the consumer behavior. Updated design: [158ae1b688](https://github.com/apache/gravitino/pull/14239/commits/158ae1b688648b04e5b2f34f248d0e0d8e235e04). These are requirements for implementation PRs, not claims that runtime tests have already passed. ########## design-docs/glossary-design.md: ########## @@ -0,0 +1,1661 @@ +<!-- + 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. +--> + +# Design: Business Glossary + +| Version | Author | Date | Status | +| ------- | ------ | ---------- | ------ | +| 0.6 | Qi Yu | 2026-11-09 | Draft | + +## Background + +Gravitino knows where data lives: catalogs, schemas and tables. With Domains +(apache/gravitino#13867), it also knows the business area of the data. But it does not know what a +business word means. Words like "Active Customer" or "Net Revenue" are defined in wikis and BI +tools. Each user and each agent maps the word to tables and metrics in its own way. Nobody owns the +definition. + +A business glossary solves this. It is a managed list of **terms**. Each term has a definition, +synonyms, an owner and a status. Terms are grouped by domain and by a parent-child hierarchy. A term +is linked to the columns, tables and metrics behind it. An agent can look up a word from a question, +find the approved term, and follow its links to the data. + +The glossary is built in two steps. **Step 1** is this design: terms, relations, bindings, status, +privileges on the metalake, APIs and agent lookup. **Step 2** adds review of changes, version +history and grants on domains. Implementation Steps lists what each step contains. + +## Goals + +1. **Term object**: a `GlossaryTerm` under the metalake. It has a name, definition, synonyms, owner, + status, domains, documentation links, properties and an optional source reference. There is no + glossary container. Domains and the term hierarchy group the terms. Terms can carry tags through + the existing tag APIs. +2. **Hierarchy**: a term can have several broader (parent) terms, in any domain. Narrower (child) + terms come from the other side. `RELATED` links two terms both ways. The server rejects cycles. +3. **Bindings**: a term can be linked to catalogs, schemas, tables, views, columns, filesets, + topics and models (where the data is), and to semantic-model metrics (what is computed from it). + Column bindings in Step 1 support table columns only; views themselves can be bound. A term + lists its objects, and an object lists its terms. A binding never gives access to data. +4. **Domains**: a term belongs to zero or more domains. A domain is optional when a term is + created. In Step 1, domains group and filter terms. They do not change who can see or manage a + term. +5. **Status**: `DRAFT`, `APPROVED` or `DEPRECATED`. New terms are `APPROVED`. Anyone who can edit a + term can set its status, in the create or update call. There are no transition rules. Agents + only see `APPROVED` terms they can read. Step 1 has no approval decision; `APPROVED` means + available for agent use. +6. **Privileges**: `VIEW_DEFINITION`, `CREATE_DEFINITION` and `MANAGE_DEFINITIONS`, granted on the + metalake. CREATE permits creation and maintenance of own terms; MANAGE permits reading, + editing and deleting any term, without an approval role in Step 1. Drafts are visible only to + their owner with CREATE and to MANAGE. Deny wins over allow. REST and MCP use the same rules. +7. **Revisions**: every content change increases the revision number of the term, and is audited. + There are no content snapshots and no history API in Step 1. +8. **APIs**: REST, Java and Python clients, read-only MCP tools, events and audit. Each view of the + glossary page needs one or two REST calls. An agent can look up all business words of a question + in one call. + +## Non-Goals + +1. **Approval workflow, version history and grants on domains**: these come in Step 2 (see + Implementation Steps). In Step 1, edits take effect at once. Step 2 plugs in through + `TermChangeHandler` (see Status and versions). +2. **CSV import/export in Step 1, external connectors and SKOS export**: Step 1 provides APIs + and a source reference for future importers. CSV is retained as Step 2 task S2.6, not dropped + from the feature plan. External connectors and SKOS export remain later work. +3. **Ranked, fuzzy or semantic lookup in Step 1**: Step 1 only matches names and synonyms exactly + (ignoring case and extra spaces). This is enough for words that the glossary defines. Better + matching can come later without an API change: `matchedBy` can get new values (for example + `FUZZY` or `SEMANTIC`) and a score, and `resolve_business_term` keeps the same input and output. +4. **Access through terms**: a term or a binding never gives or blocks access to data. Terms have + no policies. +5. **Agent writes and the UI itself**: the MCP tools are read-only. The UI uses the REST API. Web UI + support lists the calls for each part of the page. + +## Delivery Scope and Tracking + +This is a design PR. T1–T19 describe future implementation work, not runtime functionality +delivered by merging this document. [Issue #14238](https://github.com/apache/gravitino/issues/14238) +also lists design requirements assigned to Step 2, including CSV import/export. The scope is: + +| Requirement in #14238 | Step 1 design | Later work and tracking | +| ------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ------------------------------------------------------------------- | +| Terms, explicit domain membership, hierarchy, asset/metric bindings, REST, clients and exact MCP lookup | Covered by this document and T1–T19; membership uses selected Option A | Step 2 extends the same identities and live store | +| Definition grants on domains | Metalake grants only | S2.3: domain grants and inherited authorization | +| Version snapshots and history | Revision and audit only; no snapshots | S2.2: approved snapshots, history and diffs | +| Independent review and no self-approval | No review; default APPROVED and immediate edits | S2.1: proposed changes, reviewer authorization and no self-approval | +| CSV import/export | No CSV endpoint or format; APIs and source references are prerequisites only | S2.6: a separate CSV design and implementation task | + +Until the remaining design requirements are accepted or explicitly split into linked follow-up +issues, #14238 remains open. The PR description should use `Related to #14238`, rather than +`Fixes #14238`. The S2 task IDs below track the deferred scope locally; they are not GitHub issue +numbers. Filing the follow-up issues and linking them from #14238 is still a separate step. +CSV remains planned, with its scope tracked in S2.6. + +## Usage Scenario + +1. An admin with `MANAGE_DEFINITIONS` on the metalake creates term `Customer` in domain Sales. New + terms are `APPROVED`, so users with `VIEW_DEFINITION` can see it at once. +2. An analyst with `CREATE_DEFINITION` on the metalake creates `Active Customer` with status + `DRAFT`, so agents do not use it yet. Its broader term is `Customer` and its synonym is + `active user`. The analyst links it to column `dw.sales.customers.is_active` (Implemented by). +3. When the definition is ready, the analyst sets `Active Customer` to `APPROVED`. The analyst owns + this term, so the analyst can edit it and set its status. The analyst cannot edit `Customer`. +4. The owner of semantic model `dw.sales.sales_model` links its metric `active_customers` to + `Active Customer`. The term now shows the metric under Used by. +5. A user asks an agent for "net revenue from VIP active users last month". The agent picks the + business words and calls `resolve_business_term(["net revenue", "VIP", "active user"])` once: + - `active user` returns `Active Customer` (matched by synonym), with its column and metric. + `net revenue` returns `Net revenue`, with its metric. The result only contains what the user + can read. + - `VIP` has no match. The agent asks the user what VIP means. It does not guess a column. + + Then the agent loads the table or the semantic model with the existing tools. The full flow is + in Agent integration. +6. Later the term is replaced. The owner or the admin can set it to `DEPRECATED`, and agents stop + seeing it. The admin can delete it in any status; deprecation is optional before deletion. + +## Design + +### Data model + +``` +GlossaryTerm { id, name, definition, synonyms[], status: DRAFT | APPROVED | DEPRECATED, + links[{label, url}], sourceRef?, properties, currentVersion, audit_info } + // tags: the existing tag relation tables +TermRelation { fromTermId, toTermId, type: BROADER | RELATED, audit_info } +TermDomain { termId, domainId, audit_info } // Option A in Domain membership +TermBinding { termId, targetId, targetType, audit_info } +TermVersion { termId, version, state, snapshot, audit_info } // created now; rows from Step 2 +``` + +| Table | Unique key | Other index | +| ---------------------------- | ------------------------------------------------------------------------------ | ---------------------------------------- | +| `glossary_term_meta` | `(metalake_id, name_key, deleted_at)`, `(metalake_id, source_ref, deleted_at)` | | +| `glossary_term_synonym` | `(term_id, synonym_key, deleted_at)` | `(metalake_id, synonym_key, deleted_at)` | +| `glossary_term_rel` | `(from_term_id, to_term_id, rel_type, deleted_at)` | `(to_term_id, rel_type)` | +| `glossary_term_domain_rel` | `(term_id, domain_id, deleted_at)` | `(domain_id)` | +| `glossary_term_binding` | `(term_id, target_type, target_id, deleted_at)` | `(target_type, target_id)` | +| `glossary_term_version_info` | `(term_id, version, deleted_at)` | `(term_id, state)` | + +- The tables are added to the H2, MySQL and PostgreSQL schemas and to the `upgrade-1.3.0-to-2.0.0` + scripts. +- **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 + name on every database. Responses return the name as the user typed it. Names follow the tag and + domain rules: up to 128 characters, and `/` is allowed (URL-encoded in paths). +- **Synonyms** are stored one per row, with `synonym_key = key(synonym)`. Two terms can share a + synonym. A synonym cannot be the name of another term. The server checks this in both + directions: when a synonym is added, and when a term is created or renamed (400). Create, rename + and synonym changes take the same per-metalake hierarchy lock before checking (see Locking). +- **Documentation links** (a label and a URL) are shown on the term page. They are stored in a JSON + column of `glossary_term_meta`. No query reads inside them. +- **Source reference** is optional. When set, it is unique in the metalake. It records where an + imported term came from, in the form `<system>:<id>`, for example + `datahub:urn:li:glossaryTerm:Customer`. A new import can then update the term instead of creating + a copy. A term without a source reference was created in Gravitino. +- `MetadataObject.Type.GLOSSARY_TERM` is added for owners, tags, events and audit. Privileges + **cannot be granted on a single term**: the role APIs reject them. +- Terms, relations and bindings are not cached. Every request reads the store, the same as for + domains. + +### Relations + +- `BROADER` is stored on the child. A → B means "A is a kind of B". Narrower terms are not stored; + the server finds them from the `BROADER` rows. `RELATED` is stored once per pair (with + `from_term_id < to_term_id`) and shows on both terms. +- Setting the broader or related term of A only changes A. The caller needs the edit privilege on A + and read access to the other term, including its draft visibility check (see Access control). +- **Cycle check**: adding A → B fails with 400 if B already reaches A through `BROADER` links. The + server walks up from B, level by level, under the hierarchy lock (see Locking). A term cannot be + its own parent. +- **Depth limit**: a `BROADER` chain has at most `L` links, where `L` is the release depth-limit + constant in `GlossaryManager`. A new link that makes a chain longer fails with 400. This bounds + the cycle check and the hierarchy read. 20 is the provisional value; T18 in Testing selects the + final release value. Boundary tests use the loaded limit, not the provisional number. +- **No overlap**: two terms cannot be `RELATED` if one is an ancestor of the other. Adding such a + `RELATED` link, or a `BROADER` link that creates such a pair, fails with 400. This follows the + SKOS rule. For a new `RELATED` pair, check ancestry in both directions. Before adding A → B, + collect A and all its descendants, and B and all its ancestors. Reject the link if any + `RELATED` pair crosses these two sets, regardless of how that pair is stored. For example, + 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 + 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. +- Deprecating a term does not change its children. Deleting a term removes its links. Each child + that loses a parent, and each surviving term that loses a `RELATED` link, gets one revision + increment and its own audit record in the cleanup transaction (see Status and versions). The + child keeps its other parents, or becomes a top-level term. + +How other systems store term relations: + +| System | Where relations are stored | Parents per term | Cycle check | +| ---------------- | ---------------------------------------------- | ---------------- | ------------------- | +| DataHub | a list of outgoing links on the source term | one term group | not documented | +| OpenMetadata | one shared relation table for all entities | one | tree, so not needed | +| Apache Atlas | edges in a graph database | many (`isA`) | self-link only | +| Gravitino Domain | `DomainRel { parentId, childId }` edge table | one, one level | not needed | +| This design | `glossary_term_rel` edge table, like DomainRel | many, any depth | yes, under a lock | + +All of them store one direction and derive the other. The only new part here is many parents at +any depth. That is why this design needs the cycle check and the hierarchy lock. + +### Domain membership + +A term belongs to zero or more domains. In Step 1 the definition privileges are granted on the +metalake only, so a domain groups and filters terms but does not change who can see or manage them. +In Step 2, domains also become the scope of grants (see Implementation Steps). Then membership +decides who manages a term. **Decision: Option A, explicit relations.** Jerry selected it in the +[November 9 review](https://github.com/apache/gravitino/pull/14239#discussion_r4512415347), and +the author acknowledged the choice. Step 1 and Step 2 use this single membership source. +Backing tags (Option B) are retained under [Alternatives Considered](#alternatives-considered), +not as an implementation prerequisite. + +**Selected design: explicit relation (Option A)** + +- A table `glossary_term_domain_rel (term_id, domain_id)`. Only the term API changes it: `domains` + on create, `addDomain` and `removeDomain`. These changes go through `TermChangeHandler`, like any + term change. +- To add a term to a domain, the caller needs the edit privilege on the term, and must be able to + see the domain (`USE_DOMAIN`). In Step 2, the caller also needs `CREATE_DEFINITION` on that + domain, so nobody can move a term into a domain where they cannot write. +- **Terms of a domain** (`GET /terms?domain=`) use the same scope as the Domain design: terms in + the domain, and terms in its subdomains that the caller can see. +- **Domains in a response**: every `TermDTO.domains` contains only domains the caller can see + through the ordinary domain-read check (`USE_DOMAIN`). Apply this to direct gets, list and + lookup results, nested terms, and create/alter responses. A readable term remains readable + even if some or all of its domains are hidden; its returned domain list can be empty. Filtering + a response never changes stored membership or reveals a hidden-domain count. +- Dropping a domain that still has terms fails with 409 `NonEmptyDomainException`. This is the same + as a domain with subdomains. Removing the terms silently would change how they are grouped, and in + Step 2 who manages them. The change is one more check in `DomainManager#dropDomain`. +- **Descriptive tags** on terms use the existing tag APIs and `APPLY_TAG`. A tag on a term never + changes its domains, even when the tag backs a domain. + +**Rationale for Option A.** Most reasons are about Step 2: + +1. **In Step 2, the domain decides who can read and manage a term.** For an asset, being in a domain + gives nobody any permission. That is why the Domain design lets anyone with `APPLY_TAG` add an + asset. It is also why the Domain design does not allow access grants on domains. Terms are the + opposite case: in Step 2, the grants on a term's domains decide who can see, edit and approve + it. With Option B, adding a tag would change these permissions. +2. **Tag permissions go to other people.** In the Domain design, admins give `APPLY_TAG` on a + domain's tag to the owners of the tables in that domain. With Option B in Step 2, any of these + table owners could move a term into the domain. The domain admins would then control the term. Or + the term would be hidden from a role that the domain denies. One tag cannot allow this for tables + and forbid it for terms. +3. **The benefits of tags do not apply to terms.** The Domain design uses tags for three things: + inheritance from catalogs and schemas, tag-based policies, and the existing tag checks. Terms + are not under a catalog or schema. Terms have no policies. And in Step 2 terms need stricter + checks than `APPLY_TAG`. +4. **Permissions do not change by accident.** With Option B, replacing or deleting a domain's tag + silently removes its terms. In Step 2, who can see or edit them changes, but nobody edited a + term. With + Option A, membership changes only through the term API. It is checked and audited like any + other term edit, and in Step 2 it is reviewed. +5. **Smaller change to the Domain design.** Option A adds one check when a domain is dropped. + Option B makes terms taggable, adds a member type, and adds term-only rules to the shared tag + code. + +The cost: the terms of a domain are listed by `GET /terms?domain=`, not by +`GET /domains/{domain}/objects`. Both use the same rules: a term can be in several domains, and a +domain includes its subdomains. + +### Bindings + +A binding links a term to the data behind it. A term page shows two kinds of bindings. An object +page shows the terms linked to the object. + +| Kind | Meaning | Targets | Example | +| ------------------ | ---------------------------------------------- | --------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | +| **Implemented by** | The object stores or computes the term | `CATALOG`, `SCHEMA`, `TABLE`, `VIEW`, `COLUMN`, `FILESET`, `TOPIC`, `MODEL` | `Customer` is implemented by table `sales.public.customers` and column `customers.customer_id` | +| **Used by** | A semantic-model metric is built from the term | `METRIC`, identified by its existing `metric_id` | metric `net_revenue` uses `Net revenue` and `Order` | + +**Column scope in Step 1**: `COLUMN` means a table column. Resolve its identity as +`catalog.schema.table.column`, using the table and column IDs, and authorize through that table. +The endpoint fence is metalake -> catalog -> schema -> table, followed by the existing column +identity check. Table alteration fences column changes and cleans up removed-column bindings; +table/column renames preserve the IDs and bindings. A COLUMN lookup whose parent resolves only +as a view returns 404; do not reinterpret a view as a table. View-column bindings are outside +Step 1. Binding a view itself remains supported, but `children=true` on a view returns 400. + +Both kinds are stored in `glossary_term_binding`, using the target's own stable ID: + +- `target_type` identifies one of the eight Implemented by asset types, or `METRIC` for Used by. + This is a binding-specific type; it does not add `METRIC` to `MetadataObject.Type`. +- `target_id` is the asset's ID, the stable column ID for `COLUMN` (not a version-row ID), or the + existing `semantic_model_metric_meta.metric_id` for `METRIC`. It is never the containing + semantic-model ID for a metric binding. The containing table or semantic model is resolved + from the target identity for authorization, endpoint locking and cleanup. +- All columns of `(term_id, target_type, target_id, deleted_at)` are `NOT NULL`, with + `deleted_at = 0` for a live row. This key prevents duplicate bindings on H2, MySQL and PostgreSQL + without nullable fields, empty-string markers or metric names in the key. +- REST and client inputs still identify a metric by semantic model and exact metric name. The + server resolves that input to a live metric ID before binding. Responses resolve the ID back + to its current model/name; the existing `TermBindingDTO` and MCP argument shapes are unchanged. + +A binding is direct only: binding a table does not bind its columns. `glossary_term_rel` stores +term-to-term relations; `glossary_term_binding` stores term-to-asset and term-to-metric bindings. + +- There is no semantic view type in Gravitino. A semantic view from another system (for example + Snowflake) is stored as a semantic model, so its metrics use Used by. + +**One write endpoint, two ways to be allowed** + +Bindings are written on the object, the same as tags and policies: +`POST /objects/{type}/{fullName}/terms`, or `POST /objects/semantic_model/{fullName}/metrics/{metric}/terms` +for a metric. Two kinds of people know about a binding: + +- the object admin knows what the object means; +- the term owner knows which data implements the term. + +Both can write bindings. The server checks each term in the request separately: + +| Caller | Needs | Terms allowed | +| ------------ | ---------------------------------------------------------------- | ------------------------------------------------- | +| Object admin | Admin privilege on the object, and `VIEW_DEFINITION` on the term | `APPROVED` only | +| Term editor | Edit privilege on the term, and read access to the object | Any status, so a draft can get its bindings early | + +- **Admin privilege on an object**: + - tables and columns: the existing `MODIFY_TABLE_AUTHORIZATION_EXPRESSION` (owner of the table or + of a parent, or `MODIFY_TABLE` with `USE_CATALOG` and `USE_SCHEMA`); + - views: the existing `VIEW_OWNER_AUTHORIZATION_EXPRESSION` (owner of the view or of a parent); + - metrics: `MODIFY_SEMANTIC_MODEL_AUTHORIZATION_EXPRESSION`; + - other types have no modify privilege, so the caller must own the object or one of its parents + (metalake, catalog, schema). +- The endpoint checks the object once, and then checks each term in the request body in code. + A missing or hidden term returns 404 before checking its status. For a visible term, allow the + term-editor path in any status, even when the caller is also an object admin. Otherwise, an + object admin can use only `APPROVED` terms; another status returns 400. A caller satisfying + neither authorization path gets 403. Failure on any term rejects the whole request and + changes nothing. Removing a binding uses the same checks as adding it. +- Each changed term gets a new revision and goes through `TermChangeHandler`. So the Step 2 workflow + can hold a binding change, like any other term change. +- Binding a missing object or metric fails with 404. Binding any other object type fails with 400. + The status restriction on the object-admin path applies only after term visibility is checked + and only when the term-editor path does not allow the operation. +- When a term is deprecated later, it keeps its bindings. It no longer shows in lookups or MCP + results. + +**Reads** + +- `GET /terms/{term}/objects?kind=IMPLEMENTED_BY|USED_BY&types=` lists the bindings of a term. It + first checks read access to the root term, then returns only objects and metrics the caller + can access (`filterMetadataObject`). A table column requires read access to its table. A metric + requires read access to its semantic model. +- `GET /objects/{type}/{fullName}/terms` and `GET /objects/semantic_model/{fullName}/metrics/{metric}/terms` + first authorize reading the target using its ordinary metadata-read expression, then list only + terms the caller can see. For COLUMN, authorize its table; for a metric, authorize its semantic + model and verify the metric exists. Glossary VIEW or MANAGE never replaces target access. + Insufficient target read access returns 403, and a missing target returns 404, with no terms, + child names or counts in the error. Check target access before enumerating children or reading + their bindings. Reuse `LOAD_TABLE_AUTHORIZATION_EXPRESSION` for tables and table columns, + `LOAD_VIEW_AUTHORIZATION_EXPRESSION` for views, `LOAD_SEMANTIC_MODEL_AUTHORIZATION_EXPRESSION` + for models' metrics, and the existing load expression for each other supported type. +- `?children=true` on a table or semantic model also returns the terms of each table column or + metric that has readable terms. A schema tab or a metric table then loads in one call, not one + call per column. On the server it is one query on `glossary_term_binding`, by the table and its + column IDs. For a semantic model, resolve its live metric IDs in a batch and query bindings + with `target_type = METRIC` and those IDs; do not query one metric at a time. Other types, + including VIEW, reject `children=true` with 400. Views still support listing their own terms + with no children. + +**Cleanup** + +- Dropping an object soft-deletes its bindings. This happens in the same places that clean up + `tag_relation_meta` (by object, schema, catalog and metalake). Renames keep the bindings, because + bindings use IDs. +- Dropping a column in `alterTable` soft-deletes the bindings of the column, in the same + transaction. +- Metrics already have internal IDs. When a semantic model is altered, clean up bindings by + `target_type = METRIC` and the retired metric IDs. Reuse the existing metric identity lifecycle: + content edits and semantic-model renames preserve a metric ID; removing a metric retires its ID. + A metric rename is currently removal of the old name and addition of the new name, with a new + ID: its old bindings are removed and must be linked again. Reintroducing a removed name also + gets a new ID and must not revive old bindings. The cleanup writes one audit record per + affected term, listing its ID and name, the semantic-model ID and name, the retired metric IDs + and names, the triggering alter operation and the resulting term revision. This also applies + to metric removal without a rename; bindings are never silently transferred to a new identity. +- Every surviving term that loses bindings gets one revision increment in the same transaction + as the object change and binding cleanup, even if it loses several bindings. Unaffected terms + do not change. The transaction locks all affected term rows in ID order before deleting the + bindings (see Locking). Failure rolls back the object change, bindings and revisions together, + with no successful cleanup audit record. + +### Status and versions + +| Status | Who can see it | Who can delete it | +| -------------------- | ---------------------------------------------------------------- | -------------------- | +| `DRAFT` | owner with `CREATE_DEFINITION`, or `MANAGE_DEFINITIONS`; not MCP | `MANAGE_DEFINITIONS` | +| `APPROVED` (default) | `VIEW_DEFINITION`; MCP also requires this privilege | `MANAGE_DEFINITIONS` | +| `DEPRECATED` | `VIEW_DEFINITION`; not MCP | `MANAGE_DEFINITIONS` | + +- **Status is an ordinary field.** It is set in the create request (default `APPROVED`) or with + `setStatus` in the update request. Anyone who can edit the term can set it: the owner with + `CREATE_DEFINITION`, or `MANAGE_DEFINITIONS`. There are no transition rules and no separate + status endpoint. +- **What `APPROVED` means in Step 1**: the term can be used by agents. It does not mean that a + reviewer accepted it. Creation defaults to this status and makes the term immediately visible + to callers with read access. Content edits to an `APPROVED` term also take effect immediately. + An owner with CREATE can explicitly create a draft, or set any status on an existing own term; + MANAGE can do the same for any term. Neither action is an approval decision or requires a + reviewer in Step 1. Step 2 introduces review separately. +- **Delete** requires `MANAGE_DEFINITIONS` in every status, including `APPROVED`. Being the owner + with CREATE never permits deletion, even after changing a term back to `DRAFT`. Deprecation + before deletion is optional. MANAGE is an administration privilege in Step 1, not an approval + privilege. +- **Why three states**: each term is used on its own. `DRAFT` keeps a term away from agents while + it is written. Bindings and people keep using a term after it is replaced, so `DEPRECATED` keeps + it readable, which a delete cannot do. In Step 2, `APPROVED` also records that a reviewer + accepted the term. A domain or an ontology (#14310) is published as a whole and has no review per + item, so `DRAFT` / `PUBLISHED` is enough there. +- **Every API applies the same term-read authorization** (REST, clients, MCP); MCP additionally + excludes non-`APPROVED` terms. If the caller cannot see a term, lists leave it out and get + returns 404. The same rule applies inside responses. The `broader`, + `narrower` and `related` lists of a term, the terms of an object, and the terms of a domain all + leave out terms the caller cannot see. So a hidden draft never shows up as a relation. +- **Known leaks**: hiding a term does not make it secret. A user can still find out that it exists + in two ways: creating a term with the same name returns 409, and adding a synonym equal to its + name returns 400. +- **Revision**: each change to the name, definition, synonyms, links, properties, relations, + domains, bindings or status increases `current_version` by one, in the same transaction. + Responses return it as `version`, so a client can see that a term changed after it read it. + Owner and tag changes are only audited. +- **Cleanup revisions**: deleting a term, object, column or metric also increments each surviving + term that loses a broader relation, a `RELATED` relation or a binding. Each affected term gets + exactly one increment per cleanup transaction, regardless of the number of removed rows, and + an audit record of the losses with its resulting revision. A change to a derived `narrower` + list alone does not increment the parent, just as adding or removing a broader relation only + changes the child. Terms deleted in the same transaction need no increment. No-op cleanup + changes no revisions; failed cleanup commits neither losses nor revision increments. These + are required cleanup effects, applied with the endpoint deletion rather than left pending for + review in Step 2. +- **No snapshots in Step 1**: the audit log holds the change record. There is no history API. + `glossary_term_version_info` is created with the other tables, but Step 1 writes no rows to it. + Term reads and writes do not need it. A revision is not an approved version. +- **Workflow hook**: `GlossaryManager` sends every change to a `TermChangeHandler`: content, status, + relations, domains, and both binding paths. The default handler applies the change at once. In + Step 2, a review handler keeps the proposed change apart from the live tables until it is + approved. +- Dropping a term soft-deletes its synonyms, relations, domain links, bindings and version rows, in + the same transaction. Dropping a metalake soft-deletes all its glossary rows in + `MetalakeMetaService#deleteMetalake`, next to the tag cleanup. + +### Access control + +In Step 1, the three privileges are granted on the metalake: + +| Action | `VIEW_DEFINITION` | `CREATE_DEFINITION` | `MANAGE_DEFINITIONS` | +| --------------------------------------------------------- | ----------------- | ------------------- | -------------------- | +| Read `APPROVED` and `DEPRECATED` terms; look up words | ✓ | ✓ | ✓ | +| Create a term (the creator becomes the owner) | | ✓ | ✓ | +| See own `DRAFT` terms | | ✓ | ✓ | +| See other users' `DRAFT` terms | | | ✓ | +| Edit, bind and set the status of own terms, in any status | | ✓ | ✓ | +| Edit, bind and set the status of any term | | | ✓ | +| Delete any term, in any status | | | ✓ | + +- `MANAGE_DEFINITIONS` includes `CREATE_DEFINITION`, and `CREATE_DEFINITION` includes + `VIEW_DEFINITION`. The names are general, so other business-definition objects can use them too. +- **Owner versus any term**: `CREATE_DEFINITION` lets a user write and maintain their own terms. + `MANAGE_DEFINITIONS` lets an admin read, edit and delete any term. Ownership means the current + owner, including group members, not necessarily the original creator. Changing status is an + ordinary edit in Step 1; CREATE and MANAGE have no separate approval capability. Step 2 adds + submission and review, including reviewer authorization and no self-approval. +- **Read privilege on a term**: `VIEW_DEFINITION` for `APPROVED` and `DEPRECATED`; for `DRAFT`, + `MANAGE_DEFINITIONS`, or being the owner with `CREATE_DEFINITION`. CREATE alone gives no access + to another owner's draft. Apply this rule to direct gets, lists and every nested term result. +- **Edit privilege on a term**, used by Relations, Domain membership and Bindings: + `MANAGE_DEFINITIONS`, or being the owner with `CREATE_DEFINITION`. +- **Delete privilege on a term**: `MANAGE_DEFINITIONS` only, independent of status or ownership. +- **Registration**: three new `Privilege.Name` values. In Step 1 their `canBindTo` accepts + `METALAKE` only. The role APIs return 400 when these privileges are granted on any other object, + or when anything is granted on `GLOSSARY_TERM`. Step 2 adds `DOMAIN`. +- **Deny** works as for other privileges: expand the allowed grant implications above, then + apply explicit denies to each required capability. Every glossary operation requires effective + VIEW, so denying VIEW blocks both reads and writes, even for a term owner. Creating requires + effective CREATE; editing uses effective MANAGE or the owner-with-effective-CREATE path; + deleting requires effective MANAGE. A deny on MANAGE removes the all-term path, but leaves + effective CREATE usable on own terms. The metalake owner always passes. +- **Bindings** are written on the object, by the object admin (`APPROVED` terms only) or by the + term editor. See Bindings. +- **Owner** (a user or a group), set through `/owners/glossary_term/{term}`. When a group owns a + term, all its members count as the owner. To change the owner, the caller must be the current + owner, or have `MANAGE_GRANTS` on the metalake. +- **Create** needs `CREATE_DEFINITION` on the metalake, and `USE_DOMAIN` on each domain in the + request. The creator becomes the owner. +- **Implementation**: add shared glossary authorization checks for effective VIEW, CREATE and + MANAGE on the metalake, and for reading, editing and deleting a term using the rules above. + REST endpoints and request-body checks use these same checks. Do not use + `JcasbinAuthorizer#hasMetadataPrivilegePermission` as the term-edit check: it controls managing + grants and ownership, not glossary content. Owner-transfer and role-grant APIs retain their + existing authorization; MANAGE does not grant `MANAGE_GRANTS`. In Step 2, a `TermScopeResolver` + adds the domains of a term, and their parents, as more levels of the glossary checks. + +### Locking + +Before writing, plan the locks for the whole request, including every update in an alter and +every relation and domain in a create. Acquire their union using the existing store tools, +always in this order: + +1. the live-endpoint fence (`LiveEndpointService.lockLiveEndpoint`, shared): the metalake, plus the + chain of the bound object when binding; +2. the per-metalake hierarchy lock, if needed; +3. term rows, in ID order (exclusive); +4. domain rows (shared). + +Each row is locked only once, in its final mode. Do not process updates one by one and acquire a +hierarchy lock after a term lock. Once locked, reread and validate the current state, apply all +updates in one transaction, and hold the locks until commit or rollback. If a reread shows that +the plan needs an earlier lock or an additional term row that would break ID order, roll back +and rebuild the plan before writing. + +| Operation | Locks | Conflict it prevents | +| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- | +| Create, including initial relations and domains | metalake (shared) -> hierarchy lock -> referenced terms (exclusive, ID order) -> domains (shared) | name/synonym conflict; invalid relations; endpoint drop | +| Rename or change synonyms | metalake (shared) -> hierarchy lock -> term (exclusive) | name/synonym conflict; concurrent edits | +| Edit other content, status or domains | metalake (shared) -> term (exclusive) -> added domains (shared) | concurrent edits; endpoint drop | +| Add or remove a relation | metalake (shared) -> hierarchy lock -> all referenced terms (exclusive, ID order) -> added domains (shared), if any | a cycle or overlap; endpoint drop; mixed alters | +| Bind / unbind | object chain (`lockLiveEndpoint`, shared) -> terms (exclusive, ID order) | object drop; concurrent term edits | +| Delete a term | metalake (shared) -> hierarchy lock -> deleted and affected surviving terms (exclusive, ID order) | new links; lost cleanup revisions | +| Object, column or metric cleanup | endpoint locks in the deleting or altering operation's final mode -> affected surviving terms (exclusive, ID order) | new bindings; lost cleanup revisions | + +For an alter that combines rows of this table, use the union of locks in the global order. For +example, rename plus `addBroader` plus `addDomain` takes the metalake fence, hierarchy lock, the +edited and referenced terms in ID order, then the added domain rows. Create with relations locks +the existing referenced terms before inserting the new term and its relations. Relation cleanup +finds the affected surviving terms after taking the hierarchy lock; binding cleanup finds them +after taking the endpoint deletion or alteration locks, which must exclude concurrent binding +writes. A metalake drop deletes all its terms, so there are no surviving terms to increment. + +- The **hierarchy lock** is a `SELECT … FOR UPDATE` on one row per metalake in + `glossary_hierarchy_lock`. The row is inserted on first use. Locking only the two terms is not + enough. Example: A → B and C → D are added at the same time, then B → C and D → A. Each link + passes its own check, but together they form a cycle. Every relation change and term delete + takes this lock. Every create, rename and synonym change also takes it, so checking names in + `glossary_term_meta` and synonyms in `glossary_term_synonym` cannot race. These writes run one + at a time per metalake; other content edits do not take this lock. +- Name/synonym checks and hierarchy walks run after the lock is taken and read the latest + committed state, including a transaction that committed while this request waited for the + lock. They must not reuse an earlier transaction snapshot or a MyBatis cached result. If a term + was deleted before the lock was taken, the server sees that when it locks the term row, and + returns 404. +- For operations by name, the server finds the row by name, locks it, and then checks the name and + `deleted_at` again. If they changed, it returns 404. The unique key on the name protects + concurrent creates (409). + +### REST API + +All paths are under `/api/metalakes/{metalake}`. They follow the Tag, Policy and Domain APIs: + +- a top-level `/terms` collection (there is no glossary container, so no `/glossary` level); +- `?details=` on lists; +- `PUT` with a list of updates to alter, including the status; +- `DropResponse` on delete; +- bindings are written on the object. + +| Operation | Endpoint | Request -> response | +| ---------------------- | -------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | +| List, filter, match | `GET /terms?details=&domain=&status=&nameContains=&match=&bindings=` | -> `NameListResponse` / `TermListResponse` | +| Create | `POST /terms` | `TermCreateRequest` -> `TermResponse` | +| Get | `GET /terms/{term}?status=` | -> `TermResponse` | +| Alter | `PUT /terms/{term}` | `TermUpdatesRequest` -> `TermResponse` | +| Drop | `DELETE /terms/{term}` | -> `DropResponse` | +| Hierarchy | `GET /terms/{term}/hierarchy?direction=BROADER\|NARROWER&status=` | -> `TermTreeResponse` | +| Bindings of a term | `GET /terms/{term}/objects?kind=&types=&status=` | -> `TermBindingListResponse` | +| Terms of an object | `GET /objects/{type}/{fullName}/terms?details=&children=&status=` | -> `NameListResponse` / `ObjectTermsResponse` | +| Bind / unbind | `POST /objects/{type}/{fullName}/terms` | `TermsAssociateRequest{termsToAdd, termsToRemove}` -> `NameListResponse` | +| Terms of a metric | `GET /objects/semantic_model/{fullName}/metrics/{metric}/terms?details=&status=` | -> `NameListResponse` / `TermListResponse` | +| Bind / unbind a metric | `POST /objects/semantic_model/{fullName}/metrics/{metric}/terms` | `TermsAssociateRequest` -> `NameListResponse` | +| Owner | existing `/owners/glossary_term/{term}` | | +| Tags | existing `/objects/glossary_term/{term}/tags` | | + +``` +TermCreateRequest { name, definition, synonyms, status?, domains, broader, related, links, + sourceRef, properties } +TermUpdatesRequest { updates: [rename, updateDefinition, setStatus, addSynonym, removeSynonym, + addDomain, removeDomain, addBroader, removeBroader, addRelated, + removeRelated, updateLinks, setSourceRef, setProperty, removeProperty] } +TermDTO { name, definition, synonyms, status, domains, broader, narrower, related, + links, owner, sourceRef, properties, version, audit, + matchedBy?: [{word, field: NAME | SYNONYM}], + bindings?: [TermBindingDTO], bindingsTruncated? } +TermBindingDTO { kind: IMPLEMENTED_BY | USED_BY, object: MetadataObjectDTO, metric? } +ObjectTermsResponse { terms: [TermDTO], children: [{ name, terms: [TermDTO] }] } +TermsAssociateRequest { termsToAdd: [name], termsToRemove: [name] } +``` + +- **Status filtering on reads**: `status` is optional on the term collection, get, hierarchy, + term-binding and reverse object/metric GET endpoints. With no filter, return any term the + caller is allowed to read. With a filter, apply both + authorization and that status to all terms: roots, list items, `broader`, `narrower`, `related`, + hierarchy nodes and terms inside object/metric responses. A named root that is hidden, missing + or in another status returns 404, including on `/terms/{term}/objects`, even though that + response contains only bindings. A list omits nonmatching terms; a hierarchy stops at each + nonmatching or hidden node and does not traverse through it. An invalid status returns 400. + Read root status and response data from one consistent database snapshot, using one query or + a read transaction for multiple queries. Do not check status in a separate request and then + fetch unguarded bindings or relations. This requires no write locks; each response reflects + its read snapshot, and later requests can observe subsequent status changes. +- **Domain filtering on responses**: every occurrence of a term uses the domain visibility rule + in Domain membership, including terms embedded by hierarchy, object and metric endpoints. +- **List** is used both to browse and to look up words: + - `domain` returns the terms of the domain and of the subdomains the caller can see. + - `nameContains` finds names that contain the text, ignoring case. It is for search boxes. + - `match` looks up business words: one `match` per word, up to 20. Each word is looked up on its + own, and a term is returned when it matches any word (OR). The server compares `key(word)` + with `name_key` and `synonym_key`. Each returned term has `matchedBy`. With + `status=APPROVED`, a word that only matches `DEPRECATED` terms returns nothing. + - `bindings=true` adds at most 20 authorized bindings per term. Apply target-read authorization + before the limit: collect up to 21 visible bindings, return the first 20, and set + `bindingsTruncated` only when a 21st visible binding exists. Hidden bindings do not consume + the limit or affect the flag. A query may fetch candidates in batches, but must continue + through hidden rows until it finds 21 visible bindings or exhausts the candidates. It only + works together with `match` and `details=true`. A lookup then needs only one REST call. A word + usually matches one to three terms. + - Why not a separate path like `/terms/resolve`? It would clash with a term named `resolve`. So + lookup is a filter of the list. +- **Alter** applies all updates in one transaction and increases the revision once. `narrower` is + computed and cannot be set. `version` is the current revision. `updateLinks` replaces the whole + link list. `status` defaults to `APPROVED` on create. +- **Terms of an object**: `children=true` works on `table` and `semantic_model` after target-read + authorization. It adds one entry to `children` for each table column or metric with terms + passing the authorization and optional status filter. A semantic model itself has no terms; + only its metrics do. A view supports its own terms, without `children=true`. +- **Bind / unbind** use the same request format as tag association. The response is the object's + terms after the change. +- **Errors**: + - 404: `NoSuchTermException` (missing, hidden, or a named root excluded by the status filter), + `NoSuchMetadataObjectException`; + - 409: `TermAlreadyExistsException` (same name or same source reference), `NonEmptyDomainException`; + - 400: a cycle, a term as its own parent, binding an unsupported object type, a synonym equal to + another term's name, an object admin binding a visible non-`APPROVED` term without the + term-editor path, invalid `status`, `children=true` on an unsupported type, or more than 20 + `match` values; + - 403: `ForbiddenException`. +- **Concurrency**: changes apply to the current state, and the last write wins, the same as other Review Comment: Accepted the optional conditional-edit guard. The design uses expectedRevision, copied from the returned opaque revisionToken, rather than an integer expectedVersion alone. A per-term integer resets on same-name recreation: a stale editor could otherwise overwrite a different term that also has version 1. The token identifies the metalake, term identity and revision, while numeric version remains for display. Under the term lock, authorize and compare identity/revision before updates or no-op detection. Mismatch returns 409 TermVersionConflictException without writes or success events; hidden/missing roots remain 404. Omission retains unconditional editing. Clients must preserve the condition or fail before writes, and reconcile rather than automatically replay. T4.18 includes two-editor list replacement, stale no-ops, deletion/recreation, rename/name reuse and cross-metalake tokens; client tests preserve the token end to end. Updated design: [158ae1b688](https://github.com/apache/gravitino/pull/14239/commits/158ae1b688648b04e5b2f34f248d0e0d8e235e04). These are requirements for implementation PRs, not claims that runtime tests have already passed. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
