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


##########
design-docs/gravitino-kb-article-design.md:
##########
@@ -0,0 +1,1003 @@
+<!--
+  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**: definition 
privileges are granted on
+   the metalake. Domains group articles; they do not authorize access to an 
article.
+3. **Web UI, collaborative editing and agent writes**: the design provides 
REST APIs and read-only
+   MCP tools. A web editor, stale-editor conflict detection 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 also has access to Domain `Finance`, 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 saves a new body and another binding through one alter request 
containing
+   `updateBody` and `addObjects`.
+   Current content and changed relations take effect atomically; the response 
shows that state.
+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
+}
+ArticleBinding { articleId, targetType, targetId, audit_info }
+ArticleDomain  { articleId, domainId, audit_info }
+```
+
+The Article row stores current content. Its `revision` remains an internal CAS 
counter.
+
+- **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, not title conflicts, CAS failures or other errors.
+- **Title**: required, nonblank after trimming, at most 512 characters. 
Compare titles after
+  trimming and lower-casing with `Locale.ROOT`, independent of database 
collation. Among articles
+  that are not `DEPRECATED`, titles are unique within each directly assigned 
Domain. Articles
+  in different Domains may share a title; an article in several Domains claims 
it in each one.
+  Articles without a Domain share one title-uniqueness scope per metalake, 
separate from all
+  Domain scopes. Parent and child Domains are separate scopes. Deprecation 
releases the title
+  in its current scope(s); leaving `DEPRECATED` claims it again. A conflict is 
`409`, without revealing another article or a hidden Domain. Different
+  titles, or equal titles in separate Domains, can generate the same name, so 
generated names
+  still need collision suffixes within the metalake.
+- **Owner**: the creator becomes the owner through the existing Owner APIs. 
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 characters. `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 
1024 characters,
+  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. Use two Article-specific tables and the 
shared
+`domain_member_rel` table on H2, MySQL and PostgreSQL. Define the shared 
schema and mappers once
+for Article and Glossary; whichever feature introduces them first supplies 
them. 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`                   
                                   |

Review Comment:
   We’ll keep the body in `kb_article_meta`. Summary queries will select only 
the columns they need, and full Article entities will bypass the generic entity 
cache.



-- 
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