jerryshao commented on code in PR #15067: URL: https://github.com/apache/gravitino/pull/15067#discussion_r4676891120
########## design-docs/gravitino-kb-article-design.md: ########## @@ -0,0 +1,1095 @@ +<!-- + 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 Articles to Terms and metadata objects, and list Articles by bound + Term or asset. 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, target filters 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. Term and asset + filters select 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. See +[Lists and search](#lists-and-search) for the Term and asset filters. + +| Article status | Ordinary reads | Lists filtered by Term or asset | 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 + usual Article create or edit authority and effective `MANAGE_DOMAIN` on every added or + removed Domain. Compute changes from the full stored set, so a caller cannot remove an unseen + membership by submitting only the filtered response. Without `expectedRevision`, concurrent + replacements run sequentially and the later replacement wins. Returned Domain lists apply + the ordinary visibility checks (`USE_DOMAIN` and draft visibility) without revealing hidden + names or counts. +- A Domain administrator can explicitly detach a named Article from that Domain through the + detach endpoint with effective `MANAGE_DOMAIN`. The operation changes only that membership + and does not require Article edit permission. It advances the Article revision once and + records the actor on an effective change. A missing membership is a no-op. +- `GET /domains/{domain}/definition-members` requires effective `MANAGE_DOMAIN` on the + requested Domain. It lists live, directly assigned Article and Term members, including + hidden drafts. Each entry contains only `type` (`KNOWLEDGE_BASE_ARTICLE` or `GLOSSARY_TERM`) + and the current `name`. Content reads use the respective Article and Term permissions. + Query `domain_member_rel` by Domain, resolve live names by member type and ID, and order + by `(member_type, member_id)` before paging. This list uses the same `limit`, `offset` and + `hasMore` rules as other lists below. +- Domain deletion follows the existing authorization, status and subdomain checks. An authorized + attempt to delete a `PUBLISHED` Domain returns `400` with an instruction to unpublish it first. + Once a `DRAFT` Domain passes those checks, check `domain_member_rel` for any live member type + under the same Domain lock, using the shared Domain lookup index. A remaining membership + returns `409 NonEmptyDomainException` without member names or counts. + The Domain administrator can use the member list to find and explicitly detach remaining + members before retrying the drop. +- Changing or deleting a backing tag does not change Article membership. + +### Bindings and target lifecycle + +| Binding | Supported targets | +| --------------- | --------------------------------------------------------------------------------- | +| Article → Term | `GLOSSARY_TERM`, by stable numeric ID | +| Article → Asset | Catalog, Schema, Table, View, table Column, Fileset, Topic, Model, Semantic Model | + +An article may have no bindings. Bindings point to object identity, not to one target version. +Article→Term, Article→Asset and Term→Asset are independent. There is no inheritance from a table +to columns or from a term to its assets. A binding may cross catalogs or Domains. + +- Adding a binding requires Article edit permission and read access to the target. A missing or + invisible target fails the complete request; no partial binding changes are stored. +- A new Term binding requires the Term to be `APPROVED`; otherwise return `409`. Check target + visibility before returning details of that conflict. Existing bindings remain if a Term + becomes `DRAFT` or `DEPRECATED`; returned Term details carry its current status. +- Add/remove sets apply atomically. Duplicate adds and absent removals are no-ops; an effective + mixed request advances the Article revision once. +- Reads resolve target identity, liveness and visibility before pagination, previews and + continuation. Missing targets are omitted even before background cleanup; unreadable live + targets remain stored, with no hidden-target counts in responses. +- Extend `OrphanedMetadataObjectRelationService` and its mappers to batch-soft-delete Article + bindings to authoritatively retired targets. Target deletion does not lock or update Articles. + Same-name replacement targets have new IDs and do not inherit old bindings. +- The sweep rechecks each relation identity and target retirement. Authorization failures, + status changes and transient catalog errors are not retirement evidence. Cleanup is idempotent, + takes no Article-row lock and does not change its revision or body; normal deleted-data GC + later reclaims retired rows. Register a liveness lookup for every supported target type. +- Table-column bindings use the registered column ID and the containing table's authorization + and endpoint fencing. Reuse platform column-identity reconciliation, including load-triggered + reconciliation; retired column bindings are filtered on read and collected asynchronously. + Concurrent external column rename has the inherited identity + limitation tracked by [#14279](https://github.com/apache/gravitino/issues/14279); this design + does not promise unconditional preservation when the platform replaces the column ID. +- Catalog cascades and other target drops use their normal endpoint lifecycle without collecting + linked Articles in the drop transaction. Delayed or failed binding cleanup does not change a + target-drop result; it is retried by the background sweep. External DDL can still succeed before + local registrations are updated. Keep existing DDL responses and platform reconciliation and + recovery behavior; a stale registration or transient catalog error must not be treated as + confirmed target retirement. A local rollback cannot undo external DDL. +- Links written in the body are ordinary text URLs, independent of bindings. Renaming a target + updates resolved binding names, but does not rewrite URLs in article text. + +Deleting an article soft-deletes its current row, bindings and Domain memberships in one +transaction. It never deletes targets. Dropping a metalake removes articles through the normal +parent lifecycle. Removing a user does not delete their articles; the metalake owner can reassign +ownership through the existing Owner API. + +### Access control + +With `gravitino.authorization.enable=false`, create Articles without an initial Owner. Direct +reads and lists without a Term or asset filter can include `DRAFT` Articles subject to their +status filters. Lists filtered by Term or asset exclude drafts, and MCP only returns +`PUBLISHED` Articles. + +When authorization is enabled, use the metalake privileges `VIEW_DEFINITION`, +`CREATE_DEFINITION` and `MANAGE_DEFINITIONS`, abbreviated VIEW, CREATE and MANAGE in this section. +`MANAGE_DEFINITIONS` implies CREATE, and CREATE implies VIEW. Expand those implications and +apply explicit Deny rules to every required capability. Article operations require effective VIEW. +The Domain definition member list and the dedicated detach endpoint are exceptions and require +effective `MANAGE_DOMAIN` on the requested Domain. Ownership never bypasses Deny on Article +operations. + +| Operation | Required authority | +| --------------------------------- | --------------------------------------------------------------------------- | +| List and load | VIEW; drafts also require current owner with CREATE, or MANAGE | +| Create | CREATE | +| Edit, set status, change bindings | Current owner with CREATE, or MANAGE | +| Change Domains in create or alter | Article create or edit authority and `MANAGE_DOMAIN` on each changed Domain | +| List Domain definition members | `MANAGE_DOMAIN` on the requested Domain | +| Detach from one Domain | `MANAGE_DOMAIN` on that Domain, through the detach endpoint | +| Delete in any status | Current owner with CREATE, or MANAGE | +| Lists filtered by Term or asset | VIEW on the Article and read access to each filter target | + +CREATE alone cannot read another owner's draft, and ownership alone cannot replace CREATE. +Use the same Article visibility rules on direct reads, Article lists, nested results and MCP. +Shared securable-object validation rejects Article as a grant scope, covering role creation, +privilege grants and subsequent updates across the generic authorization APIs. +Administrators explicitly grant VIEW to reader roles on the metalake; there is no implicit +`PUBLIC` or anonymous read grant. + +This release evaluates definition grants at the metalake, as in Glossary Step 1. Domain +membership is used for classification and filtering. When Domain-scoped grants are introduced +for Articles, use the same `*_DEFINITION` privileges, scope resolution, inheritance from +parent Domains and Deny rules as [Glossary Step 2](glossary-design.md#step-2-tasks-not-filed-yet). +Reevaluate access when Domain membership changes. + +Use the shared authorizer for Article identity, Owner and group-based checks, including its +existing lookup caches and owner-change invalidation. Ownership changes become visible across +nodes through the platform's normal cache refresh mechanism. Group membership follows the +platform's authenticated-principal freshness rules; Gravitino adds no user-to-group membership store. + +Ownership transfer uses the existing Owner API and `CAN_SET_OWNER` authorization. For a +metalake-scoped Article, the current Article owner (including members of an owner group) or +the metalake owner may transfer ownership. `MANAGE_DEFINITIONS` alone does not grant that right. +The recipient must be an existing user or group in the metalake, but need not hold +`CREATE_DEFINITION`. Transfer does not grant definition privileges: the new owner still needs +effective VIEW and CREATE to edit or read its draft. Owner changes use the existing owner +relation and audit path, without advancing the Article revision. + +Article lists, search and nested summaries use the same visibility predicate. Hidden Articles are +excluded before pagination and do not affect `hasMore`. The Domain definition member list is an +exception. To support cleanup, it returns the type and name of directly assigned members, +including hidden drafts, to callers with effective `MANAGE_DOMAIN`. Article reads still require +the usual Article permissions. Reading an Article does not authorize its targets. Lists filtered +by Term or asset check access to the target before filtering Articles. + +### Locking and writes + +When authorization is enabled, require the creator to be a registered user in the metalake. +Use `OwnerMetaService` to persist the initial Owner in the same transaction as the Article +row and its initial Domain and binding relations. An Owner write failure rolls back the +creation, including the name and relations. With authorization disabled, skip the Owner write +and the registered-creator requirement. + +Read the latest Article state and `revision` under the Article row lock. Check any supplied +`expectedRevision` under that lock before applying changes. Each effective write advances +`revision` once in the same transaction. Writes commit sequentially. Updates to different +fields and binding additions/removals preserve each other. A no-op leaves the revision unchanged +and emits no content-change success event. Validate identity and authorization before detecting a no-op. +Compare persisted values, treating memberships and bindings as sets; updates that cancel out +are a no-op. + +Plan the complete lock set before acquiring locks. Take the metalake fence first, then bound +asset endpoint chains in their established order, then Term, Domain and Article rows in that +order. Within each row type, lock by ID. This follows the Term-before-Domain order in +[Glossary locking](glossary-design.md#locking). Revalidate the resolved identities and +relation sets under the locks. If planning discovers a stale set, restart lock planning with a +bounded retry and carry the original editing token into each attempt. + +The metalake endpoint fence uses a shared lock on MySQL and PostgreSQL. H2 uses `FOR UPDATE`, +so unrelated writes that take the fence can still serialize within a metalake. + +- A membership write holds a shared Domain-row lock until commit. Domain drop takes its + exclusive lock, then checks the latest committed memberships without taking Article locks + while holding that exclusive Domain lock. A concurrent add either commits first and blocks + the drop, or fails because the Domain was dropped. A detach that commits first can let + the drop proceed. +- For the dedicated detach operation, recheck `MANAGE_DOMAIN` in the write transaction after Review Comment: #15200 now rechecks `MANAGE_DOMAIN` under the Domain lock for every membership change: create with Domains, `addDomain`, `removeDomain` and detach (Glossary T7.10 also covers a mixed alter). Article create with Domains and `updateDomains` require the same `MANAGE_DOMAIN`, so they have the same race: a concurrent Domain move can remove the inherited privilege while the write waits for the lock. Could this rule cover every Article membership change, with all checks passing before any change is applied? T5.3 could add a mixed alter case (e.g. `updateBody` plus `updateDomains`) that leaves the body, memberships and revision unchanged on `403`. -- 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]
