diqiu50 commented on code in PR #15067:
URL: https://github.com/apache/gravitino/pull/15067#discussion_r4674811915


##########
design-docs/gravitino-kb-article-design.md:
##########
@@ -0,0 +1,1064 @@
+<!--
+  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: Knowledge Base Articles
+
+## Background
+
+Gravitino manages data assets and their metadata. A [Glossary 
Term](glossary-design.md) gives a
+short definition of a business concept. Teams also need longer explanations: 
how revenue is
+calculated, why it differs from GMV, and which tables feed it. Today these 
explanations live in
+wikis and documents, apart from the terms and data they describe. Users and 
agents cannot find
+them through the same metadata APIs or follow managed links from an 
explanation to its data.
+
+A Knowledge Base (KB) Article is a text document managed under a metalake. It 
has a title, a
+Markdown or HTML body, an owner and a status. It can belong to several
+[Domains](domain-design.md) and link to terms and data assets across catalogs. 
Users and agents
+can search for an article, read it, and follow its bindings under their 
existing privileges.
+
+---
+
+## Goals
+
+1. **Article object**: add `KnowledgeBaseArticle` as metalake-scoped metadata 
with an immutable
+   name and stable numeric ID. A title can change without breaking references 
to the article.
+2. **Current content storage**: store the title and Markdown/HTML body 
directly on the Article
+   row. Edits update that current content; no historical-content copies are 
retained.
+3. **Bindings**: link an article to terms and metadata objects. Support 
reverse lookup from
+   either target. A binding never grants access to data.
+4. **Domains**: organize and filter articles by zero or more Domains. 
Membership does not change
+   article privileges in this design.
+5. **Status and privileges**: support `DRAFT`, `PUBLISHED` and `DEPRECATED`, 
with immediate edits
+   and definition privileges granted on the metalake. `PUBLISHED` makes 
content available to
+   authorized readers and agents.
+6. **Discovery**: provide basic title, synonym and body search, with Domain, 
status and owner
+   filters. Read-only MCP tools return readable `PUBLISHED` articles and
+   support progressive discovery through bindings, summaries and selected 
article reads.
+7. **APIs and governance**: provide REST, Java and Python APIs, ownership, 
events and audit.
+   Concurrent writes must not leave current content and relations out of sync.
+
+---
+
+## Non-Goals
+
+1. **Review and publication approval**: content and status changes take effect 
immediately;
+   approval workflows and review APIs are outside the scope.
+2. **Domain-scoped or Article-scoped definition grants**: this release 
supports metalake grants.
+   A reader with effective metalake `VIEW_DEFINITION` can read every published 
Article in that
+   metalake, regardless of Domain membership.
+   Domain-scoped grants will follow the shared rules described in [Access 
control](#access-control).
+3. **Web UI, collaborative editing and agent writes**: the design provides 
REST APIs and read-only
+   MCP tools. A web editor, real-time co-editing and agent writes are deferred.
+4. **File ingestion, attachments and image upload**: the body is text. It may 
contain ordinary
+   external links, but Gravitino does not host files, extract text or fetch 
linked content.
+5. **Ranked, fuzzy or semantic search and RAG**: this design provides basic 
discovery. Advanced
+   document retrieval belongs in a future integration with a dedicated 
document knowledge base;
+   the current scope adds no embedding index or answer-generation service.
+6. **Inferred or transitive bindings**: words and links in the body do not 
create bindings.
+   Binding an article to a term does not bind it to that term's assets; 
binding a table does not
+   bind its columns.
+7. **Metric bindings and version pinning**: bind a Semantic Model as an 
object, not an individual
+   metric. A binding points to the target's identity and resolves its current 
state.
+8. **Content history, comparison, rollback and article hierarchy**: only 
current content is stored
+   and exposed. There is no history table or history API. Articles form a flat 
list.
+
+---
+
+## Scope and Dependencies
+
+The design covers the following capabilities. The task references link each 
capability to its
+implementation work in [Task Breakdown](#task-breakdown).
+
+| Capability                                      | Scope                      
                      | Tasks   |
+| ----------------------------------------------- | 
------------------------------------------------ | ------- |
+| Article API, entity and storage                 | First-class metadata and 
current content         | T1–T3   |
+| Definition privileges and ownership             | Metalake grants; platform 
Owner checks           | T4      |
+| Domain membership                               | Shared member table; 
filter and drop guard       | T5      |
+| Term and asset bindings                         | Stable IDs, reverse lookup 
and lifecycle cleanup | T6      |
+| REST, editing and search                        | DTOs, errors, summaries 
and OpenAPI              | T7–T8   |
+| Events and audit                                | Existing listener and 
audit mechanisms           | T9      |
+| Java, Python and read-only MCP                  | Same contracts and 
visibility as REST            | T10–T12 |
+| Integration, upgrade, performance and user docs | Release checks and 
documented operating limits   | T13–T14 |
+
+Domain integration requires stable Domain IDs, hierarchy lookup, access checks 
and deletion
+fencing. Term bindings require stable Term IDs, current-status and 
registered-liveness lookup.
+
+Current Article title, body and metadata live directly in the Article row. 
Current Domain
+memberships and bindings use relation tables, updated with that row in one 
transaction.
+OSS retains no historical body copies, version pointers or retention 
configuration. Stable
+Article IDs, an internal revision counter and the shared transaction boundary 
support storage
+extensions without reserving history-specific columns.
+
+---
+
+## Usage Scenario
+
+1. An admin grants an analyst `CREATE_DEFINITION` and a reader 
`VIEW_DEFINITION` on a metalake.
+   The analyst can manage Domain `Finance` and read term `net-revenue` and 
table
+   `iceberg.sales.orders`.
+2. The analyst creates "Revenue Calculation Guide", with a Markdown body, 
Domain `Finance`,
+   the term and the table. The server generates a name if none is supplied. 
The analyst becomes
+   the owner; the default status is `PUBLISHED`, and its current content takes 
effect immediately.
+3. The reader searches for a word from the body and loads the article. Its 
bindings lead to
+   the current term and table; each target still requires its own read 
privilege.
+4. The analyst loads the Article, then sends its `revisionToken` as 
`expectedRevision` in one
+   alter request with `updateBody` and `addObjects`. The body and new binding 
take effect together.
+5. An agent acting as the reader calls `search_kb_articles`, then 
`get_kb_article`. It receives
+   the stored body with its format and only the bound objects it can read.
+6. To prepare content privately, the analyst can create or set the article to 
`DRAFT`. Only its
+   owner with CREATE, or a caller with MANAGE, can read it. Setting it to 
`PUBLISHED` makes it
+   available again without review.
+7. When the explanation is outdated, the owner sets it to `DEPRECATED`. It 
remains readable,
+   but agents stop returning it. The owner with CREATE or an admin with MANAGE 
can delete it
+   directly in any status. Deleting it removes neither the term nor the table.
+
+---
+
+## Design
+
+### Data model
+
+`KnowledgeBaseArticle` is directly under a metalake, alongside Tag, Policy and 
Domain. It is not
+under a catalog or schema, because an article can explain data from several 
catalogs.
+
+```text
+KnowledgeBaseArticle {
+  name, title, body: { format: MARKDOWN | HTML, content },
+  status: DRAFT | PUBLISHED | DEPRECATED, domains[], comment?, synonyms[],
+  sourceReference?, properties, audit_info, revisionToken
+}
+ArticleBinding { articleId, targetType, targetId, audit_info }
+ArticleDomain  { articleId, domainId, audit_info }
+```
+
+The Article row stores current content. Its internal `revision` is the basis 
of the editing token.
+
+- **Identity**: `metalake.articleName`. The name is immutable and unique in 
the metalake; the
+  internal numeric article ID is stable. Add `KNOWLEDGE_BASE_ARTICLE` to 
`MetadataObject.Type`
+  and `Entity.EntityType`, including the single-level object handling used by 
owner APIs.
+- **Name normalization**: use Unicode NFC for explicit and generated Article 
names before
+  storage and for every name-based lookup, including generic metadata APIs. 
Return the normalized
+  name. For example, `café` with a precomposed `é` and the spelling with `e` 
plus a combining acute
+  accent identify the same name. NFC does not change the existing case rules 
or transliterate
+  Chinese. This rule applies to Article names, not titles or body content.
+- **Explicit name**: normalize to NFC before validation. Accept 1 to 128 
Unicode code points,
+  using letters, digits, combining marks,
+  `_` and `-`, with at least one letter or digit. Reject other characters with 
`400`, including
+  `/`, backslash, whitespace and control characters. Preserve case and store 
the NFC spelling.
+- **Generated name**: `name` is optional on create. Lower-case the title using 
`Locale.ROOT`,
+  preserve Unicode letters, digits and combining marks, and replace each run 
of other characters
+  with `-`. Normalize the result to NFC, trim leading/trailing `-` and cut to 
128 Unicode code
+  points without splitting a character. Chinese text is preserved: `收入计算说明` 
becomes `收入计算说明`, and
+  `收入 Calculation Guide` becomes `收入-calculation-guide`. Do not transliterate 
to Pinyin.
+  Use `article-<shortId>` only when the result contains no Unicode letter or 
digit, such as an
+  emoji-only or punctuation-only title. The suffix is 8 random lower-case 
alphanumeric
+  characters, regenerated on collision. A derived-name collision adds `-2`, 
`-3`, and so on,
+  cutting the base further to keep the whole name within 128 code points. A 
duplicate explicit
+  name is `409`. Changing the title later never changes the generated name.
+- **Concurrent name allocation**: the unique key `(metalake_id, article_name, 
deleted_at)` is
+  the final arbiter. If a generated candidate loses a concurrent insert race 
on that key, roll
+  back the complete create transaction, choose the next available suffix (or a 
fresh random
+  fallback), and retry in a new transaction. Allow at most five retries after 
the initial
+  attempt; exhaustion returns `409`. Failed attempts leave no Article, Owner 
or relation
+  rows. Explicit-name conflicts return `409` immediately. Retry only generated 
Article-name
+  unique-key conflicts. Other failures end the attempt.
+- **Title**: required, nonblank after trimming, at most 512 Unicode code 
points. Articles can share
+  a display title within the same Domain or without a Domain. Use the 
immutable `name` to
+  address an Article. Generated names from equal titles use the normal 
collision suffixes.
+- **Owner**: when authorization is enabled, the creator becomes the initial 
owner. Owners may be
+  users or groups. Persist the relation in the existing `owner_meta` table: 
`metadata_object_id` is
+  the stable article ID, `metadata_object_type` is `KNOWLEDGE_BASE_ARTICLE`, 
and `metalake_id`
+  identifies its metalake. `owner_id` references the user or group ID and 
`owner_type` is `USER`
+  or `GROUP`; owner names are resolved from `user_meta` or `group_meta`. 
Integrate the Article
+  type with `OwnerMetaService` and the existing Owner APIs. No owner column is 
added to the
+  article tables; ownership uses its own relation and audit path.
+- **Other fields**: `comment` is at most 256 Unicode code points. `synonyms` 
are trimmed, at most 128
+  characters each and at most 20 per article; remove duplicates ignoring case. 
They need not be
+  unique across articles. `sourceReference` is optional free text of at most 
1,024 Unicode code points,
+  such as a wiki URL. It is not validated as a URL, followed or fetched. 
Render it as text unless
+  a client separately validates it as a safe link. `properties` is a string 
map.
+
+#### Generic metadata API integration
+
+Article uses the existing Owner, audit and generic relation-cleanup mechanisms 
with these
+capability boundaries:
+
+| Capability                  | Article behavior                               
                                      |
+| --------------------------- | 
------------------------------------------------------------------------------------
 |
+| Owner and audit             | Supported through the existing APIs and 
authorization rules                          |
+| Tag and Policy associations | Not supported in this scope; Article is not 
added to their supported-type allowlists |
+| Definition grants           | Metalake scope only; Article scope is rejected 
by shared grant-object validation     |
+| Orphan cleanup              | Remove generic relations left behind after 
Article deletion                          |
+
+Register `KNOWLEDGE_BASE_ARTICLE` with 
`OrphanedMetadataObjectRelationService`, using
+`kb_article_meta` and `article_id` to determine Article liveness. This clears 
residual Owner and
+other generic relations referring to a deleted Article. It is separate from 
asynchronous
+Article-to-target binding cleanup, which removes bindings whose targets were 
deleted.
+
+#### Body and input validation
+
+`body.format` is `MARKDOWN` or `HTML`, stored on the current Article. Store 
Markdown as submitted text.
+Markdown consumers render embedded HTML as escaped text. They render Markdown 
first, then sanitize
+the generated HTML with a maintained library, including inline links, 
reference links and image
+URLs; see [CommonMark rendering 
guidance](https://github.com/commonmark/commonmark-java#usage).
+For HTML input, use [OWASP Java HTML 
Sanitizer](https://owasp.org/projects/java-html-sanitizer)
+on write, removing scripts, active elements and event-handler attributes while 
preserving safe
+formatting. For both formats, sanitize the final rendered HTML before display 
and use a URL
+protocol allowlist that excludes `javascript:`, `data:` and encoded variants.
+
+Responses, including MCP, return the stored body and format. Compare stored 
values for no-op
+detection. Process body input only on create or `updateBody`; unrelated edits 
and library upgrades
+do not rewrite stored bodies.
+
+Limit both submitted and stored `body.content` by UTF-8 byte length, including 
HTML after
+sanitization. The configurable limit defaults to 1 MiB (1,048,576 bytes); 
allowed settings are
+1 through 16,777,215 bytes, the
+MySQL `MEDIUMTEXT` capacity. An invalid setting prevents startup. An oversized 
request returns
+`400`, without truncation or a stored change. Use the same bounds for create 
and alter.
+
+#### Storage
+
+Persist articles through EntityStore on H2, MySQL and PostgreSQL. Glossary T7 
introduces the
+shared `domain_member_rel` schema and mapper as a standalone storage change. 
Article T2 reuses
+them and supplies the Article tables below. Use the existing Owner and audit 
storage.
+
+| Table                      | Fields beyond common row metadata               
                                                                                
                                           | Unique key                         
                | Other index                                                   
                 |
+| -------------------------- | 
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 | -------------------------------------------------- | 
------------------------------------------------------------------------------ |
+| `kb_article_meta`          | `article_id`, `metalake_id`, `article_name`, 
`title`, `body_format`, `body_content`, `revision`, `status`, 
`article_comment`, `synonyms`, `source_reference`, `properties` | 
`(metalake_id, article_name, deleted_at)`          | Primary key: `article_id`  
                                                    |
+| `kb_article_relation_meta` | `id`, `metalake_id`, `article_id`, `target_id`, 
`target_type`                                                                   
                                           | `(article_id, target_id, 
target_type, deleted_at)` | `(target_id, target_type, deleted_at)`; 
`(metalake_id, deleted_at)`            |
+| `domain_member_rel`        | `id`, `metalake_id`, `domain_id`, 
`member_type`, `member_id`                                                      
                                                         | `(member_type, 
member_id, domain_id, deleted_at)`  | `(domain_id, deleted_at, member_type, 
member_id)`; `(metalake_id, deleted_at)` |
+
+- `kb_article_meta` has one current row per Article. Title, format and body 
are stored directly
+  on that row. Article IDs are stable and never reused, including after 
same-name recreation.
+  There is no content-version table, version pointer or historical body copy.
+- Article reads use dedicated relational queries and bypass the generic 
EntityStore cache for
+  full Article entities. Authorization lookups retain the shared authorizer's 
cache behavior.
+- Use numeric IDs, `audit_info`, `deleted_at`, and `utf8mb4_bin` on MySQL. The 
Article ID is the
+  entity primary key; relation rows have an auto-increment `id`. Relation key 
columns are non-NULL.
+- `revision` starts at 1 and advances once per effective Article edit, 
including content,
+  status, descriptive-field and explicit membership/binding changes. It tracks 
writes to the
+  current row. Failed writes, no-ops, Owner transfers and background orphan 
cleanup leave it
+  unchanged. Relation rows retain the usual store metadata columns.
+- `kb_article_relation_meta.metalake_id` is non-NULL and comes from the owning 
Article.
+  Metalake cleanup uses `(metalake_id, deleted_at)` without joining Article 
rows. Reverse lookup
+  selects live bindings through `(target_id, target_type, deleted_at)`.
+- For name, title, comment and source reference, use `VARCHAR(128)`, 
`VARCHAR(512)`,
+  `VARCHAR(256)` and `VARCHAR(1024)` respectively on MySQL and PostgreSQL. On 
H2, use
+  `VARCHAR(256)`, `VARCHAR(1024)`, `VARCHAR(512)` and `VARCHAR(2048)` 
respectively, allowing two
+  UTF-16 code units per code point. REST and the Java and Python clients use 
the same code-point
+  limits on every backend. Name length is checked after NFC normalization.
+- Use `VARCHAR(32)` for status and format and `VARCHAR(64)` for target and 
member types.
+  On MySQL, body, properties and audit JSON use `MEDIUMTEXT` and synonyms use 
`TEXT`.
+  Other databases use their native equivalents.
+- Relation rows hold current Domain memberships and bindings. DTOs resolve 
endpoint IDs to
+  current names and apply visibility filtering. Services validate and fence 
endpoints in the
+  transaction without database foreign keys.
+- `domain_member_rel` contains only memberships in real Domains. `member_type` 
is
+  `GLOSSARY_TERM` or `KNOWLEDGE_BASE_ARTICLE`. Member reads, writes and 
deletion match both
+  `member_type` and `member_id`. Validate the member and Domain against 
`metalake_id`.
+  Domain filters and nonempty checks read the membership table.
+- Add schemas and upgrade scripts for all three dialects. Use the 2.0.0 
scripts while unreleased;
+  otherwise use the next release. `IF NOT EXISTS` does not make a whole 
upgrade safely rerunnable.
+- Keep one transactional write boundary for current Article fields, relation 
changes and any
+  storage extensions. An extension can capture the old row and full relation 
sets before
+  replacement and commit its own records in that transaction, without changing 
the shared
+  Article schema. Post-commit listeners are not a substitute for transactional 
storage work.
+
+### Status and current content
+
+The ordinary-read privileges in this table apply when authorization is enabled.
+
+| Article status | Ordinary reads                       | Reverse lookup       
              | MCP      |
+| -------------- | ------------------------------------ | 
---------------------------------- | -------- |
+| `DRAFT`        | Current owner with CREATE, or MANAGE | Excluded             
              | Excluded |
+| `PUBLISHED`    | Effective VIEW                       | Included             
              | Included |
+| `DEPRECATED`   | Effective VIEW                       | Only with 
`includeDeprecated=true` | Excluded |
+
+`PUBLISHED` denotes direct publication, matching Domain terminology. New 
Articles default to it.
+Create and `updateStatus` may set any of the three statuses without an 
approval step. An Article
+can be edited or deleted in any status with the normal privileges.
+
+An edit updates the current row and changed relation sets atomically. Read the 
complete stored
+state before applying deltas, preserving unrelated fields and hidden 
memberships/bindings.
+Body replacement keeps the current Article status and becomes effective 
immediately. Ordinary
+reads use the current row and current relations. Previous body, title and 
relation states are
+not retained; audit records describe operations and do not provide content 
restoration.
+
+### Domain membership
+
+An article belongs to zero or more Domains, using `domain_member_rel` rows with
+`member_type = KNOWLEDGE_BASE_ARTICLE` and `member_id = article_id`. Terms use 
the same table with
+`member_type = GLOSSARY_TERM`. Article membership is current relation state 
and changes
+through Article operations; Term changes continue through `TermChangeHandler`. 
Sharing storage
+does not change either feature's authorization or lifecycle rules, or add a 
generic membership
+write API. Membership is independent of backing-tag assignments, so tag 
changes cannot silently
+move an article.
+
+- Requests and responses use Domain names. Resolve names to stable IDs on 
write and return the
+  current names on read. A rename changes neither membership nor stable 
identity. An unknown
+  Domain returns `404`.
+- Follow the Domain model's two levels and shared metalake namespace. A Domain 
filter includes
+  the visible requested Domain and only its subdomains readable by the caller. 
Resolve that
+  visible ID set before selecting Article candidates, pagination and 
`hasMore`; an Article
+  belonging only to hidden subdomains is excluded even if the Article itself 
is readable.
+  Domain membership is optional at creation and may change later.
+- Creating an Article with Domains or changing membership through 
`updateDomains` requires the

Review Comment:
   Glossary PR #15200 aligns Domain membership with Articles by using the 
shared `domain_member_rel` table, requiring `MANAGE_DOMAIN` for membership 
changes, and adding a Term detach endpoint for Domain administrators.



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

To unsubscribe, e-mail: [email protected]

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

Reply via email to